: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(replay_vision): make the featured-digest name collision-safe (#75146)
Kim Svatos Duganedd2173369db
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.pyindex 62505b8bfdc8..c75eae12bad8 100644--- a/products/replay_vision/backend/api/vision_actions.py+++ b/products/replay_vision/backend/api/vision_actions.py@@ -33,6 +33,7 @@ from posthog.models.user import Userfrom products.replay_vision.backend.api.delivery import archive_delivery, provision_deliveryfrom products.replay_vision.backend.api.errors import ReplayVisionErrorSerializerfrom products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_process_vision_action_workflow+from products.replay_vision.backend.digest import digest_name_for_scanner, unique_digest_namefrom products.replay_vision.backend.feature_flag import (ReplayVisionActionsEnabledPermission,ReplayVisionEnabledPermission,@@ -495,6 +496,11 @@ class VisionActionSerializer(serializers.ModelSerializer):name = attrs.get("name")if name is None:return+ # A brand-new digest whose name is exactly the auto-derived one came from the one-click+ # "Turn on daily digest" button, so create() makes it collision-safe instead of 400-ing.+ # A user-typed name (even on a digest) still gets the explicit duplicate error below.+ if self.instance is None and attrs.get("is_scanner_digest") and self._has_derived_digest_name(attrs):+ returnteam = self.context["get_team"]()duplicates = VisionAction.objects.for_team(team.id).filter(name=name)if self.instance is not None:@@ -502,6 +508,11 @@ class VisionActionSerializer(serializers.ModelSerializer):if duplicates.exists():raise serializers.ValidationError({"name": "An action with this name already exists in this team."})+ @staticmethod+ def _has_derived_digest_name(attrs: dict[str, Any]) -> bool:+ scanner = attrs.get("scanner")+ return scanner is not None and attrs.get("name") == digest_name_for_scanner(scanner)+def _validate_digest(self, attrs: dict[str, Any]) -> None:# The overview card renders the featured digest as a synthesized summary, so an alert can't# occupy that slot. Promoting to the featured slot is otherwise always allowed — create()/update()@@ -551,6 +562,10 @@ class VisionActionSerializer(serializers.ModelSerializer):user = cast(User, self.context["request"].user)if validated_data.get("is_scanner_digest"):self._demote_existing_digest(validated_data["scanner"])+ if self._has_derived_digest_name(validated_data):+ # Another action may already hold the derived name (a user-named action, or a digest+ # demoted earlier), so dedupe to keep the (team, name) constraint from rejecting it.+ validated_data["name"] = unique_digest_name(team.id, validated_data["name"])try:# for_team()'s filter doesn't propagate into create(), so team is still passed explicitly.return VisionAction.objects.for_team(team.id).create(team=team, created_by=user, **validated_data)diff --git a/products/replay_vision/backend/digest.py b/products/replay_vision/backend/digest.pyindex 75616247714c..5bec2f9d10a9 100644--- a/products/replay_vision/backend/digest.py+++ b/products/replay_vision/backend/digest.py@@ -16,10 +16,28 @@ SCANNER_DIGEST_RRULE = "FREQ=DAILY;BYHOUR=8;BYMINUTE=0"def digest_name_for_scanner(scanner: "ReplayScanner") -> str:- # VisionAction names are unique per team, so the scanner name (itself team-unique) is baked in.return f"Daily digest: {scanner.name}"[:255]+def unique_digest_name(team_id: int, base: str) -> str:+ """A team-unique variant of `base`, suffixing " (2)", " (3)", … when the plain name is taken.+ Scanner names are team-unique, so two scanners can't produce the same derived name; the+ collision source is another VisionAction already holding it, such as a user-named action or a+ digest that was demoted earlier and kept its name."""+ base = base[:255]+ # One query over the team's names beating this base; the count per team is small.+ taken = set(VisionAction.objects.for_team(team_id).filter(name__startswith=base).values_list("name", flat=True))+ if base not in taken:+ return base+ for n in range(2, len(taken) + 3):+ candidate = f"{base[: 255 - len(f' ({n})')]} ({n})"+ if candidate not in taken:+ return candidate+ # Unreachable given the range spans more than the collisions, but stay well-defined; the DB+ # uniqueness constraint is the final backstop.+ return base++def provision_scanner_digest(scanner: "ReplayScanner", user: "User") -> VisionAction | None:"""Create the scanner's built-in daily digest: a summary action with no delivery targets whoseruns surface on the scanner overview. Fail-soft; scanner creation must never fail because digest@@ -29,7 +47,7 @@ def provision_scanner_digest(scanner: "ReplayScanner", user: "User") -> VisionAcreturn VisionAction.objects.for_team(scanner.team_id).create(team_id=scanner.team_id,scanner=scanner,- name=digest_name_for_scanner(scanner),+ name=unique_digest_name(scanner.team_id, digest_name_for_scanner(scanner)),created_by=user,is_scanner_digest=True,trigger_config={diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.pyindex 4c5ab3adb3d9..b1a9c8e15087 100644--- a/products/replay_vision/backend/tests/test_vision_actions_api.py+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py@@ -261,6 +261,38 @@ class TestVisionActionViewSet(_VisionActionAPITestCase):# The promotion rolled back: the restricted digest is untouched and the summary wasn't flagged.self.assertEqual(self._flagged_digest_ids(), [str(current.id)])+ def test_creating_a_digest_dedupes_a_taken_name(self) -> None:+ # The "Turn on daily digest" button derives a fixed name from the scanner. If another action+ # already holds it, the create must succeed with a suffixed name, not 400 on (team, name).+ taken = f"Daily digest: {self.scanner.name}"+ VisionAction.all_teams.create(+ team=self.team,+ scanner=self.scanner,+ name=taken,+ trigger_config={"rrule": "FREQ=DAILY", "timezone": "UTC"},+ )+ resp = self.client.post(+ self.actions_url, data=self._create_payload(name=taken, is_scanner_digest=True), format="json"+ )+ self.assertEqual(resp.status_code, 201, resp.content)+ self.assertTrue(resp.json()["is_scanner_digest"])+ self.assertEqual(resp.json()["name"], f"{taken} (2)")++ def test_creating_a_digest_with_a_user_typed_duplicate_name_still_400s(self) -> None:+ # Dedupe applies only to the auto-derived name; a user-typed name that collides must keep+ # the explicit duplicate error rather than being silently renamed.+ VisionAction.all_teams.create(+ team=self.team,+ scanner=self.scanner,+ name="my-digest",+ trigger_config={"rrule": "FREQ=DAILY", "timezone": "UTC"},+ )+ resp = self.client.post(+ self.actions_url, data=self._create_payload(name="my-digest", is_scanner_digest=True), format="json"+ )+ self.assertEqual(resp.status_code, 400, resp.content)+ self.assertEqual(resp.json()["attr"], "name")+def test_alert_cannot_be_featured_digest(self) -> None:payload = self._create_payload(name="an-alert",