: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(surveys): create surveys under feature flag approval policies (#125955)
Phil Haack70f22ac817b6
diff --git a/frontend/src/scenes/surveys/surveyLogic.test.ts b/frontend/src/scenes/surveys/surveyLogic.test.tsindex 7df55a2c6b27..20470e4a25fc 100644--- a/frontend/src/scenes/surveys/surveyLogic.test.ts+++ b/frontend/src/scenes/surveys/surveyLogic.test.ts@@ -1,6 +1,8 @@import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'+import { lemonToast } from '@posthog/lemon-ui'+import api from 'lib/api'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { dayjs } from 'lib/dayjs'@@ -2501,6 +2503,42 @@ describe('surveyLogic archived response refresh', () => {})})+describe('surveyLogic update that needs approval', () => {+ let logic: ReturnType<typeof surveyLogic.build>++ beforeEach(async () => {+ initKeaTests()++ useMocks({+ get: {+ '/api/projects/:team/surveys/': () => [200, { count: 0, results: [], next: null, previous: null }],+ '/api/projects/:team/surveys/test-survey/': () => [200, createPersistedSurvey()],+ '/api/projects/:team/surveys/test-survey/archived-response-uuids/': () => [200, []],+ },+ })+ jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)++ logic = surveyLogic({ id: 'test-survey' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ it('tells the user the change waits for approval and reloads the saved survey', async () => {+ const info = jest.spyOn(lemonToast, 'info')+ jest.spyOn(api.surveys, 'update').mockRejectedValue({+ status: 409,+ detail: 'This change needs approval.',+ data: { change_request_id: 'cr-1', resource_type: 'feature_flag', resource_id: '7' },+ })++ await expectLogic(logic, () => {+ logic.actions.updateSurvey({ name: 'Renamed' })+ }).toDispatchActions(['updateSurveyFailure', 'loadSurvey'])++ expect(info).toHaveBeenCalled()+ })+})+describe('processResultsForSurveyQuestions', () => {// Input format: AggregateRow[] = [question_id, label, count][]describe('Rating Questions', () => {diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsxindex a530d4fc4c4d..3858d356124d 100644--- a/frontend/src/scenes/surveys/surveyLogic.tsx+++ b/frontend/src/scenes/surveys/surveyLogic.tsx@@ -21,6 +21,7 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { isApprovalRequiredError } from 'lib/api-error'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { FEATURE_FLAGS } from 'lib/constants'@@ -30,6 +31,7 @@ import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { isObject } from 'lib/utils/guards'import { hasFormErrors, objectClean } from 'lib/utils/objects'import { allOperatorsMapping } from 'lib/utils/operators'+import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { projectLogic } from 'scenes/projectLogic'import { Scene } from 'scenes/sceneTypes'@@ -2014,6 +2016,15 @@ export const surveyLogic = kea<surveyLogicType>([derivedPrompt: survey.name ? `Create a ${surveyType}survey called ${survey.name}` : undefined,})},+ updateSurveyFailure: ({ errorObject }) => {+ // The global error handler skips approval 409s, so without this a targeting change that+ // waits for approval looks like a save that did nothing.+ if (isApprovalRequiredError(errorObject)) {+ showApprovalRequiredToast(errorObject.data.change_request_id, undefined, errorObject.data.code)+ // The backend saved none of the edits, so drop the form state that shows them as saved.+ actions.loadSurvey()+ }+ },updateSurveySuccess: ({ survey }) => {lemonToast.success(<>Survey {survey.name} updated</>)actions.editingSurvey(false)diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.pyindex a213721ed3c7..66537dff98e2 100644--- a/products/approvals/backend/actions/feature_flags.py+++ b/products/approvals/backend/actions/feature_flags.py@@ -17,7 +17,7 @@ from products.approvals.backend.ownership import OWNER_KIND_UNOWNED, owner_in_scfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, flag_version_conflict_messagefrom products.feature_flags.backend.api.filters_schema import FEATURE_FLAG_OPERATOR_ALIASESfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.feature_flags.backend.ownership import flag_owner_kind+from products.feature_flags.backend.ownership import MINTED_OWNER_CONTEXT_KEY, flag_owner_kind# The property filter keys that flag evaluation reads. The API adds display keys such as# `cohort_name` on read, and the flag editor sends them back on every save, so any other key is not@@ -245,17 +245,24 @@ def _cached_owner_kind(flag: FeatureFlag) -> Optional[str]:return getattr(flag, _OWNER_KIND_ATTR)-def _in_family_scope(flag: Optional[FeatureFlag], owner_scope: Optional[str], team) -> bool:+def _minted_owner_kind(view) -> Optional[str]:+ context = getattr(view, "context", None)+ return context.get(MINTED_OWNER_CONTEXT_KEY) if isinstance(context, dict) else None+++def _in_family_scope(+ flag: Optional[FeatureFlag], owner_scope: Optional[str], team, minted_owner: Optional[str] = None+) -> bool:"""Whether this action's family governs this flag, given which product owns it.- A create has no flag yet and so no owner, which leaves it with the unowned family. That is not- a hole: the flag a product mints is unowned for the instant it is written, because the row that- will own it does not exist yet.+ A create has no flag yet. The row that will own the flag does not exist yet either, so the+ owner of a create is the product that declared it mints the flag, see+ `MINTED_OWNER_CONTEXT_KEY`. A create that declares no owner stays with the unowned family."""return owner_in_scope(owner_scope,team.organization if team is not None else None,- lambda: _cached_owner_kind(flag) if flag is not None else None,+ lambda: _cached_owner_kind(flag) if flag is not None else minted_owner,)@@ -487,7 +494,7 @@ class FeatureFlagActionBase(BaseAction):if not team:return False- return _in_family_scope(flag, cls.owner_scope, team)+ return _in_family_scope(flag, cls.owner_scope, team, _minted_owner_kind(view))@classmethoddef extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:@@ -803,7 +810,7 @@ class UpdateFeatureFlagAction(BaseAction):if not team:return False- return _in_family_scope(flag, cls.owner_scope, team)+ return _in_family_scope(flag, cls.owner_scope, team, _minted_owner_kind(view))@classmethoddef extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:diff --git a/products/approvals/backend/tests/test_create_feature_flag_gate.py b/products/approvals/backend/tests/test_create_feature_flag_gate.pyindex db469d0e1303..c7fd0060172d 100644--- a/products/approvals/backend/tests/test_create_feature_flag_gate.py+++ b/products/approvals/backend/tests/test_create_feature_flag_gate.py@@ -13,6 +13,7 @@ from products.approvals.backend.actions.feature_flags import (from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestStatefrom products.approvals.backend.services import ChangeRequestServicefrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.ownership import FLAG_OWNER_SURVEY, MINTED_OWNER_CONTEXT_KEYclass TestCreateDetection(APIBaseTest):@@ -202,6 +203,24 @@ class TestCreateFlagGateAPI(APIBaseTest):flag = FeatureFlag.objects.get(team=self.team, key="rollout-gated")assert flag.filters["groups"][0]["rollout_percentage"] == 100+ def test_public_create_cannot_claim_a_product_owner(self, _mock_enabled):+ self._update_policy()++ with patch("products.approvals.backend.ownership.scope_by_owner_enabled", return_value=True):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "claims-survey-owner",+ "active": False,+ "filters": {"groups": [{"rollout_percentage": 100}]},+ MINTED_OWNER_CONTEXT_KEY: FLAG_OWNER_SURVEY,+ },+ format="json",+ )++ assert response.status_code == 409, response.json()+ assert not FeatureFlag.objects.filter(team=self.team, key="claims-survey-owner").exists()+def test_create_active_flag_with_rollout_under_both_policies_is_rejected(self, _mock_enabled):# A create that both enables the flag AND sets its rollout trips the enable policy and the# rollout-update policy at once. A single ChangeRequest carries one action's approval, anddiff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.pyindex a525f39558da..bea62d1e7faf 100644--- a/products/feature_flags/backend/facade/api.py+++ b/products/feature_flags/backend/facade/api.py@@ -47,7 +47,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLfrom products.feature_flags.backend.facade.config import detect_config_formatfrom products.feature_flags.backend.facade.filters import set_feature_enrollmentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.feature_flags.backend.ownership import flag_owner_kind+from products.feature_flags.backend.ownership import MINTED_OWNER_CONTEXT_KEY, flag_owner_kindfrom products.feature_flags.backend.request_usage import (FeatureFlagRequestType as FeatureFlagRequestType,FeatureFlagRequestUsage as FeatureFlagRequestUsage,@@ -97,6 +97,7 @@ def create_flag(user: Any,request: Any | None = None,serializer_context: dict | None = None,+ owner: Literal["survey"] | None = None,) -> FeatureFlag:"""Gated create: routes through FeatureFlagSerializer so @approval_gate, validation,and activity logging apply. ``data`` is the flag's own write shape (key, name, filters,@@ -105,8 +106,12 @@ def create_flag(``created_by`` stays null, activity is logged as system, the approval gate is skipped.``serializer_context`` is extra serializer context (an HTTP caller passes its viewsetcontext); the facade's own ``request``, ``team_id``, ``project_id``, ``get_team`` and- ``get_organization`` entries win over the caller's."""+ ``get_organization`` entries win over the caller's. ``owner`` names the product that will own+ the new flag, so the approval gate applies that product's policies to the create instead of the+ policies for flags no product owns. Pass it only when the caller links the flag to its own row+ in the same transaction."""context = {**(serializer_context or {}), **_serializer_context(team, user, request)}+ context[MINTED_OWNER_CONTEXT_KEY] = ownerserializer = FeatureFlagSerializer(data=data, context=context)serializer.is_valid(raise_exception=True)return serializer.save()diff --git a/products/feature_flags/backend/ownership.py b/products/feature_flags/backend/ownership.pyindex c7a0db8c1287..de480b9dd3b9 100644--- a/products/feature_flags/backend/ownership.py+++ b/products/feature_flags/backend/ownership.py@@ -1,4 +1,4 @@-from typing import TYPE_CHECKING, Optional, cast+from typing import TYPE_CHECKING, Final, Optional, castfrom django.db.models import Case, CharField, Count, Exists, Model, OuterRef, QuerySet, Value, Whenfrom django.db.models.fields.reverse_related import ForeignObjectRel@@ -11,10 +11,15 @@ from products.feature_flags.backend.facade.config import detect_config_formatif TYPE_CHECKING:from products.feature_flags.backend.models.feature_flag import FeatureFlag-FLAG_OWNER_EXPERIMENT = "experiment"-FLAG_OWNER_SURVEY = "survey"-FLAG_OWNER_PRODUCT_TOUR = "product_tour"-FLAG_OWNER_EARLY_ACCESS = "early_access_feature"+FLAG_OWNER_EXPERIMENT: Final = "experiment"+FLAG_OWNER_SURVEY: Final = "survey"+FLAG_OWNER_PRODUCT_TOUR: Final = "product_tour"+FLAG_OWNER_EARLY_ACCESS: Final = "early_access_feature"++# Serializer context key that names the product a create mints its flag for. Only the flag facade+# sets it, from `create_flag(owner=...)`. Request data never reaches serializer context, so a caller+# of the public flag API cannot claim an owner to move a flag out of the `feature_flag.*` policies.+MINTED_OWNER_CONTEXT_KEY = "approval_minted_owner_kind"_OWNER_LABELS = {FLAG_OWNER_EXPERIMENT: "an experiment",diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex e7053ddd0683..856858dee52b 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -72,6 +72,7 @@ from products.access_control.backend.presentation.access_control import ()from products.actions.backend.api.action import ActionSerializer, ActionStepJSONSerializerfrom products.actions.backend.models.action import Action+from products.approvals.backend.exceptions import ApprovalRequiredfrom products.approvals.backend.presentation.mixins import ApprovalHandlingMixinfrom products.approvals.backend.transactions import gated_atomicfrom products.feature_flags.backend.api.feature_flag import (@@ -1922,10 +1923,12 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):team_id=self.context["team_id"],feature_flag_id=validated_data["targeting_flag_id"],)- # 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():+ # The survey row and its flags are one unit. A flag write can fail 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. A create only mints flags.+ # `_create_or_update_targeting_flag` turns a gated mint into a 400 and rolls back its+ # change request in a savepoint, so `gated_atomic` has nothing to restore here.+ with transaction.atomic():if validated_data.get("targeting_flag_filters"):assert_feature_flag_write_scope(self.context["request"],@@ -1978,9 +1981,23 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):feature_flag_id=validated_data["targeting_flag_id"],)+ # Validate before any flag write. A flag minted below commits with the block, so a+ # rejection after it would leave an active flag that no survey links.+ iteration_count = validated_data.get("iteration_count", None)+ if (+ instance.current_iteration is not None+ and iteration_count is not None+ and instance.current_iteration > iteration_count > 0+ ):+ raise serializers.ValidationError(+ f"Cannot change survey recurrence to {iteration_count}, should be at least {instance.current_iteration}"+ )+# 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.+ # rejected change leaves the survey with no targeting flag at all. The survey row and+ # its internal flags join the block, so a gate refusing an internal flag cannot leave+ # the edits saved behind a 400.with gated_atomic():if validated_data.get("remove_targeting_flag"):if instance.targeting_flag:@@ -2047,31 +2064,37 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):validated_data["targeting_flag_id"] = new_flag.idvalidated_data.pop("targeting_flag_filters")- iteration_count = validated_data.get("iteration_count", None)- if (- instance.current_iteration is not None- and iteration_count is not None- and instance.current_iteration > iteration_count > 0- ):- raise serializers.ValidationError(- f"Cannot change survey recurrence to {iteration_count}, should be at least {instance.current_iteration}"+ if iteration_count is not None:+ instance.iteration_count = iteration_count+ instance.iteration_frequency_days = validated_data.get("iteration_frequency_days")++ instance = super().update(instance, validated_data)++ team = Team.objects.get(id=self.context["team_id"])+ # `changes_between` will not catch changes to the ForeignKey relationships+ # so it's useful for any changes to the Survey model itself, but not for the related models+ non_foreign_table_relation_changes = changes_between(+ "Survey",+ previous=before_update,+ current=instance,)+ changes.extend(non_foreign_table_relation_changes)- if iteration_count is not None:- instance.iteration_count = iteration_count- instance.iteration_frequency_days = validated_data.get("iteration_frequency_days")+ should_flag_be_active = self._should_survey_flags_be_active(instance)- instance = super().update(instance, validated_data)+ # Intentionally NOT gated on feature_flag:write: this only syncs the active state of+ # the survey's OWN dedicated targeting flag to the survey's running state (start/stop/+ # archive), which survey:write already controls. The flag's definition (its filters)+ # can only be set via the gated targeting_flag_filters path. Enforcement covers+ # definition writes, not this lifecycle mirror.+ if instance.targeting_flag:+ instance.targeting_flag.active = should_flag_be_active+ instance.targeting_flag.save()++ 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"])- # `changes_between` will not catch changes to the ForeignKey relationships- # so it's useful for any changes to the Survey model itself, but not for the related models- non_foreign_table_relation_changes = changes_between(- "Survey",- previous=before_update,- current=instance,- )- changes.extend(non_foreign_table_relation_changes)log_activity(organization_id=team.organization_id,team_id=self.context["team_id"],@@ -2118,21 +2141,6 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):team=team,request=self.context["request"],)-- should_flag_be_active = self._should_survey_flags_be_active(instance)-- # Intentionally NOT gated on feature_flag:write: this only syncs the active state of- # the survey's OWN dedicated targeting flag to the survey's running state (start/stop/- # archive), which survey:write already controls. The flag's definition (its filters)- # can only be set via the gated targeting_flag_filters path. Enforcement covers- # definition writes, not this lifecycle mirror.- if instance.targeting_flag:- instance.targeting_flag.active = should_flag_be_active- instance.targeting_flag.save()-- self._add_user_survey_interacted_filters(instance)- self._associate_actions(instance, validated_data.get("conditions"))- self._add_internal_response_sampling_filters(instance)return instancedef _add_internal_response_sampling_filters(self, instance: Survey):@@ -2295,19 +2303,30 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):request.method = "POST"random_id = generate("1234567890abcdef", 10)feature_flag_key = slugify(f"{SURVEY_TARGETING_FLAG_PREFIX}{random_id}{flag_name_suffix or ''}")- return create_flag(- {- "key": feature_flag_key,- "name": f"Targeting flag for survey {name}",- "filters": filters,- "active": active,- "creation_context": "surveys",- },- team=team,- user=request.user,- request=request,- serializer_context=self.context,- )+ # An approved change request replays only the flag write. The survey that links the+ # flag is not part of it, so approval would create an orphan flag and no survey.+ # Refuse the write instead, and let the savepoint take the change request with it.+ try:+ with transaction.atomic():+ return create_flag(+ {+ "key": feature_flag_key,+ "name": f"Targeting flag for survey {name}",+ "filters": filters,+ "active": active,+ "creation_context": "surveys",+ },+ team=team,+ user=request.user,+ request=request,+ serializer_context=self.context,+ owner=FLAG_OWNER_SURVEY,+ )+ except ApprovalRequired:+ raise serializers.ValidationError(+ "A feature flag approval policy covers the flag this survey needs, so the survey "+ "can't be saved. Ask someone who can bypass the policy to save it."+ )class SurveySerializerCreateUpdateOnlySchema(SurveySerializerCreateUpdateOnly):diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 37d6a8cce814..3cfb668b55ba 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -5409,17 +5409,21 @@ class TestSurveysRecurringIterations(APIBaseTest):survey.refresh_from_db()survey.current_iteration = 2survey.save()+ flags_before = FeatureFlag.objects.filter(team=self.team).count()response = self.client.patch(f"/api/projects/{self.team.id}/surveys/{survey.id}/",data={"start_date": datetime.now() - timedelta(days=1),"iteration_count": 1,"iteration_frequency_days": 30,+ "targeting_flag_filters": {"groups": [{"properties": [], "rollout_percentage": 25}]},},+ format="json",)assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json()["detail"] == "Cannot change survey recurrence to 1, should be at least 2"+ assert FeatureFlag.objects.filter(team=self.team).count() == flags_before@parameterized.expand([@@ -7891,7 +7895,7 @@ class TestSurveyFlagWritesUnderApprovalPolicies(APIBaseTest):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:+ def _create_policy(self, action_key: str, bypass_org_membership_levels: list[int] | None = None) -> None:ApprovalPolicy.objects.create(organization=self.organization,team=self.team,@@ -7899,6 +7903,7 @@ class TestSurveyFlagWritesUnderApprovalPolicies(APIBaseTest):conditions={},approver_config={"quorum": 1, "users": [self.user.id], "roles": []},allow_self_approve=True,+ bypass_org_membership_levels=bypass_org_membership_levels or [],created_by=self.user,)@@ -7923,23 +7928,91 @@ class TestSurveyFlagWritesUnderApprovalPolicies(APIBaseTest):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")-+ @parameterized.expand(+ [+ ("scoped_by_owner", True, False, True, status.HTTP_201_CREATED),+ ("flag_policies_cover_every_flag", False, False, True, status.HTTP_400_BAD_REQUEST),+ ("flag_policies_cover_every_flag_but_the_user_bypasses", False, True, True, status.HTTP_201_CREATED),+ ("internal_flag_refused_after_the_row_is_saved", False, False, False, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_create_mints_its_flags_without_a_change_request(+ self, _name: str, scoped_by_owner: bool, user_bypasses: bool, with_targeting: bool, expected_status: int+ ) -> None:+ self._create_policy(+ "feature_flag.update",+ bypass_org_membership_levels=[self.organization_membership.level] if user_bypasses else None,+ )surveys_before = Survey.objects.filter(team=self.team).count()+ data: dict = {"name": "Gated survey", "type": "popover", "questions": [{"type": "open", "question": "Q?"}]}+ if with_targeting:+ data["targeting_flag_filters"] = {+ "groups": [+ {+ "properties": [+ {"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}+ ],+ "rollout_percentage": 100,+ }+ ]+ }- response = self.client.post(- f"/api/projects/{self.team.id}/surveys/",- data={"name": "Gated survey", "type": "popover", "questions": [{"type": "open", "question": "Q?"}]},- format="json",- )+ with patch("products.approvals.backend.ownership.scope_by_owner_enabled", return_value=scoped_by_owner):+ response = self.client.post(f"/api/projects/{self.team.id}/surveys/", data=data, 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)+ assert response.status_code == expected_status, response.json()+ created = expected_status == status.HTTP_201_CREATED+ if not created:+ assert "approval policy" in response.json()["detail"]+ assert Survey.objects.filter(team=self.team).count() == surveys_before + (1 if created else 0)+ assert not ChangeRequest.objects.filter(team=self.team).exists()+ if created:+ survey = Survey.objects.get(id=response.json()["id"])+ assert survey.internal_targeting_flag is not None+ assert (survey.targeting_flag is not None) == with_targeting++ def test_create_with_a_past_start_date_mints_active_flags_under_an_enable_policy(self) -> None:+ self._create_policy("feature_flag.enable")++ with patch("products.approvals.backend.ownership.scope_by_owner_enabled", return_value=True):+ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={+ "name": "Started survey",+ "type": "popover",+ "questions": [{"type": "open", "question": "Q?"}],+ "start_date": (datetime.now(UTC) - timedelta(days=1)).isoformat(),+ },+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ survey = Survey.objects.get(id=response.json()["id"])+ assert survey.internal_targeting_flag is not None+ assert survey.internal_targeting_flag.active+ assert not ChangeRequest.objects.filter(team=self.team).exists()++ def test_update_rolls_back_every_edit_when_the_gate_refuses_an_internal_flag(self) -> None:+ self._create_policy("feature_flag.update")++ with patch("products.approvals.backend.ownership.scope_by_owner_enabled", return_value=False):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/surveys/{self.survey.id}/",+ data={+ "name": "Renamed survey",+ "response_sampling_interval_type": "day",+ "response_sampling_interval": 10,+ "response_sampling_limit": 500,+ "response_sampling_start_date": datetime(2024, 12, 12).isoformat(),+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ self.survey.refresh_from_db()+ assert self.survey.name == "Survey under approval policies"+ assert self.survey.internal_response_sampling_flag is None+ assert not ChangeRequest.objects.filter(team=self.team).exists()def test_targeting_filter_change_goes_through_the_rollout_gate(self) -> None:self._create_policy("feature_flag.update")@@ -7973,11 +8046,11 @@ class TestSurveyFlagWritesUnderApprovalPolicies(APIBaseTest):format="json",)- assert response.status_code == status.HTTP_409_CONFLICT, response.json()+ assert response.status_code == status.HTTP_400_BAD_REQUEST, 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()+ assert not ChangeRequest.objects.filter(team=self.team).exists()class TestSurveyListTypeFilter(APIBaseTest):