:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): provision Slack delivery destinations for vision actions (#64739)
Kim Svatos Duganb19966bfc6ef
diff --git a/products/replay_vision/backend/api/delivery.py b/products/replay_vision/backend/api/delivery.pynew file mode 100644index 000000000000..70bae6c5c5a3--- /dev/null+++ b/products/replay_vision/backend/api/delivery.py@@ -0,0 +1,93 @@+from typing import Any++from django.db.models import QuerySet++import structlog+from rest_framework.request import Request++from posthog.models import Team++from products.cdp.backend.api.hog_function import HogFunctionSerializer+from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.replay_vision.backend.models.vision_action import VisionAction++logger = structlog.get_logger(__name__)++# The scheduled child of a vision action emits this as a PRIVATE internal event (cdp_internal_events+# topic) with `vision_action_id` + `slack_text`. Per-action `internal_destination` HogFunctions filter+# on it and post `slack_text` to their channel. Using the internal channel (not the public capture+# pipeline) makes the trigger non-forgeable with the project's client token — the Alerts pattern.+EVENT_NAME = "$replay_vision_action_ready"+_INTERNAL_DESTINATION = "internal_destination"+_SLACK_TEMPLATE = "template-slack"+++def _managed_destinations(action: VisionAction, team: Team) -> QuerySet[HogFunction]:+ """The internal_destination HogFunctions this action owns.++ There's no FK on the action — the trigger filter IS the binding, so we find them by the+ `vision_action_id` property the filter carries (the same bind-by-filter pattern alerts use).+ """+ return HogFunction.objects.filter(+ team_id=team.id,+ type=_INTERNAL_DESTINATION,+ deleted=False,+ filters__contains={"properties": [{"key": "vision_action_id", "value": str(action.id)}]},+ )+++def _slack_destination_payload(action: VisionAction, target: dict[str, Any]) -> dict[str, Any]:+ return {+ "type": _INTERNAL_DESTINATION,+ "enabled": action.enabled,+ "template_id": _SLACK_TEMPLATE,+ "name": f"Replay Vision · {action.name}",+ "filters": {+ "events": [{"id": EVENT_NAME, "type": "events"}],+ "properties": [+ {"key": "vision_action_id", "value": str(action.id), "operator": "exact", "type": "event"},+ ],+ },+ "inputs": {+ "slack_workspace": {"value": target["integration_id"]},+ "channel": {"value": target["channel"]},+ # Hog-templated pass-through of the pre-formatted Slack text carried on the event.+ "text": {"value": "{event.properties.slack_text}"},+ },+ }+++def provision_delivery(action: VisionAction, *, request: Request, team: Team) -> None:+ """Reconcile this action's `internal_destination` HogFunctions to its `delivery_config`.++ Archive-and-recreate: drop the action's managed destinations, then create one per delivery target+ when the action is enabled. A provisioning failure propagates so the caller learns delivery wasn't+ wired up — the viewset runs this inside its atomic block.+ """+ _archive_managed(action, team)+ if not action.enabled or not action.delivery_config:+ return++ # HogFunctionSerializer.create() reads context["request"].user, so provisioning stays in the viewset.+ context = {"request": request, "team_id": team.id, "get_team": lambda: team, "is_create": True}+ for target in action.delivery_config:+ serializer = HogFunctionSerializer(data=_slack_destination_payload(action, target), context=context)+ serializer.is_valid(raise_exception=True)+ serializer.save()+++def archive_delivery(action: VisionAction, *, team: Team) -> None:+ """Best-effort archive of the action's delivery destinations — a failure never blocks the delete."""+ try:+ _archive_managed(action, team)+ except Exception:+ logger.exception("replay_vision_delivery_archive_failed", vision_action_id=str(action.id))+++def _archive_managed(action: VisionAction, team: Team) -> None:+ # Per-row .save() (not a bulk .update()) so the post_save signal deregisters each function from the+ # workers — a soft-deleted destination must stop firing.+ for fn in _managed_destinations(action, team):+ fn.enabled = False+ fn.deleted = True+ fn.save()diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.pyindex c6e5335b8d09..3dd0fff26d26 100644--- a/products/replay_vision/backend/api/vision_actions.py+++ b/products/replay_vision/backend/api/vision_actions.py@@ -1,12 +1,13 @@from typing import Any, NoReturn, cast-from django.db import IntegrityError+from django.db import IntegrityError, transactionfrom django.db.models import QuerySetimport structlogfrom rest_framework import serializers, viewsetsfrom rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Request+from rest_framework.serializers import BaseSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField@@ -14,6 +15,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.models.integration import Integrationfrom posthog.models.user import User+from products.replay_vision.backend.api.delivery import archive_delivery, provision_deliveryfrom products.replay_vision.backend.feature_flag import (ReplayVisionActionsEnabledPermission,ReplayVisionEnabledPermission,@@ -306,3 +308,30 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def safely_get_queryset(self, queryset: QuerySet[VisionAction]) -> QuerySet[VisionAction]:return queryset.filter(team_id=self.team_id).select_related("scanner", "created_by").order_by("name", "id")++ def perform_create(self, serializer: BaseSerializer) -> None:+ # Atomic so a destination-provisioning failure rolls back the action row rather than leaving an+ # action that looks created but never delivers.+ with transaction.atomic():+ action = serializer.save()+ provision_delivery(action, request=self.request, team=self.team)++ def perform_update(self, serializer: BaseSerializer) -> None:+ instance = cast(VisionAction, serializer.instance)+ # Snapshot the destination-affecting fields BEFORE save() — DRF mutates `instance` in place, so+ # these must be read pre-save for the change comparison to be meaningful.+ old_delivery = instance.delivery_config+ old_enabled = instance.enabled+ old_name = instance.name+ # Atomic so a re-provision failure rolls the action edit back too (parity with perform_create).+ with transaction.atomic():+ action = serializer.save()+ # Re-provision only when something the destinations reflect changed: delivery targets, the+ # enabled flag, or the name (each destination is named after the action). Cadence/selection+ # edits don't touch the destinations, so they must not churn them.+ if action.delivery_config != old_delivery or action.enabled != old_enabled or action.name != old_name:+ provision_delivery(action, request=self.request, team=self.team)++ def perform_destroy(self, instance: VisionAction) -> None:+ archive_delivery(instance, team=self.team)+ super().perform_destroy(instance)diff --git a/products/replay_vision/backend/tests/test_vision_action_delivery.py b/products/replay_vision/backend/tests/test_vision_action_delivery.pynew file mode 100644index 000000000000..bd5bf094d54e--- /dev/null+++ b/products/replay_vision/backend/tests/test_vision_action_delivery.py@@ -0,0 +1,201 @@+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.cdp.templates.hog_function_template import sync_template_to_db+from posthog.cdp.templates.slack.template_slack import template as template_slack+from posthog.models import Team+from posthog.models.integration import Integration++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.replay_vision.backend.api.delivery import EVENT_NAME+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.models.vision_action import VisionAction+++class TestVisionActionDelivery(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ sync_template_to_db(template_slack)+ self.flag_patcher = patch(+ "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self.flag_patcher.start()+ # Saving a HogFunction pushes it to the CDP workers; there are none in tests.+ self.reload_patcher = patch(+ "products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers",+ )+ self.reload_patcher.start()+ self.scanner = self._create_scanner()+ self.integration = self._create_slack_integration()+ self.other_integration = self._create_slack_integration()++ def tearDown(self) -> None:+ self.reload_patcher.stop()+ self.flag_patcher.stop()+ super().tearDown()++ @property+ def actions_url(self) -> str:+ return f"/api/projects/{self.team.id}/vision/actions/"++ def _create_scanner(self, team: Team | None = None) -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=team or self.team,+ name="my-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_FLASH,+ )++ def _create_slack_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id=f"T_{Integration.objects.count()}",+ config={"team": {"name": "Test Workspace"}},+ sensitive_config={"access_token": "test-token"},+ created_by=self.user,+ )++ def _payload(self, **overrides: Any) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "name": "daily-summary",+ "scanner": str(self.scanner.id),+ "trigger_config": {"rrule": "FREQ=DAILY", "timezone": "UTC"},+ "selection": {"scanner_type": "summarizer", "window_days": 1},+ "delivery_config": [+ {"type": "slack", "integration_id": self.integration.id, "channel": "#general"},+ ],+ }+ payload.update(overrides)+ return payload++ def _create_action(self, **overrides: Any) -> VisionAction:+ resp = self.client.post(self.actions_url, data=self._payload(**overrides), format="json")+ self.assertEqual(resp.status_code, 201, resp.content)+ return VisionAction.all_teams.get(id=resp.json()["id"])++ def _destinations(self, action: VisionAction) -> list[HogFunction]:+ """The action's live internal_destination HogFunctions — found by the vision_action_id filter+ (no FK; the trigger filter is the binding), mirroring delivery._managed_destinations."""+ return list(+ HogFunction.objects.filter(+ team_id=self.team.id,+ type="internal_destination",+ deleted=False,+ filters__contains={"properties": [{"key": "vision_action_id", "value": str(action.id)}]},+ ).order_by("created_at")+ )++ @staticmethod+ def _inputs(fn: HogFunction) -> dict[str, Any]:+ assert fn.inputs is not None+ return fn.inputs++ @staticmethod+ def _filters(fn: HogFunction) -> dict[str, Any]:+ assert fn.filters is not None+ return fn.filters++ def test_create_provisions_destination(self) -> None:+ action = self._create_action()++ destinations = self._destinations(action)+ self.assertEqual(len(destinations), 1)+ fn = destinations[0]+ self.assertEqual(fn.type, "internal_destination")+ self.assertEqual(fn.template_id, "template-slack")+ self.assertTrue(fn.enabled)+ self.assertEqual(fn.name, "Replay Vision · daily-summary")++ event_filter = self._filters(fn)["events"][0]+ self.assertEqual(event_filter["id"], EVENT_NAME)+ prop = self._filters(fn)["properties"][0]+ self.assertEqual(prop["key"], "vision_action_id")+ self.assertEqual(prop["value"], str(action.id))++ self.assertEqual(self._inputs(fn)["slack_workspace"]["value"], self.integration.id)+ self.assertEqual(self._inputs(fn)["channel"]["value"], "#general")+ self.assertEqual(self._inputs(fn)["text"]["value"], "{event.properties.slack_text}")++ def test_create_two_targets_makes_two_destinations(self) -> None:+ action = self._create_action(+ delivery_config=[+ {"type": "slack", "integration_id": self.integration.id, "channel": "#one"},+ {"type": "slack", "integration_id": self.other_integration.id, "channel": "#two"},+ ],+ )+ destinations = self._destinations(action)+ self.assertEqual(len(destinations), 2)+ self.assertEqual({self._inputs(d)["channel"]["value"] for d in destinations}, {"#one", "#two"})++ def test_create_empty_delivery_no_destination(self) -> None:+ action = self._create_action(delivery_config=[])+ self.assertEqual(self._destinations(action), [])++ def test_update_delivery_reprovisions(self) -> None:+ action = self._create_action()+ resp = self.client.patch(+ f"{self.actions_url}{action.id}/",+ data={"delivery_config": [{"type": "slack", "integration_id": self.integration.id, "channel": "#changed"}]},+ format="json",+ )+ self.assertEqual(resp.status_code, 200, resp.content)++ destinations = self._destinations(action)+ self.assertEqual(len(destinations), 1)+ self.assertEqual(self._inputs(destinations[0])["channel"]["value"], "#changed")++ @parameterized.expand(+ [+ ("selection", {"selection": {"window_days": 7}}),+ ("trigger_config", {"trigger_config": {"rrule": "FREQ=WEEKLY", "timezone": "UTC"}}),+ ("synthesis_config", {"synthesis_config": {"prompt_guide": "focus on checkout drop-off"}}),+ ]+ )+ def test_update_non_delivery_does_not_reprovision(self, _field: str, patch_data: dict[str, Any]) -> None:+ action = self._create_action()+ before = self._destinations(action)[0].id++ # Editing a field the destinations don't reflect (cadence/selection/synthesis) must not churn them.+ with patch("products.replay_vision.backend.api.vision_actions.provision_delivery") as mock_provision:+ resp = self.client.patch(f"{self.actions_url}{action.id}/", data=patch_data, format="json")+ self.assertEqual(resp.status_code, 200, resp.content)+ mock_provision.assert_not_called()++ after = self._destinations(action)+ self.assertEqual(len(after), 1)+ self.assertEqual(after[0].id, before)++ def test_rename_reprovisions_and_updates_destination_name(self) -> None:+ # Each destination is named after the action, so a rename re-provisions to keep the name in sync.+ action = self._create_action()+ resp = self.client.patch(f"{self.actions_url}{action.id}/", data={"name": "renamed action"}, format="json")+ self.assertEqual(resp.status_code, 200, resp.content)++ destinations = self._destinations(action)+ self.assertEqual(len(destinations), 1)+ self.assertEqual(destinations[0].name, "Replay Vision · renamed action")++ def test_disable_archives_destinations(self) -> None:+ action = self._create_action()+ resp = self.client.patch(f"{self.actions_url}{action.id}/", data={"enabled": False}, format="json")+ self.assertEqual(resp.status_code, 200, resp.content)+ self.assertEqual(self._destinations(action), [])++ def test_delete_archives_destinations(self) -> None:+ action = self._create_action()+ resp = self.client.delete(f"{self.actions_url}{action.id}/")+ self.assertEqual(resp.status_code, 204, resp.content)+ self.assertEqual(self._destinations(action), [])++ def test_update_to_empty_delivery_archives_destinations(self) -> None:+ action = self._create_action()+ resp = self.client.patch(f"{self.actions_url}{action.id}/", data={"delivery_config": []}, format="json")+ self.assertEqual(resp.status_code, 200, resp.content)+ self.assertEqual(self._destinations(action), [])diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.pyindex f325cd5f341d..d159d79163c9 100644--- a/products/replay_vision/backend/tests/test_vision_actions_api.py+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py@@ -3,6 +3,8 @@ from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from posthog.cdp.templates.hog_function_template import sync_template_to_db+from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.models import Organization, Teamfrom posthog.models.integration import Integration@@ -13,15 +15,24 @@ from products.replay_vision.backend.models.vision_action import VisionActionclass _VisionActionAPITestCase(APIBaseTest):def setUp(self) -> None:super().setUp()+ # Creating an action provisions a Slack internal_destination HogFunction, which resolves the+ # template from the DB.+ sync_template_to_db(template_slack)self.flag_patcher = patch("products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",return_value=True,)self.flag_patcher.start()+ # Saving a HogFunction pushes it to the CDP workers; there are none in tests.+ self.reload_patcher = patch(+ "products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers",+ )+ self.reload_patcher.start()self.scanner = self._create_scanner()self.integration = self._create_slack_integration()def tearDown(self) -> None:+ self.reload_patcher.stop()self.flag_patcher.stop()super().tearDown()@@ -74,6 +85,7 @@ class TestVisionActionViewSet(_VisionActionAPITestCase):self.assertEqual(data["mode"], "group_summary")self.assertIsNotNone(data["next_run_at"])self.assertIsNone(data["last_run_at"])+ # Delivery is an internal_destination HogFunction (no HogFlow), so hog_flow_id stays null.self.assertIsNone(data["hog_flow_id"])self.assertEqual(data["created_by"]["id"], self.user.id)diff --git a/tach.toml b/tach.tomlindex 0b805bc8f218..f87bb37d69ed 100644--- a/tach.toml+++ b/tach.toml@@ -522,8 +522,10 @@ path = "products.replay_vision"depends_on = ["ee","posthog",+ "products.cdp","products.exports","products.signals",+ "products.workflows",]layer = "modules"