: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
refactor(product-tours): route targeting flag writes through the flag facade (#71301)
Andersaf809d5948b0
diff --git a/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yaml b/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yamlindex bec6ab925049..fbeaa7d46e58 100644--- a/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yaml+++ b/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yaml@@ -39,7 +39,6 @@ rules:- '/products/early_access_features/backend/apps.py'- '/products/experiments/backend/experiment_service.py'- '/products/experiments/backend/experiment_summary_data_service.py'- - '/products/product_tours/backend/api/product_tour.py'patterns:- pattern-either:- pattern: $FLAG.filters[$KEY]diff --git a/products/product_tours/backend/api/product_tour.py b/products/product_tours/backend/api/product_tour.pyindex 6e563c5b175f..8cb6a7fe916f 100644--- a/products/product_tours/backend/api/product_tour.py+++ b/products/product_tours/backend/api/product_tour.py@@ -40,7 +40,9 @@ from posthog.models.user import Userfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.utils_cors import cors_response-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, MinimalFeatureFlagSerializer+from products.approvals.backend.mixins import ApprovalHandlingMixin+from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer+from products.feature_flags.backend.facade.api import create_flag, set_flag_active, update_flagfrom products.product_tours.backend.constants import ProductTourEventName, ProductTourPersonPropertiesfrom products.product_tours.backend.generate_tour_content import ContentGenerationResult, generate_with_geminifrom products.product_tours.backend.models import ProductTour@@ -148,8 +150,8 @@ class ProductTourSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerif not tour.internal_targeting_flag:return None- filters = tour.internal_targeting_flag.filters- if not filters or "groups" not in filters:+ groups = tour.internal_targeting_flag.conditions+ if not groups:return None# Filter out the base exclusion properties to return only user-defined targeting@@ -161,7 +163,7 @@ class ProductTourSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSer}cleaned_groups = []- for group in filters.get("groups", []):+ for group in groups:properties = group.get("properties", [])user_properties = [p for p in properties if p.get("key") not in base_property_keys]if user_properties:@@ -274,6 +276,11 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):return data+ # Kept @transaction.atomic so a failed create rolls back cleanly instead of leaving a tour+ # persisted without its internal targeting flag. The trade-off (mirroring experiments'+ # create_experiment) is that an approval-gated flag write here rolls back its pending+ # ChangeRequest along with the tour; the update path below runs non-atomically to avoid+ # that, which it can because the tour already exists there.@transaction.atomicdef create(self, validated_data):request = self.context["request"]@@ -317,7 +324,12 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):return instance- @transaction.atomic+ # Not @transaction.atomic: the internal targeting flag writes below route through the+ # feature flag facade's approval gate, which can raise ApprovalRequired (surfacing as a+ # 409 + a pending ChangeRequest). Wrapping them in a transaction would roll that+ # ChangeRequest back as the exception propagates, leaving the 409 pointing at a request+ # that no longer exists. Running non-atomically keeps the pending ChangeRequest intact for+ # an approver to act on — mirroring experiments' update_experiment.def update(self, instance, validated_data):request = self.context["request"]team = self.context["get_team"]()@@ -369,8 +381,7 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):self._update_internal_targeting_flag_state(instance)elif instance.internal_targeting_flag:# auto_launch turned OFF - deactivate the flag- instance.internal_targeting_flag.active = False- instance.internal_targeting_flag.save(update_fields=["active"])+ set_flag_active(instance.internal_targeting_flag, False, **self._flag_write_kwargs())elif start_date_changed or end_date_changed or archived_changed:# Only update flag state if auto_launch is enabledif instance.auto_launch:@@ -418,6 +429,11 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):return instance+ def _flag_write_kwargs(self) -> dict[str, Any]:+ """team/user/request kwargs for the feature flag facade's gated write functions."""+ request = self.context["request"]+ return {"team": self.context["get_team"](), "user": request.user, "request": request}+def _get_base_exclusion_properties(self, instance: ProductTour) -> list:"""Get the base exclusion properties for the internal targeting flag based on display frequency."""tour_key = str(instance.id)@@ -521,13 +537,7 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):"creation_context": "product_tours",}- # Use self.context to pass through project_id and other context- flag_serializer = FeatureFlagSerializer(- data=flag_data,- context=self.context,- )- flag_serializer.is_valid(raise_exception=True)- flag = flag_serializer.save()+ flag = create_flag(flag_data, **self._flag_write_kwargs())instance.internal_targeting_flag = flaginstance.save(update_fields=["internal_targeting_flag"])@@ -540,8 +550,7 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):should_be_active = bool(instance.start_date) and not instance.end_date and not instance.archivedif flag.active != should_be_active:- flag.active = should_be_active- flag.save(update_fields=["active"])+ set_flag_active(flag, should_be_active, **self._flag_write_kwargs())def _update_targeting_flag_filters(self, instance: ProductTour, new_filters: dict | None) -> None:"""Update the internal targeting flag's filters with additional user targeting conditions.@@ -552,19 +561,16 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):if not flag:return- if new_filters is None:- flag.filters = {"groups": self._build_flag_groups(instance)}- flag.save(update_fields=["filters"])- return-- new_groups = new_filters.get("groups", [])+ new_groups = (new_filters or {}).get("groups", [])user_property_groups = [group.get("properties", []) for group in new_groups]if not user_property_groups or all(not p for p in user_property_groups):- flag.filters = {"groups": self._build_flag_groups(instance)}+ # No user targeting: reset to base + wait period filters only+ groups = self._build_flag_groups(instance)else:- flag.filters = {"groups": self._build_flag_groups(instance, user_property_groups)}- flag.save(update_fields=["filters"])+ groups = self._build_flag_groups(instance, user_property_groups)+ # Replace the whole filters dict with only "groups", matching the shape these flags have always had+ update_flag(flag, {"filters": {"groups": groups}}, **self._flag_write_kwargs())def _is_system_managed_property(self, instance: ProductTour, prop: dict) -> bool:"""Check whether a flag property is system-managed (base exclusion or wait period)."""@@ -586,7 +592,7 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):# (wait period expansion creates N groups with identical user props)seen: set[frozenset] = set()user_groups: list[list] = []- for g in flag.filters.get("groups", []):+ for g in flag.conditions:props = [p for p in g.get("properties", []) if not self._is_system_managed_property(instance, p)]sig = frozenset((p.get("key", ""), p.get("value", ""), p.get("operator", ""), p.get("type", "")) for p in props@@ -760,7 +766,17 @@ class GenerateResponseSerializer(serializers.Serializer):],),)-class ProductTourViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):+class ProductTourViewSet(+ # Converts the ApprovalRequired raised by FeatureFlagSerializer, when a gated internal+ # targeting flag write needs approval, into a 409 carrying the pending change_request_id+ # rather than a 500.+ ApprovalHandlingMixin,+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ viewsets.ModelViewSet,+):+ """Create, read, update, and manage product tours and their targeting."""+scope_object = "product_tour"scope_object_read_actions = ["list", "retrieve", "draft_status"]scope_object_write_actions = [diff --git a/products/product_tours/backend/api/test/test_product_tour.py b/products/product_tours/backend/api/test/test_product_tour.pyindex 2a5fe8a192a8..e3f18bc19833 100644--- a/products/product_tours/backend/api/test/test_product_tour.py+++ b/products/product_tours/backend/api/test/test_product_tour.py@@ -6,8 +6,10 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeaturefrom posthog.models.team.team import Team+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestStatefrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.api.product_tour import get_product_tours_responsefrom products.product_tours.backend.constants import ProductTourEventName, ProductTourPersonProperties@@ -790,6 +792,138 @@ class TestProductTourInternalTargetingFlag(APIBaseTest):else:assert len(properties) == 0, f"Expected no exclusion properties, got {properties}"+ def test_full_filters_shape_round_trips_through_gated_flag_writes(self):+ user_filters = {+ "groups": [+ {"properties": [{"key": "plan", "value": "pro", "operator": "exact", "type": "person"}]},+ ]+ }+ response = self.client.post(+ f"/api/projects/{self.team.id}/product_tours/",+ data={+ "name": "Round trip",+ "content": {+ "steps": [],+ "displayFrequency": "until_interacted",+ "conditions": {"seenTourWaitPeriod": {"days": 7, "types": ["tour"]}},+ },+ "auto_launch": True,+ "start_date": timezone.now().isoformat(),+ "targeting_flag_filters": user_filters,+ },+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ tour = ProductTour.objects.get(id=response.json()["id"])+ assert tour.internal_targeting_flag is not None+ flag = tour.internal_targeting_flag++ tour_key = str(tour.id)+ base_properties = [+ {+ "key": f"$product_tour_completed/{tour_key}",+ "type": "person",+ "value": "is_not_set",+ "operator": "is_not_set",+ },+ {+ "key": f"$product_tour_dismissed/{tour_key}",+ "type": "person",+ "value": "is_not_set",+ "operator": "is_not_set",+ },+ ]+ wait_key = f"{ProductTourPersonProperties.TOUR_LAST_SEEN_DATE}/tour"+ wait_options = [+ {"key": wait_key, "value": "is_not_set", "operator": "is_not_set", "type": "person"},+ {"key": wait_key, "value": "7d", "operator": "is_date_before", "type": "person"},+ ]+ user_property = {"key": "plan", "value": "pro", "operator": "exact", "type": "person"}+ # aggregation_group_type_index keys are FeatureFlagSerializer normalization,+ # the only mutation the gated write path is expected to make+ expected_filters = {+ "aggregation_group_type_index": None,+ "groups": [+ {+ "variant": "",+ "rollout_percentage": 100,+ "properties": [*base_properties, wait_option, user_property],+ "aggregation_group_type_index": None,+ }+ for wait_option in wait_options+ ],+ }++ flag.refresh_from_db()+ assert flag.filters == expected_filters+ assert flag.active++ response = self.client.patch(+ f"/api/projects/{self.team.id}/product_tours/{tour.id}/",+ data={"targeting_flag_filters": user_filters},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters == expected_filters++ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+ def test_update_under_disable_policy_leaves_pending_change_request(self, _mock_approvals_enabled):+ # Turning auto_launch off deactivates the internal targeting flag through the feature flag+ # facade's approval gate. That gated write must run outside a transaction: if update() were+ # atomic, the ApprovalRequired it raises would roll back the pending ChangeRequest the gate+ # just created, leaving the 409 pointing at a request that no longer exists. Lock in that the+ # ChangeRequest survives and the flag is left untouched.+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()++ # Create an auto-launching tour with no policy in place, so its internal targeting flag is active.+ create_response = self.client.post(+ f"/api/projects/{self.team.id}/product_tours/",+ data={+ "name": "Approval gated tour",+ "content": {+ "steps": [],+ "displayFrequency": "until_interacted",+ "conditions": {"seenTourWaitPeriod": {"days": 7, "types": ["tour"]}},+ },+ "auto_launch": True,+ "start_date": timezone.now().isoformat(),+ },+ format="json",+ )+ assert create_response.status_code == status.HTTP_201_CREATED, create_response.json()+ tour = ProductTour.objects.get(id=create_response.json()["id"])+ flag = tour.internal_targeting_flag+ assert flag is not None+ assert flag.active++ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.disable",+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ patch_response = self.client.patch(+ f"/api/projects/{self.team.id}/product_tours/{tour.id}/",+ data={"auto_launch": False},+ format="json",+ )++ # The gated disable needs approval: it comes back as a 409 referencing the pending+ # ChangeRequest, the flag is left active, and — because update() is not atomic — that+ # ChangeRequest survives for an approver to act on rather than being rolled back.+ assert patch_response.status_code == status.HTTP_409_CONFLICT, patch_response.content+ assert patch_response.json()["change_request_id"]+ flag.refresh_from_db()+ assert flag.active+ assert ChangeRequest.objects.filter(state=ChangeRequestState.PENDING).count() == 1+class TestProductTourStepNormalization(APIBaseTest):@parameterized.expand(diff --git a/products/product_tours/frontend/generated/api.ts b/products/product_tours/frontend/generated/api.tsindex 4f768868adee..53bf94148986 100644--- a/products/product_tours/frontend/generated/api.ts+++ b/products/product_tours/frontend/generated/api.ts@@ -52,6 +52,9 @@ export const getProductToursListUrl = (projectId: string, params?: ProductToursL: `/api/projects/${projectId}/product_tours/`}+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursList = async (projectId: string,params?: ProductToursListParams,@@ -67,6 +70,9 @@ export const getProductToursCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/product_tours/`}+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursCreate = async (projectId: string,productTourSerializerCreateUpdateOnlyApi: NonReadonly<ProductTourSerializerCreateUpdateOnlyApi>,@@ -84,6 +90,9 @@ export const getProductToursRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/product_tours/${id}/`}+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursRetrieve = async (projectId: string,id: string,@@ -99,6 +108,9 @@ export const getProductToursUpdateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/product_tours/${id}/`}+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursUpdate = async (projectId: string,id: string,@@ -117,6 +129,9 @@ export const getProductToursPartialUpdateUrl = (projectId: string, id: string) =return `/api/projects/${projectId}/product_tours/${id}/`}+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursPartialUpdate = async (projectId: string,id: string,@@ -135,6 +150,9 @@ export const getProductToursDestroyUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/product_tours/${id}/`}+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {return apiMutator<void>(getProductToursDestroyUrl(projectId, id), {...options,diff --git a/products/product_tours/frontend/generated/api.zod.ts b/products/product_tours/frontend/generated/api.zod.tsindex 5bc59f23661b..cb5df3b5801a 100644--- a/products/product_tours/frontend/generated/api.zod.ts+++ b/products/product_tours/frontend/generated/api.zod.ts@@ -9,6 +9,9 @@*/import * as zod from 'zod'+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursCreateBodyNameMax = 400export const productToursCreateBodyCreationContextDefault = `app`@@ -32,6 +35,9 @@ export const ProductToursCreateBody = /* @__PURE__ */ zod}).describe('Serializer for creating and updating ProductTour.')+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursUpdateBodyNameMax = 400export const ProductToursUpdateBody = /* @__PURE__ */ zod@@ -46,6 +52,9 @@ export const ProductToursUpdateBody = /* @__PURE__ */ zod}).describe('Read-only serializer for ProductTour.')+/**+ * Create, read, update, and manage product tours and their targeting.+ */export const productToursPartialUpdateBodyNameMax = 400export const productToursPartialUpdateBodyCreationContextDefault = `app`diff --git a/tach.toml b/tach.tomlindex 8ce61af20a7f..bf4a462fe5de 100644--- a/tach.toml+++ b/tach.toml@@ -564,6 +564,7 @@ layer = "modules"path = "products.product_tours"depends_on = ["posthog",+ "products.approvals","products.feature_flags","products.surveys",]