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.

chore(surveys): write survey targeting flags through the flag facade (#107821)

Yasendfc928d5bece
diff --git a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
index f1582093964c..c79438c27306 100644
--- a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
+++ b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
@@ -24,8 +24,6 @@ products/posthog_ai/evals/experiments/seeders.py::seed_inactive_flag_experiment:
products/posthog_ai/evals/experiments/seeders.py::seed_running_experiment::FeatureFlag.objects.create()
products/posthog_ai/evals/experiments/seeders.py::seed_uneven_split_experiment::FeatureFlag.objects.create()
products/surveys/backend/api/survey.py::SurveySerializerCreateUpdateOnly._add_user_survey_interacted_filters::internal_targeting_flag.active =
-products/surveys/backend/api/survey.py::SurveySerializerCreateUpdateOnly._create_or_update_targeting_flag::FeatureFlagSerializer()
-products/surveys/backend/api/survey.py::SurveySerializerCreateUpdateOnly._create_or_update_targeting_flag::FeatureFlagSerializer(existing_flag)
products/surveys/backend/api/survey.py::SurveySerializerCreateUpdateOnly.update::instance.targeting_flag.active =
products/tasks/backend/management/commands/setup_background_agents.py::Command._setup_feature_flags::FeatureFlag.objects.create()
products/tasks/backend/management/commands/setup_background_agents.py::Command._setup_feature_flags::existing.active =
diff --git a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
index 92511f422cb9..7cb5cc41294f 100644
--- a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
+++ b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
@@ -23,7 +23,7 @@ GATED_PATH = {
# Shrink-only. Move a write to the facade, then regenerate the baseline and drop its entry here.
ALLOWED_REASONS: dict[str, str] = {
- "products/surveys/backend/api/survey.py": "targeting flag writes and the start/stop mirror of active",
+ "products/surveys/backend/api/survey.py": "start/stop mirror of active, which the serializer would gate and guard",
"products/feature_flags/backend/facade/api.py": "file-system trash and restore flip active, and never-fail early access enrollment cleanup",
"posthog/api/file_system/registrations.py": "calls the ungated trash and restore helpers",
"posthog/management/commands/generate_random_product_tours.py": "local data generator",
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index 8d535519ac21..130be1a08053 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -68,12 +68,14 @@ from products.access_control.backend.presentation.access_control import (
)
from products.actions.backend.api.action import ActionSerializer, ActionStepJSONSerializer
from products.actions.backend.models.action import Action
+from products.approvals.backend.mixins import ApprovalHandlingMixin
+from products.approvals.backend.transactions import gated_atomic
from products.feature_flags.backend.api.feature_flag import (
BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,
- FeatureFlagSerializer,
MinimalFeatureFlagSerializer,
assert_feature_flag_write_scope,
)
+from products.feature_flags.backend.facade.api import create_flag, update_flag
from products.feature_flags.backend.facade.config import ConfigFormatError
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.ownership import FLAG_OWNER_SURVEY, assert_flag_available_for
@@ -1742,27 +1744,31 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
team_id=self.context["team_id"],
feature_flag_id=validated_data["targeting_flag_id"],
)
- if validated_data.get("targeting_flag_filters"):
- assert_feature_flag_write_scope(
- self.context["request"],
- action="survey.create",
- resource_scope="survey:write",
- team_id=self.context["team_id"],
- )
- targeting_feature_flag = self._create_or_update_targeting_flag(
- None, validated_data["targeting_flag_filters"], validated_data["name"]
- )
- validated_data["targeting_flag_id"] = targeting_feature_flag.id
- validated_data.pop("targeting_flag_filters")
+ # The survey row and its flags are one unit. The gate can reject a flag write after the
+ # row is saved, which would leave a survey with no targeting or internal flag and no way
+ # to retry, so keep the whole create in one block.
+ with gated_atomic():
+ if validated_data.get("targeting_flag_filters"):
+ assert_feature_flag_write_scope(
+ self.context["request"],
+ action="survey.create",
+ resource_scope="survey:write",
+ team_id=self.context["team_id"],
+ )
+ targeting_feature_flag = self._create_or_update_targeting_flag(
+ None, validated_data["targeting_flag_filters"], validated_data["name"]
+ )
+ validated_data["targeting_flag_id"] = targeting_feature_flag.id
+ validated_data.pop("targeting_flag_filters")
- if "targeting_flag_filters" in validated_data:
- validated_data.pop("targeting_flag_filters")
+ if "targeting_flag_filters" in validated_data:
+ validated_data.pop("targeting_flag_filters")
- validated_data["created_by"] = self.context["request"].user
- instance = super().create(validated_data)
- self._add_user_survey_interacted_filters(instance)
- self._associate_actions(instance, validated_data.get("conditions"))
- self._add_internal_response_sampling_filters(instance)
+ validated_data["created_by"] = self.context["request"].user
+ instance = super().create(validated_data)
+ self._add_user_survey_interacted_filters(instance)
+ self._associate_actions(instance, validated_data.get("conditions"))
+ self._add_internal_response_sampling_filters(instance)
team = Team.objects.get(id=self.context["team_id"])
log_activity(
@@ -1794,70 +1800,74 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
feature_flag_id=validated_data["targeting_flag_id"],
)
- if validated_data.get("remove_targeting_flag"):
- if instance.targeting_flag:
+ # One PATCH can remove the existing targeting flag and ask for new filters. The gate can
+ # reject the replacement, so the delete and the write stay in one block. Without it a
+ # rejected change leaves the survey with no targeting flag at all.
+ with gated_atomic():
+ if validated_data.get("remove_targeting_flag"):
+ if instance.targeting_flag:
+ assert_feature_flag_write_scope(
+ self.context["request"],
+ action="survey.update.remove_targeting_flag",
+ resource_scope="survey:write",
+ team_id=self.context["team_id"],
+ feature_flag_id=instance.targeting_flag_id,
+ )
+ # Manually delete the flag and log the change
+ # The `changes_between` method won't catch this because the flag (and underlying ForeignKey relationship)
+ # will have been deleted by the time the `changes_between` method is called, so we need to log the change manually
+ changes.append(
+ Change(type="Survey", field="targeting_flag", action="deleted", before=instance.targeting_flag)
+ )
+ instance.targeting_flag.delete()
+ validated_data["targeting_flag_id"] = None
+ validated_data.pop("remove_targeting_flag")
+
+ # make sure instance.targeting_flag is gone
+ instance.refresh_from_db()
+
+ # if the target flag filters come back with data, update the targeting feature flag if there is one, otherwise create a new one
+ if validated_data.get("targeting_flag_filters"):
assert_feature_flag_write_scope(
self.context["request"],
- action="survey.update.remove_targeting_flag",
+ action="survey.update.targeting_flag_filters",
resource_scope="survey:write",
team_id=self.context["team_id"],
feature_flag_id=instance.targeting_flag_id,
)
- # Manually delete the flag and log the change
- # The `changes_between` method won't catch this because the flag (and underlying ForeignKey relationship)
- # will have been deleted by the time the `changes_between` method is called, so we need to log the change manually
- changes.append(
- Change(type="Survey", field="targeting_flag", action="deleted", before=instance.targeting_flag)
- )
- instance.targeting_flag.delete()
- validated_data["targeting_flag_id"] = None
- validated_data.pop("remove_targeting_flag")
-
- # make sure instance.targeting_flag is gone
- instance.refresh_from_db()
-
- # if the target flag filters come back with data, update the targeting feature flag if there is one, otherwise create a new one
- if validated_data.get("targeting_flag_filters"):
- assert_feature_flag_write_scope(
- self.context["request"],
- action="survey.update.targeting_flag_filters",
- resource_scope="survey:write",
- team_id=self.context["team_id"],
- feature_flag_id=instance.targeting_flag_id,
- )
- new_filters = validated_data["targeting_flag_filters"]
- if instance.targeting_flag:
- existing_targeting_flag = instance.targeting_flag
- existing_targeting_flag_filters = existing_targeting_flag.filters
- serialized_data_filters = {
- **existing_targeting_flag_filters,
- **new_filters,
- }
- # Log the existing filter change
- # The `changes_between` method won't catch this because the flag (and underlying ForeignKey relationship)
- # will have been deleted by the time the `changes_between` method is called, so we need to log the change manually
- changes.append(
- Change(
- type="Survey",
- field="targeting_flag_filters",
- action="changed",
- before=existing_targeting_flag_filters,
- after=new_filters,
+ new_filters = validated_data["targeting_flag_filters"]
+ if instance.targeting_flag:
+ existing_targeting_flag = instance.targeting_flag
+ existing_targeting_flag_filters = existing_targeting_flag.filters
+ serialized_data_filters = {
+ **existing_targeting_flag_filters,
+ **new_filters,
+ }
+ # Log the existing filter change
+ # The `changes_between` method won't catch this because the flag (and underlying ForeignKey relationship)
+ # will have been deleted by the time the `changes_between` method is called, so we need to log the change manually
+ changes.append(
+ Change(
+ type="Survey",
+ field="targeting_flag_filters",
+ action="changed",
+ before=existing_targeting_flag_filters,
+ after=new_filters,
+ )
)
- )
- self._create_or_update_targeting_flag(instance.targeting_flag, serialized_data_filters)
- else:
- new_flag = self._create_or_update_targeting_flag(
- None, new_filters, instance.name, bool(instance.start_date)
- )
- # Log the new filter change
- # The `changes_between` method won't catch this because the flag (and underlying ForeignKey relationship)
- # will have been deleted by the time the `changes_between` method is called, so we need to log the change manually
- changes.append(
- Change(type="Survey", field="targeting_flag_filters", action="created", after=new_filters)
- )
- validated_data["targeting_flag_id"] = new_flag.id
- validated_data.pop("targeting_flag_filters")
+ self._create_or_update_targeting_flag(instance.targeting_flag, serialized_data_filters)
+ else:
+ new_flag = self._create_or_update_targeting_flag(
+ None, new_filters, instance.name, bool(instance.start_date)
+ )
+ # Log the new filter change
+ # The `changes_between` method won't catch this because the flag (and underlying ForeignKey relationship)
+ # will have been deleted by the time the `changes_between` method is called, so we need to log the change manually
+ changes.append(
+ Change(type="Survey", field="targeting_flag_filters", action="created", after=new_filters)
+ )
+ validated_data["targeting_flag_id"] = new_flag.id
+ validated_data.pop("targeting_flag_filters")
iteration_count = validated_data.get("iteration_count", None)
if (
@@ -2088,36 +2098,39 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
def _create_or_update_targeting_flag(
self, existing_flag=None, filters=None, name=None, active=False, flag_name_suffix=None
):
+ request = self.context["request"]
+ team = self.context["get_team"]()
with create_flag_with_survey_errors():
- # Ensure the request method is set correctly for validation
+ # Ensure the request method is set correctly for validation. The facade passes a
+ # real request through as-is, so it does not set the method.
if existing_flag:
- self.context["request"].method = "PATCH"
- existing_flag_serializer = FeatureFlagSerializer(
+ request.method = "PATCH"
+ return update_flag(
existing_flag,
- data={"filters": filters},
- partial=True,
- context=self.context,
+ {"filters": filters},
+ team=team,
+ user=request.user,
+ request=request,
+ serializer_context=self.context,
)
- existing_flag_serializer.is_valid(raise_exception=True)
- return existing_flag_serializer.save()
else:
- self.context["request"].method = "POST"
+ request.method = "POST"
random_id = generate("1234567890abcdef", 10)
feature_flag_key = slugify(f"{SURVEY_TARGETING_FLAG_PREFIX}{random_id}{flag_name_suffix or ''}")
- feature_flag_serializer = FeatureFlagSerializer(
- data={
+ return create_flag(
+ {
"key": feature_flag_key,
"name": f"Targeting flag for survey {name}",
"filters": filters,
"active": active,
"creation_context": "surveys",
},
- context=self.context,
+ team=team,
+ user=request.user,
+ request=request,
+ serializer_context=self.context,
)
- feature_flag_serializer.is_valid(raise_exception=True)
- return feature_flag_serializer.save()
-
class SurveySerializerCreateUpdateOnlySchema(SurveySerializerCreateUpdateOnly):
linked_flag_id = serializers.IntegerField(
@@ -2268,7 +2281,7 @@ class SurveyFilterSet(FilterSet):
],
),
)
-class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
+class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
scope_object = "survey"
queryset = Survey.objects.select_related(
"linked_flag", "linked_insight", "targeting_flag", "internal_targeting_flag"
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index f1c7aad282ac..9137c124d759 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -32,6 +32,7 @@ from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
from products.actions.backend.models.action import Action
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.cohorts.backend.models.cohort import Cohort
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.facade.models import Insight
@@ -7556,6 +7557,124 @@ class TestSurveyLifecycleActions(APIBaseTest):
self.assertEqual(self.survey.end_date, original_end)
+class TestSurveyFlagWritesUnderApprovalPolicies(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}
+ ]
+ self.organization.save()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={
+ "name": "Survey under approval policies",
+ "type": "popover",
+ "questions": [{"type": "open", "question": "What do you think?"}],
+ "targeting_flag_filters": {
+ "groups": [
+ {
+ "properties": [
+ {"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ self.survey = Survey.objects.get(id=response.json()["id"])
+
+ def _create_policy(self, action_key: str) -> None:
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key=action_key,
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id], "roles": []},
+ allow_self_approve=True,
+ created_by=self.user,
+ )
+
+ def _flag_states(self) -> tuple[bool, bool]:
+ self.survey.refresh_from_db()
+ assert self.survey.targeting_flag is not None
+ assert self.survey.internal_targeting_flag is not None
+ return self.survey.targeting_flag.active, self.survey.internal_targeting_flag.active
+
+ @parameterized.expand([("feature_flag.enable",), ("feature_flag.disable",), ("feature_flag.update",)])
+ def test_start_and_stop_mirror_flag_state_without_a_change_request(self, action_key: str) -> None:
+ self._create_policy(action_key)
+ url = f"/api/projects/{self.team.id}/surveys/{self.survey.id}/"
+
+ response = self.client.patch(url, data={"start_date": datetime.now(UTC) - timedelta(days=1)}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._flag_states() == (True, True)
+
+ response = self.client.patch(url, data={"end_date": datetime.now(UTC) - timedelta(hours=1)}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._flag_states() == (False, False)
+
+ assert not ChangeRequest.objects.filter(team=self.team).exists()
+
+ def test_create_writes_its_internal_flag_through_the_rollout_gate(self) -> None:
+ self._create_policy("feature_flag.update")
+
+ surveys_before = Survey.objects.filter(team=self.team).count()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={"name": "Gated survey", "type": "popover", "questions": [{"type": "open", "question": "Q?"}]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ # The internal flag is written after the survey row, so a rejected gate must take the row with it.
+ assert Survey.objects.filter(team=self.team).count() == surveys_before
+ assert response.json()["status"] == "approval_required"
+ change_request = ChangeRequest.objects.get(team=self.team, action_key="feature_flag.update")
+ assert response.json()["change_request_id"] == str(change_request.id)
+
+ def test_targeting_filter_change_goes_through_the_rollout_gate(self) -> None:
+ self._create_policy("feature_flag.update")
+ assert self.survey.targeting_flag is not None
+ filters_before = self.survey.targeting_flag.filters
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{self.survey.id}/",
+ data={"targeting_flag_filters": {"groups": [{"properties": [], "rollout_percentage": 50}]}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ assert response.json()["status"] == "approval_required"
+ self.survey.targeting_flag.refresh_from_db()
+ assert self.survey.targeting_flag.filters == filters_before
+ change_request = ChangeRequest.objects.get(team=self.team, action_key="feature_flag.update")
+ assert response.json()["change_request_id"] == str(change_request.id)
+
+ def test_a_rejected_replacement_keeps_the_existing_targeting_flag(self) -> None:
+ self._create_policy("feature_flag.update")
+ assert self.survey.targeting_flag is not None
+ existing_flag_id = self.survey.targeting_flag.id
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{self.survey.id}/",
+ data={
+ "remove_targeting_flag": True,
+ "targeting_flag_filters": {"groups": [{"properties": [], "rollout_percentage": 25}]},
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ assert FeatureFlag.objects.filter(pk=existing_flag_id).exists()
+ self.survey.refresh_from_db()
+ assert self.survey.targeting_flag_id == existing_flag_id
+ assert ChangeRequest.objects.filter(team=self.team, action_key="feature_flag.update").exists()
+
+
class TestSurveyListTypeFilter(APIBaseTest):
def test_filter_by_type(self):
Survey.objects.create(team=self.team, name="popover survey", type="popover", questions=[])
diff --git a/products/surveys/frontend/generated/api.ts b/products/surveys/frontend/generated/api.ts
index 9631780b776c..710903ce828b 100644
--- a/products/surveys/frontend/generated/api.ts
+++ b/products/surveys/frontend/generated/api.ts
@@ -134,6 +134,13 @@ export const getSurveysListUrl = (projectId: string, params?: SurveysListParams)
: `/api/projects/${projectId}/surveys/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysList = async (
projectId: string,
params?: SurveysListParams,
@@ -149,6 +156,13 @@ export const getSurveysCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/surveys/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysCreate = async (
projectId: string,
surveySerializerCreateUpdateOnlySchemaApi: NonReadonly<SurveySerializerCreateUpdateOnlySchemaApi>,
@@ -166,6 +180,13 @@ export const getSurveysRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/surveys/${id}/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysRetrieve = async (projectId: string, id: string, options?: RequestInit): Promise<SurveyApi> => {
return apiMutator<SurveyApi>(getSurveysRetrieveUrl(projectId, id), {
...options,
@@ -177,6 +198,13 @@ export const getSurveysUpdateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/surveys/${id}/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysUpdate = async (
projectId: string,
id: string,
@@ -195,6 +223,13 @@ export const getSurveysPartialUpdateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/surveys/${id}/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysPartialUpdate = async (
projectId: string,
id: string,
@@ -213,6 +248,13 @@ export const getSurveysDestroyUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/surveys/${id}/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
return apiMutator<void>(getSurveysDestroyUrl(projectId, id), {
...options,
@@ -224,6 +266,13 @@ export const getSurveysActivityRetrieveUrl = (projectId: string, id: string) =>
return `/api/projects/${projectId}/surveys/${id}/activity/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysActivityRetrieve = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
return apiMutator<void>(getSurveysActivityRetrieveUrl(projectId, id), {
...options,
@@ -280,6 +329,13 @@ export const getSurveysGenerateTranslationsCreateUrl = (projectId: string, id: s
return `/api/projects/${projectId}/surveys/${id}/generate_translations/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysGenerateTranslationsCreate = async (
projectId: string,
id: string,
@@ -479,6 +535,13 @@ export const getSurveysSummaryHeadlineCreateUrl = (projectId: string, id: string
return `/api/projects/${projectId}/surveys/${id}/summary_headline/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysSummaryHeadlineCreate = async (
projectId: string,
id: string,
@@ -497,6 +560,13 @@ export const getSurveysAllActivityRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/surveys/activity/`
}
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysAllActivityRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
return apiMutator<void>(getSurveysAllActivityRetrieveUrl(projectId), {
...options,
diff --git a/products/surveys/frontend/generated/api.zod.ts b/products/surveys/frontend/generated/api.zod.ts
index 37d510d92c9d..285ca3b05bbe 100644
--- a/products/surveys/frontend/generated/api.zod.ts
+++ b/products/surveys/frontend/generated/api.zod.ts
@@ -70,6 +70,13 @@ export const DesktopFeedbackCreateBody = /* @__PURE__ */ zod.object({
image_2: zod.instanceof(File).optional().describe('Second image that the user attached.'),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysCreateBodyNameMax = 400
export const surveysCreateBodyTargetingFlagFiltersOneEarlyExitDefault = false
@@ -929,6 +936,13 @@ export const SurveysCreateBody = /* @__PURE__ */ zod.object({
form_content: zod.unknown().optional(),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysUpdateBodyNameMax = 400
export const surveysUpdateBodyTargetingFlagFiltersOneEarlyExitDefault = false
@@ -1788,6 +1802,13 @@ export const SurveysUpdateBody = /* @__PURE__ */ zod.object({
form_content: zod.unknown().optional(),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysPartialUpdateBodyNameMax = 400
export const surveysPartialUpdateBodyTargetingFlagFiltersOneEarlyExitDefault = false
@@ -2757,6 +2778,13 @@ export const SurveysDuplicateToProjectsCreateBody = /* @__PURE__ */ zod.object({
form_content: zod.unknown().optional(),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysGenerateTranslationsCreateBodyOverwriteDefault = false
export const SurveysGenerateTranslationsCreateBody = /* @__PURE__ */ zod.object({
@@ -2999,6 +3027,13 @@ export const SurveysSummarizeResponsesCreateBody = /* @__PURE__ */ zod.object({
.describe('When true, bypass cached summaries and regenerate. Defaults to false.'),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const surveysSummaryHeadlineCreateBodyNameMax = 400
export const surveysSummaryHeadlineCreateBodyResponsesLimitMin = 0
diff --git a/services/mcp/src/generated/surveys/api.ts b/services/mcp/src/generated/surveys/api.ts
index b7b99d8c167b..e4e24f787d9f 100644
--- a/services/mcp/src/generated/surveys/api.ts
+++ b/services/mcp/src/generated/surveys/api.ts
@@ -8,6 +8,13 @@
*/
import * as zod from 'zod'
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const SurveysListParams = () => zod.object({
project_id: zod
.string()
@@ -42,6 +49,13 @@ export const SurveysListQueryParams = () => zod.object({
),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const SurveysCreateParams = () => zod.object({
project_id: zod
.string()
@@ -909,6 +923,13 @@ export const SurveysCreateBody = () => zod.object({
form_content: zod.unknown().optional(),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const SurveysRetrieveParams = () => zod.object({
id: zod.string().describe('A UUID string identifying this survey.'),
project_id: zod
@@ -918,6 +939,13 @@ export const SurveysRetrieveParams = () => zod.object({
),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const SurveysPartialUpdateParams = () => zod.object({
id: zod.string().describe('A UUID string identifying this survey.'),
project_id: zod
@@ -1788,6 +1816,13 @@ export const SurveysPartialUpdateBody = () => zod.object({
form_content: zod.unknown().optional(),
})
+/**
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
+ *
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
+ */
export const SurveysDestroyParams = () => zod.object({
id: zod.string().describe('A UUID string identifying this survey.'),
project_id: zod
diff --git a/tach.toml b/tach.toml
index 3e1950479eb6..b278ac36a7ec 100644
--- a/tach.toml
+++ b/tach.toml
@@ -907,6 +907,7 @@ depends_on = [
"ee",
"posthog",
"products.actions",
+ "products.approvals",
"products.feature_flags",
"products.product_analytics",
"products.product_tours", "products.access_control",