Skip to content

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

feat(alerts): attach insight chart to all firing Slack alerts (#95951)

posthog[bot]e7f6cbb12c53
diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
index 79316f8a4c18..004bf5f10d60 100644
--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
@@ -1331,8 +1331,8 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho
},
// 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
- // the anomaly investigation rendered one (`insight_chart_url` set by
- // investigate_anomaly_activity), otherwise the plain divider — Slack has no way to
+ // 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'}}",
{
diff --git a/posthog/tasks/alerts/investigation_notifications.py b/posthog/tasks/alerts/investigation_notifications.py
index 534e781322f5..bdb1f7b3ed38 100644
--- a/posthog/tasks/alerts/investigation_notifications.py
+++ b/posthog/tasks/alerts/investigation_notifications.py
@@ -26,7 +26,11 @@ import structlog
from posthog.schema import AlertState
-from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert_delivery
+from posthog.tasks.alerts.utils import (
+ dispatch_alert_notification,
+ prepare_alert_insight_chart_url,
+ record_alert_delivery,
+)
from products.alerts.backend.models.alert import AlertCheck, InvestigationStatus
@@ -91,13 +95,22 @@ def run_investigation_notification_safety_net() -> int:
if alert is None or not alert.enabled:
continue
+ # Rendered before the transaction opens: the render blocks for up to
+ # exports.RENDER_TIMEOUT, and the block below holds a row lock the workflow's own
+ # dispatcher waits on. A failed render returns None and the notification still goes
+ # out, just without the chart.
+ insight_chart_url = prepare_alert_insight_chart_url(alert=alert, alert_check=check)
+ extra_properties = {"insight_chart_url": insight_chart_url} if insight_chart_url else None
+
try:
with transaction.atomic():
locked = AlertCheck.objects.select_for_update().get(id=check.id)
if locked.notification_sent_at is not None or locked.notification_suppressed_by_agent:
continue
breaches = _fallback_breach_descriptions(locked)
- deliveries = dispatch_alert_notification(alert, locked, breaches)
+ deliveries = dispatch_alert_notification(
+ alert, locked, breaches, extra_properties=extra_properties, render_chart=False
+ )
record_alert_delivery(alert, locked, deliveries, stamp_on_empty=True)
except Exception:
logger.exception(
diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.py
index b4c710321855..cb8be406c48f 100644
--- a/posthog/tasks/alerts/test/test_investigation_notifications.py
+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py
@@ -212,6 +212,26 @@ class TestInvestigationNotificationSafetyNet(APIBaseTest):
assert notified == 0
mock_dispatch.assert_not_called() # type: ignore[attr-defined]
+ @patch("posthog.tasks.alerts.investigation_notifications.prepare_alert_insight_chart_url")
+ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")
+ def test_chart_is_rendered_outside_the_row_lock(self, mock_dispatch: object, mock_prepare: object) -> None:
+ # The render blocks for up to RENDER_TIMEOUT. Doing it under the select_for_update
+ # below would stall the workflow's own dispatcher for the same check.
+ mock_prepare.return_value = "https://export/chart.png?token=abc" # type: ignore[attr-defined]
+ mock_dispatch.return_value = [ # type: ignore[attr-defined]
+ AlertDelivery(channel="email", target="[email protected]", at="2026-08-11T00:00:00+00:00")
+ ]
+ self._make_check(
+ age_minutes=INVESTIGATION_NOTIFY_GRACE_MINUTES + 60,
+ investigation_status=InvestigationStatus.DONE,
+ )
+
+ run_investigation_notification_safety_net()
+
+ kwargs = mock_dispatch.call_args.kwargs # type: ignore[attr-defined]
+ assert kwargs["render_chart"] is False
+ assert kwargs["extra_properties"] == {"insight_chart_url": "https://export/chart.png?token=abc"}
+
@patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")
def test_skips_non_agent_alert(self, mock_dispatch: object) -> None:
self.alert.investigation_agent_enabled = False
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.py
index 98a382866384..3e7ece2b6bc5 100644
--- a/posthog/tasks/alerts/test/test_utils.py
+++ b/posthog/tasks/alerts/test/test_utils.py
@@ -7,13 +7,14 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
-from posthog.schema import AlertCalculationInterval
+from posthog.schema import AlertCalculationInterval, AlertState
from posthog.slo.context import SloSpec, slo_operation
from posthog.slo.types import SloArea, SloOperation, SloOutcome
from posthog.tasks.alerts.utils import (
calculation_interval_to_order,
disable_invalid_alert,
+ dispatch_alert_notification,
next_check_time,
send_notifications_for_breaches,
send_notifications_for_errors,
@@ -274,6 +275,71 @@ class TestSendNotificationsReceipts(APIBaseTest):
mock_send.assert_called_once()
+class TestDispatchAlertInsightChart(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.insight = Insight.objects.create(team=self.team, name="test insight")
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=self.insight,
+ name="test alert",
+ condition={"type": "absolute_value"},
+ created_by=self.user,
+ )
+ self.alert.subscribed_users.add(self.user)
+ self.alert_check = AlertCheck.objects.create(
+ alert_configuration=self.alert,
+ state=AlertState.FIRING,
+ calculated_value=42.0,
+ )
+
+ @patch(
+ "posthog.tasks.alerts.utils.prepare_alert_insight_chart_url",
+ return_value="https://export/chart.png?token=abc",
+ )
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
+ def test_firing_alert_attaches_rendered_chart_url(self, mock_send: MagicMock, _mock_prepare: MagicMock) -> None:
+ dispatch_alert_notification(self.alert, self.alert_check, ["Series A is below 1000"])
+
+ assert (
+ mock_send.call_args.kwargs["extra_properties"]["insight_chart_url"] == "https://export/chart.png?token=abc"
+ )
+
+ @patch("posthog.tasks.alerts.utils.prepare_alert_insight_chart_url")
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
+ def test_real_time_alert_skips_chart_render(self, mock_send: MagicMock, mock_prepare: MagicMock) -> None:
+ self.alert.calculation_interval = AlertCalculationInterval.REAL_TIME
+ self.alert.save(update_fields=["calculation_interval"])
+
+ 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
+
+ @patch("posthog.tasks.alerts.utils.prepare_alert_insight_chart_url")
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
+ def test_render_chart_false_skips_render_under_a_lock(self, _mock_send: MagicMock, mock_prepare: MagicMock) -> None:
+ # Callers holding a row lock pre-render instead; rendering here would block the
+ # lock for up to RENDER_TIMEOUT.
+ dispatch_alert_notification(self.alert, self.alert_check, ["breach"], render_chart=False)
+
+ mock_prepare.assert_not_called()
+
+ @patch("posthog.tasks.alerts.utils.prepare_alert_insight_chart_url")
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
+ def test_supplied_chart_url_is_not_re_rendered(self, mock_send: MagicMock, mock_prepare: MagicMock) -> None:
+ dispatch_alert_notification(
+ self.alert,
+ self.alert_check,
+ ["breach"],
+ extra_properties={"insight_chart_url": "https://supplied/url"},
+ )
+
+ mock_prepare.assert_not_called()
+ assert mock_send.call_args.kwargs["extra_properties"]["insight_chart_url"] == "https://supplied/url"
+
+
class TestDisableInvalidAlert(APIBaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 04b2875fdb0b..7520d71ee634 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -1,6 +1,6 @@
from collections.abc import Collection
from contextlib import ExitStack
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
from django.utils import timezone
@@ -11,6 +11,7 @@ import structlog
from posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery
from posthog.dataclasses import frozen
+from posthog.models.user import User
from posthog.ph_client import ph_background_capture
from posthog.slo.context import get_current_slo
from posthog.slo.types import SloOperation
@@ -42,11 +43,21 @@ from products.alerts.backend.scheduling import (
next_calendar_check_time,
to_calendar_interval,
)
+from products.exports.backend.facade import api as exports
logger = structlog.get_logger(__name__)
INSIGHT_ALERT_FIRING_EVENT = "$insight_alert_firing"
+# TTL for the tokenized chart URL embedded in Slack. Slack fetches the image at delivery,
+# but the URL must stay resolvable while people scroll back to the message; 30 days matches
+# the delivery-URL TTL used for task chart artifacts (products/tasks living_artifacts).
+_INSIGHT_CHART_URL_TTL = timedelta(days=30)
+
+# The stored PNG outlives its delivery URL by one day so the URL can never point at a
+# deleted asset; without an explicit TTL the format default keeps the PNG for six months.
+_INSIGHT_CHART_ASSET_TTL = timedelta(days=31)
+
@frozen
class AlertEvaluationResult:
@@ -332,12 +343,95 @@ def get_alert_error_notification_recipients(alert: AlertConfiguration) -> list[t
]
+def _inconclusive_is_suppressed(verdict: str | None, inconclusive_action: str | None) -> bool:
+ """Whether an inconclusive verdict is held back by the alert's configured policy."""
+ return verdict == "inconclusive" and (inconclusive_action or "notify") == "suppress"
+
+
+def _should_suppress_notification(verdict: str | None, inconclusive_action: str | None) -> bool:
+ """Whether the verdict holds the notification back: false positives always suppress,
+ inconclusive follows the alert's configured policy."""
+ return verdict == "false_positive" or _inconclusive_is_suppressed(verdict, inconclusive_action)
+
+
+def _resolve_alert_render_user(alert: AlertConfiguration) -> User | None:
+ """Pick the user the chart render is attributed to: the alert creator, then any
+ subscribed user, then None. The render checks this user's view access to the insight,
+ so it mirrors who the alert was set up for."""
+ if alert.created_by_id:
+ try:
+ return User.objects.get(id=alert.created_by_id)
+ except User.DoesNotExist:
+ pass
+ return alert.subscribed_users.first()
+
+
+def prepare_alert_insight_chart_url(
+ *,
+ alert: AlertConfiguration,
+ alert_check: AlertCheck,
+ user: User | None = None,
+ verdict: str | None = None,
+) -> str | None:
+ """Render the alerted insight to a PNG and mint a URL Slack can embed as an image block.
+
+ Skipped when nothing would show it: a suppressed verdict, an already-delivered check
+ (a chart added after delivery would never reach the sent message), or no active Slack
+ destination (only the Slack template renders the chart). Best-effort: on any failure
+ (render error, no viewer access for the render user, export infrastructure down) return
+ None so the notification still goes out, just without the chart.
+
+ `user` attributes the render and is checked for view access; when omitted it falls back
+ to the alert creator or a subscribed user. Pass it explicitly from a path that already
+ resolved the acting user.
+ """
+ if _should_suppress_notification(verdict, alert.investigation_inconclusive_action):
+ return None
+ render_user = user or _resolve_alert_render_user(alert)
+ if render_user is None:
+ return None
+ pending = AlertCheck.objects.filter(
+ id=alert_check.id, notification_sent_at__isnull=True, notification_suppressed_by_agent=False
+ ).exists()
+ if not pending:
+ return None
+ try:
+ destinations = list_active_alert_destinations(
+ team_id=alert.team_id, alert_id=str(alert.id), allowed_event_ids=(INSIGHT_ALERT_FIRING_EVENT,)
+ )
+ if not any(destination.destination_type == "slack" for destination in destinations):
+ return None
+ asset, content = exports.render_png_export(
+ team=alert.team,
+ created_by=render_user,
+ insight_id=alert.insight_id,
+ # System render: keep it out of the user's export listings and quota.
+ is_system=True,
+ expires_after=datetime.now(UTC) + _INSIGHT_CHART_ASSET_TTL,
+ )
+ if content is None:
+ logger.info(
+ "alerts.insight_chart_render_failed",
+ alert_id=str(alert.id),
+ asset_id=asset.id,
+ exception=asset.exception,
+ )
+ return None
+ return exports.get_delivery_image_url(
+ team_id=alert.team_id, asset_id=asset.id, expiry_delta=_INSIGHT_CHART_URL_TTL
+ )
+ except Exception:
+ logger.exception("alerts.insight_chart_render_failed", alert_id=str(alert.id))
+ return None
+
+
def dispatch_alert_notification(
alert: AlertConfiguration,
alert_check: AlertCheck,
breaches: list[str] | None,
extra_properties: dict[str, str] | None = None,
idempotency_key: str | None = None,
+ render_chart: bool = True,
) -> list[AlertDelivery] | None:
"""Route an AlertCheck to the correct notification sender.
@@ -350,6 +444,13 @@ def dispatch_alert_notification(
check. A caller that deliberately sends a second message about the same check must pass
its own key, or MessagingRecord drops that email as a duplicate of the first.
+ `render_chart` controls the Slack chart render for a FIRING check. Pass False from a
+ caller that holds an open transaction or a row lock: the render blocks for up to
+ exports.RENDER_TIMEOUT, and waiting that long under a lock stalls every other
+ dispatcher of the same check. Such a caller renders with
+ prepare_alert_insight_chart_url before it opens the transaction, then passes the URL
+ through `extra_properties`.
+
Raises:
ValueError: state is FIRING but breaches is None/empty.
AssertionError: unknown state — surfaces a missing AlertState branch loudly.
@@ -393,11 +494,27 @@ 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:
+ properties = dict(extra_properties) if extra_properties else {}
+ # 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).
+ # Real-time alerts never render here: the render is capped at
+ # exports.RENDER_TIMEOUT (90s), which outlasts the 60s notify_start_to_close
+ # of _REAL_TIME_TIMEOUTS, so a slow render would time out the whole notify
+ # activity and lose the notification it was supposed to carry.
+ if (
+ render_chart
+ and "insight_chart_url" not in properties
+ and alert.calculation_interval != AlertCalculationInterval.REAL_TIME
+ ):
+ chart_url = prepare_alert_insight_chart_url(alert=alert, alert_check=alert_check)
+ if chart_url:
+ properties["insight_chart_url"] = chart_url
+ # Only forward extra_properties when there's something to add, keeping the
+ # common threshold-alert call unchanged when nothing was attached.
+ if properties:
return send_notifications_for_breaches(
- alert, breaches, idempotency_key=key, extra_properties=extra_properties
+ alert, breaches, idempotency_key=key, extra_properties=properties
)
return send_notifications_for_breaches(alert, breaches, idempotency_key=key)
case _:
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index 8cc33cfc6f25..c9f05e6eb30a 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -10,7 +10,7 @@ import re
import json
import asyncio
from dataclasses import dataclass
-from datetime import UTC, datetime, timedelta
+from datetime import timedelta
from typing import TYPE_CHECKING, Optional
from uuid import UUID
@@ -22,7 +22,13 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.models import Team, User
-from posthog.tasks.alerts.utils import INSIGHT_ALERT_FIRING_EVENT, dispatch_alert_notification, record_alert_delivery
+from posthog.tasks.alerts.utils import (
+ _inconclusive_is_suppressed,
+ _should_suppress_notification,
+ dispatch_alert_notification,
+ prepare_alert_insight_chart_url,
+ record_alert_delivery,
+)
from posthog.temporal.ai.anomaly_investigation.charts import png_to_b64, render_series_chart
from posthog.temporal.ai.anomaly_investigation.event_provenance import alerted_series_event, describe_event_provenance
from posthog.temporal.ai.anomaly_investigation.metric_definition import describe_metric_definition
@@ -35,10 +41,8 @@ from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.utils import absolute_uri
-from products.alerts.backend.destinations import list_active_alert_destinations
from products.alerts.backend.investigation_episode import EpisodeInvestigations, episode_investigations
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
-from products.exports.backend.facade import api as exports
from products.notebooks.backend.facade import api as notebooks
from products.signals.backend.facade import api as signals
@@ -84,15 +88,6 @@ _MAX_DESCRIPTION_CHARS = 3000
# used to clip the summary teaser on a sentence boundary instead of mid-word.
_SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")
-# TTL for the tokenized chart URL embedded in Slack. Slack fetches the image at delivery,
-# but the URL must stay resolvable while people scroll back to the message; 30 days matches
-# the delivery-URL TTL used for task chart artifacts (products/tasks living_artifacts).
-_INSIGHT_CHART_URL_TTL = timedelta(days=30)
-
-# The stored PNG outlives its delivery URL by one day so the URL can never point at a
-# deleted asset; without an explicit TTL the format default keeps the PNG for six months.
-_INSIGHT_CHART_ASSET_TTL = timedelta(days=31)
-
@dataclass
class AnomalyInvestigationWorkflowInputs:
@@ -222,7 +217,7 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
# short grace applies (INVESTIGATION_NOTIFY_GRACE_MINUTES), and a slow render sitting
# between the DONE update and the dispatch would let the sweep force-send its fallback
# notification mid-render. While the status is RUNNING the sweep waits much longer.
- insight_chart_url = await sync_to_async(_prepare_insight_chart_url, thread_sensitive=False)(
+ insight_chart_url = await sync_to_async(prepare_alert_insight_chart_url, thread_sensitive=False)(
alert=alert,
alert_check=alert_check,
user=user,
@@ -446,70 +441,6 @@ def _build_signal_description(
return description
-def _inconclusive_is_suppressed(verdict: str | None, inconclusive_action: str | None) -> bool:
- """Whether an inconclusive verdict is held back by the alert's configured policy."""
- return verdict == "inconclusive" and (inconclusive_action or "notify") == "suppress"
-
-
-def _should_suppress_notification(verdict: str | None, inconclusive_action: str | None) -> bool:
- """Whether the verdict holds the notification back: false positives always suppress,
- inconclusive follows the alert's configured policy."""
- return verdict == "false_positive" or _inconclusive_is_suppressed(verdict, inconclusive_action)
-
-
-def _prepare_insight_chart_url(
- *,
- alert: AlertConfiguration,
- alert_check: AlertCheck,
- user: User,
- verdict: str | None,
-) -> str | None:
- """Render the alerted insight to a PNG and mint a URL Slack can embed as an image block.
-
- Skipped when nothing would show it: a suppressed verdict, an already-delivered check
- (the common case for non-gated alerts, whose notification the main task sent
- synchronously), or no active Slack destination (only the Slack template renders the
- chart). Best-effort: on any failure (render error, no viewer access for the
- investigation user, export infrastructure down) return None so the notification still
- goes out, just without the chart.
- """
- if _should_suppress_notification(verdict, alert.investigation_inconclusive_action):
- return None
- pending = AlertCheck.objects.filter(
- id=alert_check.id, notification_sent_at__isnull=True, notification_suppressed_by_agent=False
- ).exists()
- if not pending:
- return None
- try:
- destinations = list_active_alert_destinations(
- team_id=alert.team_id, alert_id=str(alert.id), allowed_event_ids=(INSIGHT_ALERT_FIRING_EVENT,)
- )
- if not any(destination.destination_type == "slack" for destination in destinations):
- return None
- asset, content = exports.render_png_export(
- team=alert.team,
- created_by=user,
- insight_id=alert.insight_id,
- # System render: keep it out of the user's export listings and quota.
- is_system=True,
- expires_after=datetime.now(UTC) + _INSIGHT_CHART_ASSET_TTL,
- )
- if content is None:
- logger.info(
- "anomaly_investigation.insight_chart_render_failed",
- alert_id=str(alert.id),
- asset_id=asset.id,
- exception=asset.exception,
- )
- return None
- return exports.get_delivery_image_url(
- team_id=alert.team_id, asset_id=asset.id, expiry_delta=_INSIGHT_CHART_URL_TTL
- )
- except Exception:
- logger.exception("anomaly_investigation.insight_chart_render_failed", alert_id=str(alert.id))
- return None
-
-
def _deliver_investigation_outcome(
*,
alert,
@@ -582,7 +513,11 @@ def _deliver_investigation_outcome(
if insight_chart_url:
extra_properties["insight_chart_url"] = insight_chart_url
try:
- deliveries = dispatch_alert_notification(alert, check, breaches, extra_properties=extra_properties or None)
+ # render_chart=False: the chart was already rendered above, before this
+ # transaction took its row lock.
+ deliveries = dispatch_alert_notification(
+ alert, check, breaches, extra_properties=extra_properties or None, render_chart=False
+ )
record_alert_delivery(alert, check, deliveries, stamp_on_empty=True)
except Exception:
logger.exception(
@@ -650,6 +585,9 @@ def _dispatch_verdict_change_followup(
breaches,
extra_properties=extra_properties,
idempotency_key=f"{check.id}:investigation-verdict-change",
+ # The caller holds a row lock, and this check was already notified, so
+ # prepare_alert_insight_chart_url would return None anyway.
+ render_chart=False,
)
except Exception:
# Best-effort, like the signal emit: the verdict is persisted and the user already
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
index 60039136b89d..9523153c8ee9 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
@@ -69,7 +69,7 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
)
@pytest.mark.asyncio
- @patch("posthog.temporal.ai.anomaly_investigation.workflow._prepare_insight_chart_url", return_value=None)
+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.prepare_alert_insight_chart_url", return_value=None)
@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")
@patch("temporalio.activity.heartbeat")
@patch("temporalio.activity.info")
@@ -102,7 +102,7 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
assert self.alert_check.investigation_notebook_id is not None
@pytest.mark.asyncio
- @patch("posthog.temporal.ai.anomaly_investigation.workflow.exports.render_png_export")
+ @patch("posthog.tasks.alerts.utils.exports.render_png_export")
@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")
@patch("temporalio.activity.heartbeat")
@patch("temporalio.activity.info")
@@ -135,7 +135,7 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
mock_render.assert_not_called()
@pytest.mark.asyncio
- @patch("posthog.temporal.ai.anomaly_investigation.workflow._prepare_insight_chart_url", return_value=None)
+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.prepare_alert_insight_chart_url", return_value=None)
@patch("posthog.temporal.ai.anomaly_investigation.workflow.signals.emit_signal")
@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")
@patch("temporalio.activity.heartbeat")
@@ -176,7 +176,7 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
@pytest.mark.asyncio
@patch("posthog.temporal.ai.anomaly_investigation.workflow.dispatch_alert_notification", return_value=[])
- @patch("posthog.temporal.ai.anomaly_investigation.workflow.exports.render_png_export")
+ @patch("posthog.tasks.alerts.utils.exports.render_png_export")
@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")
@patch("temporalio.activity.heartbeat")
@patch("temporalio.activity.info")
diff --git a/products/cdp/mcp/cdp_functions.yaml b/products/cdp/mcp/cdp_functions.yaml
index 953fd0138b2a..ac4e22a0c904 100644
--- a/products/cdp/mcp/cdp_functions.yaml
+++ b/products/cdp/mcp/cdp_functions.yaml
@@ -96,10 +96,11 @@ tools:
insight_id (short_id), state (always "Firing" — the event is only emitted on a firing transition,
not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.
"Series A is below 1000"), and detector metadata: alert_mode (always present), detector_type and
- ensemble_operator (null for threshold alerts, set for anomaly detection). Dispatches gated on the
- anomaly investigation agent may also carry investigation_notebook_url and insight_chart_url
- (a tokenized image URL the Slack blocks above render as a chart); both are absent otherwise, so
- templates must fall back, as the conditional block above does. Project context is
+ ensemble_operator (null for threshold alerts, set for anomaly detection). Any firing alert may
+ carry insight_chart_url (a tokenized image URL the Slack blocks above render as a chart), and
+ dispatches gated on the anomaly investigation agent may also carry investigation_notebook_url;
+ both are absent otherwise, so templates must fall back, as the conditional block above does.
+ Project context is
available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do
not reference value, threshold_lower, or insight_url — those are not emitted.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 8b9500b45977..5fce49cba70f 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1353,7 +1353,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field. Create destinations disabled: test with cdp-functions-invocations-create, then enable with cdp-functions-partial-update once the config looks right. (Other types, like internal_destination below, create as sent.)\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n \"{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}\",\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Dispatches gated on the\n anomaly investigation agent may also carry investigation_notebook_url and insight_chart_url\n (a tokenized image URL the Slack blocks above render as a chart); both are absent otherwise, so\n templates must fall back, as the conditional block above does. Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field. Create destinations disabled: test with cdp-functions-invocations-create, then enable with cdp-functions-partial-update once the config looks right. (Other types, like internal_destination below, create as sent.)\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n \"{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}\",\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Any firing alert may\n carry insight_chart_url (a tokenized image URL the Slack blocks above render as a chart), and\n dispatches gated on the anomaly investigation agent may also carry investigation_notebook_url;\n both are absent otherwise, so templates must fall back, as the conditional block above does.\n Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 89190c93b083..c18e668481df 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1368,7 +1368,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field. Create destinations disabled: test with cdp-functions-invocations-create, then enable with cdp-functions-partial-update once the config looks right. (Other types, like internal_destination below, create as sent.)\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n \"{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}\",\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Dispatches gated on the\n anomaly investigation agent may also carry investigation_notebook_url and insight_chart_url\n (a tokenized image URL the Slack blocks above render as a chart); both are absent otherwise, so\n templates must fall back, as the conditional block above does. Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field. Create destinations disabled: test with cdp-functions-invocations-create, then enable with cdp-functions-partial-update once the config looks right. (Other types, like internal_destination below, create as sent.)\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n \"{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}\",\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Any firing alert may\n carry insight_chart_url (a tokenized image URL the Slack blocks above render as a chart), and\n dispatches gated on the anomaly investigation agent may also carry investigation_notebook_url;\n both are absent otherwise, so templates must fall back, as the conditional block above does.\n Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",