: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(approvals): stop one pending flag create from blocking all others (#110770)
Yasen222621ef5d94
diff --git a/products/approvals/backend/actions/base.py b/products/approvals/backend/actions/base.pyindex 288ef6d9ddd8..2d0846219d6b 100644--- a/products/approvals/backend/actions/base.py+++ b/products/approvals/backend/actions/base.py@@ -73,6 +73,16 @@ class BaseAction(ABC):"""return base_context+ @classmethod+ def get_target_filter(cls, intent_data: dict[str, Any]) -> dict[str, Any]:+ """+ Return ChangeRequest filters that identify the target of a change request with no resource id.++ Every such change request stores resource_id as NULL, so without these filters the+ duplicate check matches every other one for the same action.+ """+ return {}+@classmethod@abstractmethoddef detect(cls, request, view, *args, **kwargs) -> bool:diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.pyindex 294c35d83c08..47fcf5f4823f 100644--- a/products/approvals/backend/actions/feature_flags.py+++ b/products/approvals/backend/actions/feature_flags.py@@ -82,6 +82,15 @@ def _get_flag_instance(view, *args, **kwargs) -> Optional[FeatureFlag]:return view.get_object()+def _flag_target_filter(intent_data: dict[str, Any]) -> dict[str, Any]:+ # An update of an existing flag can reach the gate as a POST, for example an experiment launch,+ # so it has no resource id either. Match it on the flag id, because the key can change while the+ # request waits. Only a create has no flag id, so a create matches other creates by key.+ if intent_data["flag_id"] is not None:+ return {"intent__flag_id": intent_data["flag_id"]}+ return {"intent__flag_id": None, "intent__flag_key": intent_data["flag_key"]}++def _check_version_staleness(intent_data: dict[str, Any], context: Optional[dict[str, Any]] = None) -> bool:"""Check staleness by comparing stored version precondition against current instance version."""preconditions = intent_data.get("preconditions", {})@@ -181,6 +190,10 @@ class FeatureFlagActionBase(BaseAction):# Subclasses define the target statetarget_active_state: bool+ @classmethod+ def get_target_filter(cls, intent_data: dict[str, Any]) -> dict[str, Any]:+ return _flag_target_filter(intent_data)+@classmethoddef check_staleness(cls,@@ -418,6 +431,10 @@ class UpdateFeatureFlagAction(BaseAction):intent_fields = ["rollout_percentage"]+ @classmethod+ def get_target_filter(cls, intent_data: dict[str, Any]) -> dict[str, Any]:+ return _flag_target_filter(intent_data)+@classmethoddef check_staleness(cls,diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.pyindex 54a4a633eb8e..eddf7dfe0c33 100644--- a/products/approvals/backend/decorators.py+++ b/products/approvals/backend/decorators.py@@ -101,14 +101,19 @@ def _check_policy_for_action(action_class, team, organization) -> Optional[Any]:return None-def _check_for_duplicate(action_class, team, resource_id: Optional[str]) -> Optional[ChangeRequest]:+def _check_for_duplicate(+ action_class, team, resource_id: Optional[str], intent_data: dict[str, Any]+) -> Optional[ChangeRequest]:"""Check if there's already a pending/approved change request."""+ target_filter = action_class.get_target_filter(intent_data) if resource_id is None else {}+return ChangeRequest.objects.filter(action_key=action_class.key,team=team,resource_type=action_class.resource_type,resource_id=resource_id,state__in=[ChangeRequestState.PENDING, ChangeRequestState.APPROVED],+ **target_filter,).first()@@ -321,7 +326,7 @@ def _evaluate_gate(# Step 5: REQUIRE_APPROVAL - check for duplicates and create change requestresource_id = _extract_resource_id(request, args, kwargs)- existing = _check_for_duplicate(action_class, team, resource_id)+ existing = _check_for_duplicate(action_class, team, resource_id, intent_data)if existing:logger.info("Rejecting duplicate change request",diff --git a/products/approvals/backend/tests/test_create_feature_flag_gate.py b/products/approvals/backend/tests/test_create_feature_flag_gate.pyindex dd995331f6c2..db469d0e1303 100644--- a/products/approvals/backend/tests/test_create_feature_flag_gate.py+++ b/products/approvals/backend/tests/test_create_feature_flag_gate.py@@ -3,6 +3,8 @@ from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from products.approvals.backend.actions.feature_flags import (DisableFeatureFlagAction,EnableFeatureFlagAction,@@ -242,6 +244,35 @@ class TestCreateFlagGateAPI(APIBaseTest):flag = FeatureFlag.objects.get(team=self.team, key="remote-config-flag")assert flag.filters["groups"][0]["rollout_percentage"] == 100+ @parameterized.expand(+ [+ ("other_key", "second-flag", "approval_required", ["first-flag", "second-flag"]),+ ("same_key", "first-flag", "change_request_pending", ["first-flag"]),+ ]+ )+ def test_pending_create_blocks_only_a_create_for_the_same_key(+ self, _mock_enabled, _name, second_key, expected_code, expected_pending_keys+ ):+ # A create has no resource id yet, so resource_id cannot tell two pending creates apart.+ # The duplicate check must compare the flag key. Otherwise one pending create blocks every+ # other create in the project with a 409 that names someone else's change request.+ self._update_policy({"type": "any_change", "field": "rollout_percentage"})++ def create(key: str) -> Any:+ return self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"key": key, "active": False, "filters": {"groups": [{"rollout_percentage": 0}]}},+ format="json",+ )++ assert create("first-flag").json().get("code") == "approval_required"+ response = create(second_key)++ assert response.status_code == 409, response.content+ assert response.json().get("code") == expected_code+ pending = ChangeRequest.objects.filter(team=self.team, state=ChangeRequestState.PENDING)+ assert sorted(cr.intent["flag_key"] for cr in pending) == expected_pending_keys+def test_reapplying_create_change_request_does_not_duplicate(self, _mock_enabled):self._enable_policy()diff --git a/products/approvals/backend/tests/test_decorators.py b/products/approvals/backend/tests/test_decorators.pyindex 72090c429260..6330edc1e680 100644--- a/products/approvals/backend/tests/test_decorators.py+++ b/products/approvals/backend/tests/test_decorators.py@@ -14,7 +14,7 @@ from posthog.api.utils import ServiceRequestfrom products.approvals.backend.decorators import _create_change_requestfrom products.approvals.backend.exceptions import ApprovalRequired-from products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestStatefrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -168,6 +168,37 @@ class TestApprovalGateFailsClosed(_ApprovalGateFixtures):assert flag.active is False+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+class TestDuplicateCheckForPostUpdate(_ApprovalGateFixtures):+ def test_renamed_flag_still_matches_its_pending_change_request(self, _mock_enabled):+ # An update of an existing flag can reach the gate as a POST, for example an experiment+ # launch. Its change request then has no resource id, and its key can change while it waits.+ flag = self._create_disabled_flag()+ self._create_enable_policy()+ request = self._drf_request({"active": True})+ request.method = "POST"+ context = {+ "request": request,+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ "get_team": lambda: self.team,+ "get_organization": lambda: self.organization,+ }++ with self.assertRaises(ApprovalRequired) as first:+ self._serializer(flag, {"active": True}, context).save()++ FeatureFlag.objects.filter(id=flag.id).update(key="renamed-flag")+ flag.refresh_from_db()++ with self.assertRaises(ApprovalRequired) as second:+ self._serializer(flag, {"active": True}, context).save()++ assert second.exception.error_code == "change_request_pending"+ assert second.exception.change_request.id == first.exception.change_request.id+ assert ChangeRequest.objects.filter(team=self.team, state=ChangeRequestState.PENDING).count() == 1++class TestChangeRequestIntentIsJsonSafe(APIBaseTest):"""`intent` holds the endpoint serializer's validated_data, which carries native Pythonobjects for typed fields. A `datetime` in there used to abort the INSERT inside psycopg and