: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
chore(early-access): clear enrollment flags through the flag facade (#107820)
Yasena23b2ce01b57
diff --git a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txtindex 635537b2e145..f1582093964c 100644--- a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt+++ b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt@@ -11,8 +11,8 @@ posthog/management/commands/sync_feature_flags_from_api.py::sync_feature_flags_fproducts/demo/backend/logic/matrix/matrix.py::Matrix.set_project_up::FeatureFlag.objects.create()products/demo/backend/logic/products/hedgebox/matrix.py::HedgeboxMatrix.set_project_up.create_experiment_flag::FeatureFlag.objects.create()products/demo/backend/logic/products/hedgebox/matrix.py::HedgeboxMatrix.set_project_up::FeatureFlag.objects.create()-products/early_access_features/backend/api.py::clear_feature_enrollment::feature_flag.filters =products/feature_flags/backend/facade/api.py::_set_trashed_flag_active::FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id, team_id=team_id).update()+products/feature_flags/backend/facade/api.py::clear_feature_enrollment::flag.filters =products/feature_flags/evals/seeders.py::_create_flag::FeatureFlag.objects.create()products/feature_flags/evals/seeders.py::seed_stale_full_rollout_flag::FeatureFlag.objects.create()products/feature_flags/evals/seeders.py::seed_stale_partial_rollout_flag::FeatureFlag.objects.create()diff --git a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py b/posthog/test/repo_invariants/test_feature_flag_gated_writes.pyindex 4d7d8d9edcad..92511f422cb9 100644--- a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py+++ b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py@@ -24,9 +24,8 @@ 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/feature_flags/backend/facade/api.py": "file-system trash and restore flip active",+ "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",- "products/early_access_features/backend/api.py": "never-fail cleanup when stored filters fail validation","posthog/management/commands/generate_random_product_tours.py": "local data generator","posthog/management/commands/reencrypt_flag_payloads.py": "payload re-encryption command","posthog/management/commands/sync_feature_flags.py": "local dev flag sync",diff --git a/products/early_access_features/backend/api.py b/products/early_access_features/backend/api.pyindex 1c883d0f989f..ec37842c1a4c 100644--- a/products/early_access_features/backend/api.py+++ b/products/early_access_features/backend/api.py@@ -6,7 +6,6 @@ from django.http import JsonResponsefrom django.utils.text import slugifyfrom django.views.decorators.csrf import csrf_exempt-import structlogfrom drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializers, status, viewsetsfrom rest_framework.exceptions import PermissionDenied@@ -35,15 +34,13 @@ from products.feature_flags.backend.api.feature_flag import (assert_feature_flag_write_scope,)from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE-from products.feature_flags.backend.facade.api import create_flag, update_flag+from products.feature_flags.backend.facade.api import clear_feature_enrollment, create_flag, update_flagfrom products.feature_flags.backend.facade.filters import set_feature_enrollmentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.ownership import FLAG_OWNER_EARLY_ACCESS, assert_flag_available_for, flag_owner_kindfrom .models import EarlyAccessFeature-logger = structlog.get_logger(__name__)-def assert_feature_flag_rbac_access(user_access_control: UserAccessControl | None,@@ -77,35 +74,6 @@ def derive_feature_flag_key(feature_name: str) -> str:return slugify(feature_name)-def clear_feature_enrollment(feature_flag: FeatureFlag, *, team: Team) -> None:- """Clear the enrollment marker on a feature's linked flag (feature demoted or deleted).-- Cleanup must never fail: a linked flag can hold stored filter shapes the current- FeatureFlagSerializer rejects or crashes on (group-aggregated conditions, malformed- legacy properties, ...), and a rejection here would make the feature undeletable.- Prefer the gated facade write (validation, activity logging); fall back to a raw- model write when it raises. This is a system write (user=None): an enabled approval- policy must never block cleanup with a 409, and activity is logged as system.- """- cleared_filters = set_feature_enrollment(feature_flag.get_filters() or {}, None)- # Without "groups", the serializer's partial-PATCH shortcut discards the incoming- # filters and returns the stored ones — silently skipping the cleanup entirely.- if "groups" in cleared_filters:- try:- update_flag(feature_flag, {"filters": cleared_filters}, team=team, user=None)- return- except Exception as exc:- # Stored legacy JSON can raise arbitrary exception types through the flag- # validator (ValidationError, TypeError, KeyError, ...), so catch broadly.- logger.warning(- "early_access_feature_enrollment_cleanup_fell_back_to_raw_write",- feature_flag_id=feature_flag.id,- error=str(exc),- )- feature_flag.filters = cleared_filters # nosemgrep: feature-flags-no-raw-filters-access -- deliberate never-fail cleanup fallback when the gated write can't validate stored legacy filter shapes- feature_flag.save(update_fields=["filters"])--class MinimalEarlyAccessFeatureSerializer(serializers.ModelSerializer):"""A more minimal serializer, intended specificaly for non-generally-available features to be provided@@ -350,7 +318,11 @@ class EarlyAccessFeatureSerializer(UserAccessControlSerializerMixin, serializersfeature_flag_id=related_feature_flag.id,)assert_feature_flag_rbac_access(self.user_access_control, feature_flag=related_feature_flag)- clear_feature_enrollment(related_feature_flag, team=self.context["get_team"]())+ clear_feature_enrollment(related_feature_flag.id, team=self.context["get_team"]())+ # clear_feature_enrollment loads the flag by id and saves that copy, not this+ # instance. Reload the whole row: the response carries version, and a client that+ # sends a stale one to a rollout action gets a 409.+ related_feature_flag.refresh_from_db()updated_instance = super().update(instance, validated_data)@@ -577,7 +549,7 @@ class EarlyAccessFeatureViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiresource_scope="early_access_feature:write",)assert_feature_flag_rbac_access(self.user_access_control, feature_flag=related_feature_flag)- clear_feature_enrollment(related_feature_flag, team=self.team)+ clear_feature_enrollment(related_feature_flag.id, team=self.team)return super().destroy(request, *args, **kwargs)diff --git a/products/early_access_features/backend/apps.py b/products/early_access_features/backend/apps.pyindex 3fa2bd4e0a82..f0b00001d150 100644--- a/products/early_access_features/backend/apps.py+++ b/products/early_access_features/backend/apps.py@@ -35,12 +35,12 @@ class EarlyAccessFeaturesConfig(AppConfig):def _pre_delete(context, feature):feature_flag = getattr(feature, "feature_flag", None)if feature_flag:- # Deferred: the api module imports the feature_flag -> dashboard -> error_tracking+ # Deferred: the flag facade imports the feature_flag -> dashboard -> error_tracking# query-runner chain (-> scipy) at module scope. This hook only runs on actual# deletion, so importing it here keeps that chain off AppConfig.ready() / startup.- from products.early_access_features.backend.api import clear_feature_enrollment # noqa: PLC0415+ from products.feature_flags.backend.facade.api import clear_feature_enrollment # noqa: PLC0415- clear_feature_enrollment(feature_flag, team=feature_flag.team)+ clear_feature_enrollment(feature_flag.id, team=feature_flag.team)def _post_delete(context, feature):organization = context.organizationdiff --git a/products/early_access_features/backend/test/test_early_access_feature.py b/products/early_access_features/backend/test/test_early_access_feature.pyindex 4e8260e32709..1c109ac24e2d 100644--- a/products/early_access_features/backend/test/test_early_access_feature.py+++ b/products/early_access_features/backend/test/test_early_access_feature.py@@ -307,6 +307,9 @@ class TestEarlyAccessFeature(APIBaseTest):assert response_data["stage"] == EarlyAccessFeature.Stage.CONCEPTassert "super_groups" not in response_data["feature_flag"]["filters"]assert not response_data["feature_flag"]["filters"].get("feature_enrollment", None)+ # The response carries the version a rollout action checks, so it has to match the row.+ stored_flag = FeatureFlag.objects.get(pk=response_data["feature_flag"]["id"])+ assert response_data["feature_flag"]["version"] == stored_flag.versiondef test_archive(self):response = self.client.post(diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.pyindex c387d518ec67..3991e41a058d 100644--- a/products/feature_flags/backend/facade/api.py+++ b/products/feature_flags/backend/facade/api.py@@ -5,6 +5,8 @@ Every write routes through ``FeatureFlagSerializer`` — the only path that honocall these functions instead of driving the serializer and its DRF context by hand.``deactivate_trashed_flag`` and ``reactivate_restored_flag`` bypass the serializer, becausefile-system trash and restore flip ``active`` without the gate or validation.+``clear_feature_enrollment`` falls back to a raw model write when the serializer rejects+a flag's stored filters, because enrollment cleanup must never fail.The read helpers (``user_can_edit_flag``, ``user_can_create_flags``, ``flag_disable_requires_approval``,``serialize_flags``, ``get_feature_flag_request_usage``) expose the flag API'saccess-control, approval-policy, representation, and request-usage logic behind@@ -30,6 +32,7 @@ caller cannot surface a 409/change request), so ``ApprovalRequired`` is never rafrom datetime import datetimefrom typing import Any, Literal+import structlogfrom rest_framework.exceptions import ValidationErrorfrom posthog.api.utils import ServiceRequest@@ -41,6 +44,7 @@ from products.approvals.backend.policies import PolicyEnginefrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUEfrom products.feature_flags.backend.facade.config import detect_config_format+from products.feature_flags.backend.facade.filters import set_feature_enrollmentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.request_usage import (FeatureFlagRequestType as FeatureFlagRequestType,@@ -48,6 +52,8 @@ from products.feature_flags.backend.request_usage import (query_feature_flag_request_usage,)+logger = structlog.get_logger(__name__)+def _serializer_context(team: Team, user: Any, request: Any | None, *, method: str = "POST") -> dict:"""Build the DRF serializer context for a gated flag write.@@ -244,6 +250,44 @@ def unarchive_flag(flag: FeatureFlag, *, team: Team, user: Any, request: Any | Nreturn update_flag(flag, {"archived": False}, team=team, user=user, request=request)+def clear_feature_enrollment(flag_id: int, *, team: Team) -> None:+ """Clear the enrollment marker on an early access feature's linked flag (feature demoted or deleted).++ Cleanup must never fail: a linked flag can hold stored filter shapes the current+ FeatureFlagSerializer rejects or crashes on (group-aggregated conditions, malformed+ legacy properties, ...), and a rejection here would make the feature undeletable.+ Prefer the gated facade write (validation, activity logging); fall back to a raw+ model write when it raises. This is a system write (user=None): an enabled approval+ policy must never block cleanup with a 409, and activity is logged as system.++ The early return covers a hard-deleted id or another team's flag, so nothing is left to+ clear. A soft-deleted flag still gets cleared, through ``objects_including_soft_deleted``:+ the default manager hides it, and skipping it would leave the marker to come back with the+ flag on a restore.+ """+ flag = FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id, team=team).first()+ if flag is None:+ return++ cleared_filters = set_feature_enrollment(flag.get_filters() or {}, None)+ # Without "groups", the serializer's partial-PATCH shortcut discards the incoming+ # filters and returns the stored ones — silently skipping the cleanup entirely.+ if "groups" in cleared_filters:+ try:+ update_flag(flag, {"filters": cleared_filters}, team=team, user=None)+ return+ except Exception as exc:+ # Stored legacy JSON can raise arbitrary exception types through the flag+ # validator (ValidationError, TypeError, KeyError, ...), so catch broadly.+ logger.warning(+ "early_access_feature_enrollment_cleanup_fell_back_to_raw_write",+ feature_flag_id=flag.id,+ error=str(exc),+ )+ flag.filters = cleared_filters # nosemgrep: feature-flags-no-raw-filters-access -- deliberate never-fail cleanup fallback when the gated write can't validate stored legacy filter shapes+ flag.save(update_fields=["filters"])++def _roll_out_variant(current_filters: dict,variant_key: str,diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex 8b30580d42ae..add3012c007b 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -619,12 +619,16 @@ class TestEarlyAccessFeatureSystemWrites(APIBaseTest):# writes, so they must succeed untouched by any enabled flag approval policy.@parameterized.expand([- ("destroy", "delete", status.HTTP_204_NO_CONTENT),- ("demote_to_concept", "patch", status.HTTP_200_OK),+ ("destroy", "delete", status.HTTP_204_NO_CONTENT, False),+ ("demote_to_concept", "patch", status.HTTP_200_OK, False),+ ("destroy_with_invalid_stored_filters", "delete", status.HTTP_204_NO_CONTENT, True),+ ("demote_with_invalid_stored_filters", "patch", status.HTTP_200_OK, True),])@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)- def test_destroy_and_demote_never_require_approval(self, _name, method, expected_status, _mock_enabled):+ def test_destroy_and_demote_never_require_approval(+ self, _name, method, expected_status, invalid_stored_filters, _mock_enabled+ ):response = self.client.post(f"/api/projects/{self.team.id}/early_access_feature/",data={"name": "Gated feature", "stage": "beta"},@@ -633,6 +637,16 @@ class TestEarlyAccessFeatureSystemWrites(APIBaseTest):assert response.status_code == status.HTTP_201_CREATED, response.json()feature_id = response.json()["id"]flag = FeatureFlag.objects.get(team=self.team, key="gated-feature")+ if invalid_stored_filters:+ # The person property carries no "key" on purpose: that is what fails validation and+ # drives cleanup onto the raw fallback. Adding one turns these into gated-write cases.+ FeatureFlag.objects.filter(pk=flag.pk).update(+ filters={+ "groups": [{"properties": [{"value": "ok", "type": "person"}], "rollout_percentage": 100}],+ "feature_enrollment": True,+ }+ )+ flag.refresh_from_db()assert flag.has_feature_enrollmentself.organization.available_product_features = [@@ -661,6 +675,24 @@ class TestEarlyAccessFeatureSystemWrites(APIBaseTest):assert not flag.has_feature_enrollmentassert not ChangeRequest.objects.filter(team=self.team).exists()+ def test_enrollment_clears_on_a_soft_deleted_flag(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/early_access_feature/",+ data={"name": "Trashed feature", "stage": "beta"},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ feature_id = response.json()["id"]+ flag = FeatureFlag.objects.get(team=self.team, key="trashed-feature")+ assert flag.has_feature_enrollment+ FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True)++ response = self.client.delete(f"/api/projects/{self.team.id}/early_access_feature/{feature_id}/")++ assert response.status_code == status.HTTP_204_NO_CONTENT+ flag = FeatureFlag.objects_including_soft_deleted.get(pk=flag.pk)+ assert not flag.has_feature_enrollment+class TestSetFeatureEnrollment:@parameterized.expand(