: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(flags): reject release conditions on deleted cohorts (#113495)
Phil Haacke026a544d30c
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 0c04c6f9c642..2d282c92ba86 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -8,7 +8,7 @@ from collections.abc import Iterable, Iterator, Sequencefrom copy import deepcopyfrom typing import Annotated, Any, ClassVar, Literal, Optional, Union, cast-from django.db.models import OuterRef, QuerySet, Subquery+from django.db.models import OuterRef, Q, QuerySet, Subqueryfrom django.utils import timezoneimport requests@@ -85,6 +85,7 @@ from posthog.permissions import get_authenticator_scopesfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.renderers import SafeJSONRenderer+from posthog.scopes import scopes_not_coveredfrom posthog.taxonomy.hidden_events import HIDDEN_EVENT_REASON, added_hidden_eventfrom posthog.utils import format_query_params_absolute_url, safe_int, str_to_bool@@ -129,6 +130,7 @@ from products.feature_flags.backend.models.team_feature_flags_config import ()from products.feature_flags.backend.realtime_targeting import is_realtime_cohort_flag_targeting_enabledfrom products.product_analytics.backend.facade.models import Insight+from products.surveys.backend.models import Surveyfrom products.workflows.backend.facade.api import (filter_hog_flow_references_by_access_level,get_active_workflows_using_realtime_cohort,@@ -158,6 +160,11 @@ def _workflows_relying_on_cohort(cohort: Cohort) -> list[CohortDependentWorkflowreturn get_active_workflows_using_realtime_cohort(team_id=cohort.team_id, cohort_ids=cohort_ids)+def _token_can_read(request: Request, scope_object: str) -> bool:+ scopes = get_authenticator_scopes(request.successful_authenticator)+ return scopes is None or "*" in scopes or not scopes_not_covered(scopes, [f"{scope_object}:read"])++def _visible_workflows(request: Request,user_access_control: Optional[UserAccessControl],@@ -165,10 +172,7 @@ def _visible_workflows(workflows: list[CohortDependentWorkflow],) -> list[CohortDependentWorkflow]:# The caller sees the workflows it can view. Callers count every workflow.- scopes = get_authenticator_scopes(request.successful_authenticator)- if user_access_control is None or (- scopes is not None and not {"*", "hog_flow:read", "hog_flow:write"} & set(scopes)- ):+ if user_access_control is None or not _token_can_read(request, "hog_flow"):return []references = [HogFlowReference(id=workflow.id, name=workflow.name, status=workflow.status) for workflow in workflows@@ -182,6 +186,30 @@ def _visible_workflows(return [workflow for workflow in workflows if workflow.id in visible_ids]+def _visible_flags(+ request: Request,+ user_access_control: Optional[UserAccessControl],+ project_id: int,+ flags: list[FeatureFlag],+) -> list[FeatureFlag]:+ if user_access_control is None or not _token_can_read(request, "feature_flag"):+ return []+ visible_ids = set(+ user_access_control.filter_queryset_by_access_level(+ FeatureFlag.objects.filter(team__project_id=project_id, id__in=[flag.id for flag in flags]),+ include_all_if_admin=True,+ ).values_list("id", flat=True)+ )+ return [flag for flag in flags if flag.id in visible_ids]+++def _names_suffix(visible_names: list[str], total: int) -> str:+ if not visible_names:+ return ""+ hidden = total - len(visible_names)+ return f": {', '.join(visible_names)}" + (f" and {hidden} more" if hidden else "")++def _workflow_names_suffix(request: Request,user_access_control: Optional[UserAccessControl],@@ -189,10 +217,7 @@ def _workflow_names_suffix(workflows: list[CohortDependentWorkflow],) -> str:visible = _visible_workflows(request, user_access_control, team_id, workflows)- if not visible:- return ""- hidden = len(workflows) - len(visible)- return f": {', '.join(workflow.name for workflow in visible)}" + (f" and {hidden} more" if hidden else "")+ return _names_suffix([workflow.name for workflow in visible], len(workflows))COHORT_USED_BY_WORKFLOWS_ERROR_CODE = "cohort_used_by_workflows"@@ -1776,13 +1801,29 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializis_deletion_change = deleted_state is not None and cohort.deleted != deleted_stateif is_deletion_change:if deleted_state:- flags_with_cohort = get_active_flags_using_cohort(cohort)+ flags_with_cohort = get_flags_blocking_cohort_deletion(cohort)if flags_with_cohort:- flag_names = [flag.name or flag.key for flag in flags_with_cohort]- raise ValidationError(- f"This cohort is used in {len(flags_with_cohort)} active feature flag(s): {', '.join(flag_names)}. "- "Please remove the cohort from these feature flags before deleting it."+ visible_flags = _visible_flags(+ request, self._user_access_control(), cohort.team.project_id, flags_with_cohort+ )+ names = _names_suffix([flag.name or flag.key for flag in visible_flags], len(flags_with_cohort))+ message = (+ f"This cohort is used in {len(flags_with_cohort)} feature flag(s){names}. "+ "Remove the cohort from these flags, or archive the flags, before deleting it.")+ # Resuming a survey enables its targeting flag. That save fails once the flag is archived.+ visible_flag_ids = [flag.id for flag in visible_flags]+ if (+ visible_flag_ids+ and Survey.objects.filter(+ Q(targeting_flag_id__in=visible_flag_ids)+ | Q(internal_targeting_flag_id__in=visible_flag_ids)+ | Q(internal_response_sampling_flag_id__in=visible_flag_ids),+ team__project_id=cohort.team.project_id,+ ).exists()+ ):+ message += " For a survey's targeting flag, change the survey's targeting or delete the survey instead."+ raise ValidationError(message)workflows_with_cohort = _workflows_relying_on_cohort(cohort)if workflows_with_cohort:@@ -1973,7 +2014,7 @@ def _directly_referenced_cohort_ids(flags: list[FeatureFlag]) -> set[int]:"""Cohort ids each flag references directly, the ones ``FeatureFlag.get_cohort_ids`` starts from.Used to bulk-load those cohorts so the expansion doesn't point-query them one at a time.- An id that is not an integer is left to the expansion, which rejects it in v1 and skips it in v2.+ An id that is not an integer is left to the expansion, which skips it."""return {cohort_id for flag in flags for cohort_id in references(decode_config(flag.filters)).cohort_ids}@@ -2006,17 +2047,24 @@ def _filter_flags_referencing_cohort(in flag.get_cohort_ids(seen_cohorts_cache=seen_cohorts_cache,stop_traversal_at_static=stop_traversal_at_static,+ # A non-integer id cannot reach this cohort. Raising on it would fail the whole lookup.+ invalid_cohort_ids="skip",)]-def get_active_flags_using_cohort(cohort: Cohort) -> list[FeatureFlag]:- """Return active, non-deleted feature flags that reference this cohort.+def get_flags_blocking_cohort_deletion(cohort: Cohort) -> list[FeatureFlag]:+ """Return non-deleted, non-archived feature flags that reference this cohort.- Used by deletion protection: only live flags should block cohort deletion.+ The flag evaluator skips deleted cohorts. A flag that still references one fails every+ evaluation. A disabled flag blocks deletion because some writers enable a flag without the+ flag API's validation. For example, starting a survey enables its targeting flag directly.+ A deleted or archived flag does not block deletion. A database constraint keeps an archived+ flag disabled. The flag API rejects a restore or unarchive of a flag that targets a deleted+ cohort."""return _filter_flags_referencing_cohort(- _flags_with_cohort_filters(cohort).filter(active=True),+ _flags_with_cohort_filters(cohort).filter(archived=False),cohort,stop_traversal_at_static=True,)diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.pyindex 57216ac080b2..371a86b7624a 100644--- a/posthog/api/file_system/registrations.py+++ b/posthog/api/file_system/registrations.py@@ -312,6 +312,15 @@ def _feature_flag_post_delete(context: DeletionContext, feature_flag: Any) -> No)+def _feature_flag_pre_restore(context: RestoreContext, feature_flag: Any) -> None:+ from products.feature_flags.backend.facade.api import (+ validate_flag_restorable, # noqa: PLC0415 — keeps the heavy dep off the import path+ )++ # The endpoint shows a ValidationError's message. It replaces a ValueError with its generic refusal.+ validate_flag_restorable(feature_flag.id, team_id=feature_flag.team_id)++def _feature_flag_post_restore(context: RestoreContext, feature_flag: Any) -> None:_log_restore_activity(context,@@ -349,6 +358,7 @@ def register_core_file_system_types() -> None:undo_message="Send PATCH /api/projects/@current/feature_flags/{id} with deleted=false.",)register_post_delete_hook("feature_flag", _feature_flag_post_delete)+ register_pre_restore_hook("feature_flag", _feature_flag_pre_restore)register_post_restore_hook("feature_flag", _feature_flag_post_restore)register_file_system_type(diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex f5f7a3abe3d0..410858260cba 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -59,6 +59,7 @@ from products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfigfrom products.product_analytics.backend.facade.models import Insight+from products.surveys.backend.models import Surveyfrom products.workflows.backend.facade.testing import create_workflow_for_testfrom ee.clickhouse.materialized_columns.analyze import materialize@@ -5708,35 +5709,119 @@ [email protected],response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}", data={"deleted": True})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("used in 1 active feature flag(s): Rules flag using cohort", response.json()["detail"])+ self.assertIn("Rules flag using cohort", response.json()["detail"])+ self.assertNotIn("Unreadable flag", response.json()["detail"])+ @parameterized.expand(+ [+ ("active", {"active": True}, False, False, True),+ ("disabled", {"active": False}, False, False, True),+ ("disabled_with_non_numeric_cohort_id", {"active": False}, False, True, True),+ ("stopped_survey_targeting", {"active": False}, True, False, True),+ ("archived", {"active": False, "archived": True}, False, False, False),+ ("soft_deleted", {"active": True, "deleted": True}, False, False, False),+ ]+ )@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")- def test_cannot_delete_cohort_used_in_active_feature_flag(self, patch_calculate_cohort, patch_capture):+ def test_deleting_cohort_used_in_feature_flag(+ self,+ _name: str,+ flag_state: dict[str, bool],+ survey_targeting: bool,+ non_numeric_cohort_id: bool,+ blocks: bool,+ patch_calculate_cohort: MagicMock,+ patch_capture: MagicMock,+ ) -> None:response = self.client.post(f"/api/projects/{self.team.id}/cohorts",data={"name": "Test Cohort", "groups": [{"properties": {"team_id": 5}}]},)cohort_id = response.json()["id"]- FeatureFlag.objects.create(+ groups = [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]+ if non_numeric_cohort_id:+ groups.insert(0, {"properties": [{"key": "id", "value": "not-an-id", "type": "cohort"}]})+ flag = FeatureFlag.objects.create(team=self.team,- filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},+ filters={"groups": groups},name="Flag using cohort",key="cohort-flag",created_by=self.user,- active=True,+ **flag_state,)+ if survey_targeting:+ Survey.objects.create(+ team=self.team,+ name="Stopped survey",+ type=Survey.SurveyType.POPOVER,+ questions=[{"id": "q1", "type": "open", "question": "Hi"}],+ targeting_flag=flag,+ )response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}",data={"deleted": True},)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn(- "This cohort is used in 1 active feature flag(s): Flag using cohort",+ if blocks:+ expected_detail = (+ "This cohort is used in 1 feature flag(s): Flag using cohort. "+ "Remove the cohort from these flags, or archive the flags, before deleting it."+ )+ if survey_targeting:+ expected_detail += (+ " For a survey's targeting flag, change the survey's targeting or delete the survey instead."+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertEqual(response.json()["detail"], expected_detail)+ else:+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(Cohort.objects.get(id=cohort_id).deleted, not blocks)++ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_blocked_delete_hides_names_of_flags_the_member_cannot_view(+ self, patch_calculate_cohort: MagicMock, patch_capture: MagicMock+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts",+ data={"name": "Test Cohort", "groups": [{"properties": {"team_id": 5}}]},+ )+ cohort_id = response.json()["id"]+ filters = {"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]}+ # A flag's creator keeps access, so another member creates the hidden flag.+ hidden_flag = FeatureFlag.objects.create(+ team=self.team,+ filters=filters,+ name="Hidden flag",+ key="hidden-flag",+ active=False,+ created_by=self._create_user("[email protected]"),+ )+ FeatureFlag.objects.create(+ team=self.team, filters=filters, name="Visible flag", key="visible-flag", created_by=self.user+ )+ AccessControl.objects.create(+ team=self.team,+ resource="feature_flag",+ resource_id=str(hidden_flag.id),+ access_level="none",+ organization_member=self.organization_membership,+ )++ response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}", data={"deleted": True})++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertEqual(response.json()["detail"],+ "This cohort is used in 2 feature flag(s): Visible flag and 1 more. "+ "Remove the cohort from these flags, or archive the flags, before deleting it.",)@patch("posthog.api.cohort.report_user_action")@@ -5773,7 +5858,6 @@ [email protected],self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)detail = response.json()["detail"]- self.assertIn("This cohort is used in 2 active feature flag(s):", detail)self.assertIn("First Flag", detail)self.assertIn("Second Flag", detail)@@ -5795,61 +5879,6 @@ [email protected],cohort = Cohort.objects.get(id=cohort_id)self.assertTrue(cohort.deleted)- @patch("posthog.api.cohort.report_user_action")- @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")- def test_can_delete_cohort_used_in_inactive_feature_flag(self, patch_calculate_cohort, patch_capture):- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts",- data={"name": "Test Cohort", "groups": [{"properties": {"team_id": 5}}]},- )- cohort_id = response.json()["id"]-- FeatureFlag.objects.create(- team=self.team,- filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},- name="Inactive Flag",- key="inactive-flag",- created_by=self.user,- active=False,- )-- response = self.client.patch(- f"/api/projects/{self.team.id}/cohorts/{cohort_id}",- data={"deleted": True},- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- cohort = Cohort.objects.get(id=cohort_id)- self.assertTrue(cohort.deleted)-- @patch("posthog.api.cohort.report_user_action")- @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")- def test_can_delete_cohort_used_in_deleted_feature_flag(self, patch_calculate_cohort, patch_capture):- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts",- data={"name": "Test Cohort", "groups": [{"properties": {"team_id": 5}}]},- )- cohort_id = response.json()["id"]-- FeatureFlag.objects.create(- team=self.team,- filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},- name="Deleted Flag",- key="deleted-flag",- created_by=self.user,- active=True,- deleted=True,- )-- response = self.client.patch(- f"/api/projects/{self.team.id}/cohorts/{cohort_id}",- data={"deleted": True},- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- cohort = Cohort.objects.get(id=cohort_id)- self.assertTrue(cohort.deleted)-@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_cannot_delete_cohort_used_in_test_account_filters(self, patch_calculate_cohort, patch_capture):@@ -6677,7 +6706,7 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):)cohort_id = response.json()["id"]- # Inactive, so it doesn't block deletion but still appears in used_in.+ # An archived flag does not block deletion. The used_in endpoint still lists it.FeatureFlag.objects.create(team=self.team,filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},@@ -6685,6 +6714,7 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):key="lingering-flag",created_by=self.user,active=False,+ archived=True,)response = self.client.patch(@@ -7060,30 +7090,6 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["feature_flags"], {"results": [], "total": 0, "has_more": False})- @patch("posthog.api.cohort.report_user_action")- @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")- def test_deletion_protection_still_excludes_inactive_flags(self, patch_calculate_cohort, patch_capture):- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts",- data={"name": "Deletable Cohort", "groups": [{"properties": {"team_id": 5}}]},- )- cohort_id = response.json()["id"]-- FeatureFlag.objects.create(- team=self.team,- filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},- name="Inactive Flag",- key="inactive-flag",- created_by=self.user,- active=False,- )-- response = self.client.patch(- f"/api/projects/{self.team.id}/cohorts/{cohort_id}",- data={"deleted": True},- )- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())-@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_deletion_protection_blocks_on_transitively_referencing_flag(self, patch_calculate_cohort, patch_capture):@@ -7095,10 +7101,7 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):data={"deleted": True},)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn(- "This cohort is used in 1 active feature flag(s): Transitive Flag",- response.json()["detail"],- )+ self.assertIn("Transitive Flag", response.json()["detail"])@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")@@ -7111,7 +7114,7 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertNotIn("active feature flag", response.json()["detail"])+ self.assertNotIn("Static snapshot flag", response.json()["detail"])self.assertIn("This cohort is used as criteria in 1 other cohort(s): Static snapshot cohort",response.json()["detail"],diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.pyindex 8564d4715224..32c6af8cab15 100644--- a/posthog/api/test/test_file_system.py+++ b/posthog/api/test/test_file_system.py@@ -772,6 +772,33 @@ class TestFileSystemDeletion(APIBaseTest):assert restored.deleted is Falseassert not ChangeRequest.objects.filter(team=self.team).exists()+ def test_undo_delete_refuses_feature_flag_targeting_deleted_cohort(self) -> None:+ cohort = Cohort.objects.create(team=self.team, name="Retired cohort", deleted=True)+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="undo-cohort-flag",+ created_by=self.user,+ filters={+ "groups": [+ {"properties": [{"key": "id", "type": "cohort", "value": cohort.id}], "rollout_percentage": 100}+ ]+ },+ )+ file_entry = FileSystem.objects.get(team=self.team, type="feature_flag", ref=str(flag.id))+ delete_response = self.client.delete(f"/api/environments/{self.team.id}/file_system/{file_entry.id}/")+ assert delete_response.status_code == status.HTTP_200_OK++ undo_response = self.client.post(+ f"/api/environments/{self.team.id}/file_system/undo_delete/",+ {"items": [{"type": "feature_flag", "ref": str(flag.id)}]},+ )++ assert undo_response.status_code == status.HTTP_400_BAD_REQUEST+ assert undo_response.json()["detail"] == (+ f"Cohort 'Retired cohort' (ID {cohort.id}) has been deleted. Restore the cohort, choose another cohort, or remove this condition."+ )+ assert FeatureFlag.objects_including_soft_deleted.get(pk=flag.pk).deleted is True+def test_undo_delete_restores_original_path(self) -> None:flag = FeatureFlag(team=self.team, key="undo-path-flag", created_by=self.user)flag._create_in_folder = "Restored/Flags"diff --git a/posthog/tasks/process_scheduled_changes.py b/posthog/tasks/process_scheduled_changes.pyindex e73b0b2245da..7803d90cc365 100644--- a/posthog/tasks/process_scheduled_changes.py+++ b/posthog/tasks/process_scheduled_changes.py@@ -1,6 +1,7 @@import osimport jsonimport socket+from collections.abc import Iteratorfrom datetime import UTC, datetime, tzinfofrom zoneinfo import ZoneInfo, ZoneInfoNotFoundError@@ -13,6 +14,7 @@ from celery import current_taskfrom croniter import croniter # type: ignore[import-untyped,unused-ignore]from dateutil.relativedelta import relativedeltafrom prometheus_client import Counter+from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom posthog.exceptions_capture import capture_exception@@ -40,6 +42,17 @@ SCHEDULED_CHANGE_MISSED_EXECUTIONS = Counter()+def _drf_error_codes(codes: object) -> Iterator[str]:+ if isinstance(codes, str):+ yield codes+ elif isinstance(codes, dict):+ for value in codes.values():+ yield from _drf_error_codes(value)+ elif isinstance(codes, list):+ for value in codes:+ yield from _drf_error_codes(value)++def is_unrecoverable_error(exception: Exception) -> bool:"""Determine if an exception represents an unrecoverable error that should not be retried.@@ -79,6 +92,10 @@ def is_unrecoverable_error(exception: Exception) -> bool:if any(indicator in error_message for indicator in permanent_error_indicators):return True+ # The flag API rejects a release condition on a missing or deleted cohort with this code.+ if isinstance(exception, DRFValidationError) and "cohort_does_not_exist" in _drf_error_codes(exception.get_codes()):+ return True+return isinstance(exception, unrecoverable_types)diff --git a/posthog/tasks/test/test_process_scheduled_changes.py b/posthog/tasks/test/test_process_scheduled_changes.pyindex 402859084761..7bb877c6bbb5 100644--- a/posthog/tasks/test/test_process_scheduled_changes.py+++ b/posthog/tasks/test/test_process_scheduled_changes.py@@ -23,6 +23,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.team import Teamfrom posthog.tasks.process_scheduled_changes import process_scheduled_changes, resolve_schedule_timezone+from products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -175,6 +176,51 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):assert applying.failure_reason is Noneassert applying.executed_at is not None+ @parameterized.expand(+ [+ ("deleted_cohort", "unrecoverable", "has been deleted"),+ ("disabled_dependency", "recoverable", "depends on disabled flags"),+ ]+ )+ def test_scheduled_enable_rejected_by_the_flag_api(+ self, rejection: str, classification: str, expected_error: str+ ) -> None:+ if rejection == "deleted_cohort":+ cohort = Cohort.objects.create(team=self.team, name="Retired cohort", deleted=True)+ prop = {"key": "id", "type": "cohort", "value": cohort.id}+ else:+ dependency = FeatureFlag.objects.create(+ key="dependency", active=False, filters={"groups": []}, team=self.team, created_by=self.user+ )+ prop = {"key": str(dependency.id), "type": "flag", "value": "true", "operator": "flag_evaluates_to"}+ feature_flag = FeatureFlag.objects.create(+ name="Flag 1",+ key="flag-1",+ active=False,+ filters={"groups": [{"properties": [prop]}]},+ team=self.team,+ created_by=self.user,+ )+ scheduled_change = ScheduledChange.objects.create(+ team=self.team,+ record_id=feature_flag.id,+ model_name="FeatureFlag",+ payload={"operation": "update_status", "value": True},+ scheduled_at=(datetime.now(UTC) - timedelta(seconds=30)),+ created_by=self.user,+ )++ process_scheduled_changes()++ feature_flag.refresh_from_db()+ scheduled_change.refresh_from_db()+ assert feature_flag.active is False+ assert (scheduled_change.executed_at is not None) is (classification == "unrecoverable")+ assert scheduled_change.failure_reason is not None+ failure_data = json.loads(scheduled_change.failure_reason)+ assert failure_data["error_classification"] == classification+ assert expected_error in failure_data["error"]+def test_schedule_feature_flag_invalid_payload(self) -> None:feature_flag = FeatureFlag.objects.create(name="Flag 1",diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 02b6fa55673e..ae196499e7cd 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -28,7 +28,11 @@ from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings, LimitContextfrom posthog.hogql.query import execute_hogql_query-from posthog.api.cohort import ALLOW_HIDDEN_EVENT_CRITERIA_CONTEXT_KEY, CohortSerializer, get_active_flags_using_cohort+from posthog.api.cohort import (+ ALLOW_HIDDEN_EVENT_CRITERIA_CONTEXT_KEY,+ CohortSerializer,+ get_flags_blocking_cohort_deletion,+)from posthog.api.utils import ServiceRequestfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.event_usage import EventSource, report_user_action@@ -110,6 +114,7 @@ from products.feature_flags.backend.facade.api import (update_flag,user_can_create_flags,user_can_edit_flag,+ validate_flag_restorable,)from products.feature_flags.backend.facade.filters import (restrict_groups_to_cohort,@@ -1984,7 +1989,8 @@ class ExperimentService:manually stays archived. The flag stays disabled either way; re-enabling it isan explicit user decision. Un-archiving the flag is a feature_flag write, so it'sskipped (leaving the flag archived and the bookkeeping intact, recoverable later)- when the caller lacks feature_flag:write scope or editor access to the flag.+ when the caller lacks feature_flag:write scope or editor access to the flag. The flag+ also stays archived when one of its release conditions targets a deleted cohort."""if not experiment.feature_flag_auto_archived:return@@ -2003,6 +2009,18 @@ class ExperimentService:if not can_write_feature_flag or not user_can_edit_flag(feature_flag, team=self.team, user=self.user):return+ try:+ validate_flag_restorable(feature_flag.id, team_id=feature_flag.team_id)+ except ValidationError:+ logger.warning(+ "experiment_flag_unarchive_skipped",+ experiment_id=experiment.pk,+ flag_id=feature_flag.pk,+ team_id=self.team.pk,+ reason="flag_targets_missing_or_deleted_cohort",+ )+ return+# Gated write inside unarchive_experiment's transaction: safe because an# archived-only payload matches no approval action (enable/disable detect on# `active`, update on `filters`), so the gate can't raise ApprovalRequired here@@ -2450,8 +2468,8 @@ class ExperimentService:The ids come from the EXPOSURE_FROZEN_COHORT_KEY stamps in the flag's filters, whichround-trip through the flag API and are therefore user-editable — treat them as claims,not facts. Only delete a cohort verifiable as an orphaned freeze snapshot: named like one,- and no longer referenced by any active flag (the same protection the cohort API enforces- on delete). Anything failing verification is skipped rather than fatal — a leftover+ and no longer referenced by any flag that blocks its deletion through the cohort API.+ Anything failing verification is skipped rather than fatal — a leftovercohort is cheaper than a blocked lifecycle action or a hijacked deletion."""for cohort in Cohort.objects.filter(team=self.team, pk__in=cohort_ids, is_static=True, deleted=False):@@ -2463,12 +2481,12 @@ class ExperimentService:reason="not_a_freeze_snapshot_name",)continue- if get_active_flags_using_cohort(cohort):+ if get_flags_blocking_cohort_deletion(cohort):logger.warning("experiment_freeze_snapshot_cleanup_skipped",cohort_id=cohort.pk,team_id=self.team.pk,- reason="still_referenced_by_active_flags",+ reason="still_referenced_by_flags",)continuecohort.deleted = Truediff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 774196f2d0ff..4b7cca61e96a 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -3180,18 +3180,30 @@ class TestExperimentService(APIBaseTest):assert flag.archived is Falseassert experiment.feature_flag_auto_archived is False- def test_unarchive_experiment_skips_flag_without_feature_flag_write_scope(self):- # Unarchiving the flag is a feature_flag write — skipped (flag stays archived, bookkeeping- # intact) for an experiment-only token, recoverable on a later unarchive with the scope.- experiment = self._create_ended_experiment(name="Unarchive No Scope", feature_flag_key="unarchive-no-scope")+ @parameterized.expand(+ [+ ("no_feature_flag_write_scope", False, False),+ ("flag_targets_deleted_cohort", True, True),+ ]+ )+ def test_unarchive_experiment_leaves_flag_archived_when_flag_cannot_be_unarchived(+ self, _name: str, can_write_feature_flag: bool, targets_deleted_cohort: bool+ ):+ # The bookkeeping stays so that a later unarchive can bring the flag back.+ experiment = self._create_ended_experiment(name="Unarchive Blocked", feature_flag_key="unarchive-blocked")experiment.feature_flag.active = Falseexperiment.feature_flag.save()service = self._service()service.archive_experiment(experiment)experiment.refresh_from_db()assert experiment.feature_flag_auto_archived is True+ if targets_deleted_cohort:+ cohort = Cohort.objects.create(team=self.team, name="Retired cohort", deleted=True)+ FeatureFlag.objects.filter(pk=experiment.feature_flag_id).update(+ filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.id}]}]}+ )- service.unarchive_experiment(experiment, can_write_feature_flag=False)+ service.unarchive_experiment(experiment, can_write_feature_flag=can_write_feature_flag)experiment.refresh_from_db()assert experiment.archived is Falsediff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex d945ed84ad67..eb723c64a5c7 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -1182,6 +1182,42 @@ def _iter_flag_filter_properties(groups: Any) -> Iterator[_FlagFilterProperty]:)+def _validate_cohort_reference(cohort_id: Any, project_id: int) -> Cohort:+ """Return the cohort a release condition targets, or raise if the flag cannot evaluate it.++ The flag evaluator loads only non-deleted cohorts. A request that reaches a condition on a+ deleted cohort therefore fails the whole flag. The lookup includes deleted cohorts so that the+ error can name the cohort.+ """+ try:+ # A JSON true is the Python integer 1, so the lookup would match the cohort with id 1.+ if isinstance(cohort_id, bool):+ raise TypeError(cohort_id)+ cohort = Cohort.objects.get(pk=cast(str | int, cohort_id), team__project_id=project_id)+ except (Cohort.DoesNotExist, ValueError, TypeError):+ raise serializers.ValidationError(+ detail=f"Cohort with id {cohort_id} does not exist",+ code="cohort_does_not_exist",+ )+ if cohort.deleted:+ label = f"Cohort '{cohort.name}' (ID {cohort.pk})" if cohort.name else f"Cohort with id {cohort.pk}"+ raise serializers.ValidationError(+ detail=f"{label} has been deleted. Restore the cohort, choose another cohort, or remove this condition.",+ code="cohort_does_not_exist",+ )+ return cohort+++def validate_stored_cohort_references(flag: FeatureFlag) -> None:+ """Raise if a stored release condition targets a cohort the flag cannot evaluate."""+ # Only config version 1 can reference a cohort.+ if detect_config_format(flag.filters).kind != "v1":+ return+ for located in _iter_flag_filter_properties(flag.conditions):+ if located.prop.get("type") == "cohort":+ _validate_cohort_reference(located.prop.get("value"), flag.team.project_id)++class FeatureFlagCreateRequestSchemaSerializer(serializers.Serializer):key = serializers.CharField(required=False, help_text="Feature flag key.")name = serializers.CharField(@@ -1476,10 +1512,13 @@ class FeatureFlagSerializer(# Fallback to database query if annotation is not availablereturn teams_gating_replay_on_flag(feature_flag, key=feature_flag.key).exists()- def _validate_reactivated_dependency_formats(self, attrs: Mapping[str, JsonValue]) -> None:- """Empty filters retain stored targeting and bypass dependency checks in _validate_filters_inner.+ def _validate_reactivated_references(self, attrs: Mapping[str, JsonValue]) -> None:+ """Check stored references when a write turns the flag on or brings it back.- Treat them as omitted so enabling or restoring an active flag still checks its dependencies.+ Turning the flag on, including restoring a flag that comes back active, checks its flag+ dependencies and cohorts. Restoring a disabled flag or unarchiving a flag checks its cohorts.+ Empty filters retain stored targeting and bypass the reference checks in _validate_filters_inner,+ so treat them as omitted."""# A v2 document cannot be walked as v1; enabling one validates the stored document# strictly under the lock instead, and that validator admits no flag or cohort reference.@@ -1487,14 +1526,18 @@ class FeatureFlagSerializer(returnenabling = attrs.get("active") is True and not self.instance.active- restoring_active = (- attrs.get("deleted") is False and self.instance.deleted and attrs.get("active", self.instance.active)+ # The cohort delete guard skips deleted and archived flags. Once a flag is neither, a writer+ # that skips this serializer can enable it. Survey resume is one such writer.+ returning = (self.instance.deleted or self.instance.archived) and not (+ attrs.get("deleted", self.instance.deleted) or attrs.get("archived", self.instance.archived))- if not (enabling or restoring_active):+ if not (enabling or returning):returntry:- self._validate_dependency_formats(self.instance.filters or {}, traverse=True)+ if attrs.get("active", self.instance.active):+ self._validate_dependency_formats(self.instance.filters or {}, traverse=True)+ validate_stored_cohort_references(self.instance)except serializers.ValidationError as exc:raise serializers.ValidationError({"filters": exc.detail}) from exc@@ -1524,7 +1567,7 @@ class FeatureFlagSerializer(self._validate_device_bucketing_with_persist_auth(attrs)self._validate_encrypted_payloads_require_remote_config(attrs)self._validate_archived_flags_are_disabled(attrs)- self._validate_reactivated_dependency_formats(attrs)+ self._validate_reactivated_references(attrs)self._validate_flag_limits()# Materialize the remote-config 100% rollout default here, before the approval gate runs in@@ -2293,49 +2336,40 @@ class FeatureFlagSerializer(raise serializers.ValidationError(f"{located.path}.value: invalid regex pattern")if located.prop.get("type") == "cohort":- cohort_id = located.prop.get("value")- try:- initial_cohort: Cohort = Cohort.objects.get(- pk=cast(str | int, cohort_id), team__project_id=self.context["project_id"]- )- # Static cohorts (including one-time snapshots) hold a- # materialised person list. The populating criteria may- # still be stored on the record, but they are inert – the- # cohort no longer re-evaluates them, and the Rust engine's- # extract_dependencies returns an empty set for them. Skip- # both the behavioural property check and the dependency walk- # so snapshot cohorts can be used in flags without an extra- # export step, even when their inert criteria reference- # another cohort. See #65270.- dependency_cohorts = (- []- if initial_cohort.is_static- else get_all_cohort_dependencies(initial_cohort, stop_traversal_at_static=True)- )- for cohort in [initial_cohort, *dependency_cohorts]:- # Static cohorts have materialized membership, any preserved behavioral- # filters are display-only and never evaluated, so skip them.- if cohort.is_static:- continue- behavioral_props = [- cohort_prop for cohort_prop in cohort.properties.flat if cohort_prop.type == "behavioral"- ]- # Gate on both signals: cohort.properties.flat parses each leaf into a- # Property() object, so a leaf shape the parser doesn't recognize would- # silently vanish from it and defeat this guard; _has_filter_type walks- # the raw filters JSON instead, so it can't miss an unparsable leaf. But- # _has_filter_type only reads `filters` — legacy cohorts that store their- # condition in the deprecated `groups` field instead (see Cohort.properties)- # would defeat *that* check, so behavioral_props still needs to cover them.- if cohort._has_filter_type("behavioral") or behavioral_props:- _validate_behavioral_cohort_for_feature_flag(- cohort, behavioral_props, allow_realtime_backfilled=self._allow_realtime_backfilled- )- except Cohort.DoesNotExist:- raise serializers.ValidationError(- detail=f"Cohort with id {cohort_id} does not exist",- code="cohort_does_not_exist",- )+ initial_cohort = _validate_cohort_reference(located.prop.get("value"), self.context["project_id"])+ # Static cohorts (including one-time snapshots) hold a+ # materialised person list. The populating criteria may+ # still be stored on the record, but they are inert – the+ # cohort no longer re-evaluates them, and the Rust engine's+ # extract_dependencies returns an empty set for them. Skip+ # both the behavioural property check and the dependency walk+ # so snapshot cohorts can be used in flags without an extra+ # export step, even when their inert criteria reference+ # another cohort. See #65270.+ dependency_cohorts = (+ []+ if initial_cohort.is_static+ else get_all_cohort_dependencies(initial_cohort, stop_traversal_at_static=True)+ )+ for cohort in [initial_cohort, *dependency_cohorts]:+ # Static cohorts have materialized membership, any preserved behavioral+ # filters are display-only and never evaluated, so skip them.+ if cohort.is_static:+ continue+ behavioral_props = [+ cohort_prop for cohort_prop in cohort.properties.flat if cohort_prop.type == "behavioral"+ ]+ # Gate on both signals: cohort.properties.flat parses each leaf into a+ # Property() object, so a leaf shape the parser doesn't recognize would+ # silently vanish from it and defeat this guard; _has_filter_type walks+ # the raw filters JSON instead, so it can't miss an unparsable leaf. But+ # _has_filter_type only reads `filters` — legacy cohorts that store their+ # condition in the deprecated `groups` field instead (see Cohort.properties)+ # would defeat *that* check, so behavioral_props still needs to cover them.+ if cohort._has_filter_type("behavioral") or behavioral_props:+ _validate_behavioral_cohort_for_feature_flag(+ cohort, behavioral_props, allow_realtime_backfilled=self._allow_realtime_backfilled+ )self._reject_oversized_filters(merged)@@ -4328,8 +4362,8 @@ class FeatureFlagViewSet(required_scopes=["feature_flag:write"],request=None,responses=flag_lifecycle_responses(- "The flag is archived, one of the flags it depends on is disabled, or a flag it "- "depends on uses an unsupported configuration format."+ "The flag is archived, one of the flags it depends on is disabled, a flag it depends "+ "on uses an unsupported configuration format, or a cohort it targets has been deleted."),)def enable(self, request: request.Request, **kwargs) -> Response:@@ -4339,7 +4373,8 @@ class FeatureFlagViewSet(Sets `active` to true and changes nothing else. Targeting, variants, payloads, tags andarchived state are left as they are. An archived flag is refused: unarchive it first. Aflag whose own flag dependencies are disabled or use an unsupported configuration- format is also refused. An already-enabled flag is returned unchanged.+ format is also refused, as is a flag whose release conditions target a deleted cohort.+ An already-enabled flag is returned unchanged."""return self._set_active(request, active=True)@@ -4402,14 +4437,17 @@ class FeatureFlagViewSet(detail=True,required_scopes=["feature_flag:write"],request=None,- responses=flag_lifecycle_responses(approval_gated=False),+ responses=flag_lifecycle_responses(+ "One of the flag's release conditions targets a deleted cohort.", approval_gated=False+ ),)def unarchive(self, request: request.Request, **kwargs) -> Response:"""Restore an archived feature flag to the default flag list.Sets `archived` to false and changes nothing else. The flag stays disabled; enable it- with a separate call. An already-unarchived flag is returned unchanged.+ with a separate call. A flag whose release conditions target a deleted cohort is+ refused: remove that condition first. An already-unarchived flag is returned unchanged."""from products.feature_flags.backend.facade.api import unarchive_flagdiff --git a/products/feature_flags/backend/api/test/feature_flag_write_test_helpers.py b/products/feature_flags/backend/api/test/feature_flag_write_test_helpers.pynew file mode 100644index 000000000000..44708f943404--- /dev/null+++ b/products/feature_flags/backend/api/test/feature_flag_write_test_helpers.py@@ -0,0 +1,22 @@+"""Shared helpers for feature flag write tests. This module is not a test module itself."""++from typing import TYPE_CHECKING++from rest_framework.test import APIClient++if TYPE_CHECKING:+ from rest_framework.response import _MonkeyPatchedResponse++# Each mode turns a flag on without sending new targeting. The serializer must then check the stored filters.+# "restore" expects a soft-deleted flag stored with active=True. The other modes expect a disabled flag.+TURN_ON_MODES = ("patch", "empty", "action", "restore")+++def turn_flag_on(client: APIClient, flag_url: str, mode: str) -> "_MonkeyPatchedResponse":+ if mode == "action":+ return client.post(f"{flag_url}enable/", {}, format="json")+ if mode == "restore":+ return client.patch(flag_url, {"deleted": False}, format="json")+ if mode == "empty":+ return client.patch(flag_url, {"active": True, "filters": {}}, format="json")+ return client.patch(flag_url, {"active": True}, format="json")diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 2e53eda9aef7..4086666e3c39 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -72,6 +72,7 @@ from products.feature_flags.backend.api.feature_flag import (_flag_write_source,parse_created_by_ids,)+from products.feature_flags.backend.api.test.feature_flag_write_test_helpers import TURN_ON_MODES, turn_flag_onfrom products.feature_flags.backend.blast_radius_flag_deps import MAX_DEPENDENCY_DEPTHfrom products.feature_flags.backend.encrypted_flag_payloads import (REDACTED_PAYLOAD_VALUE,@@ -5071,22 +5072,136 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):expected_status=status.HTTP_201_CREATED,)- def test_creating_feature_flag_with_non_existant_cohort(self):- cohort_request = self._create_flag_with_properties(- "cohort-flag",- [{"key": "id", "type": "cohort", "value": 5151}],- expected_status=status.HTTP_400_BAD_REQUEST,+ def _unusable_cohort_id(self, cohort_state: str) -> int | str:+ if cohort_state == "missing":+ return (Cohort.objects.order_by("-id").values_list("id", flat=True).first() or 0) + 1+ if cohort_state == "malformed":+ return "not-an-id"+ if cohort_state == "boolean":+ # A live cohort with id 1 is what a boolean value would wrongly resolve to.+ Cohort.objects.update_or_create(pk=1, defaults={"team": self.team, "name": "First cohort"})+ return True+ return Cohort.objects.create(+ team=self.team,+ name=None if cohort_state == "deleted_unnamed" else "Retired cohort",+ filters={+ "properties": {+ "type": "AND",+ "values": [{"key": "email", "type": "person", "value": "@example.com", "operator": "icontains"}],+ }+ },+ deleted=True,+ ).id++ @staticmethod+ def _cohort_condition_filters(cohort_id: int | str) -> dict[str, Any]:+ return {"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort_id}]}]}++ @staticmethod+ def _unusable_cohort_detail(cohort_state: str, cohort_id: int | str) -> str:+ if cohort_state in ("missing", "malformed", "boolean"):+ return f"Cohort with id {cohort_id} does not exist"+ label = (+ f"Cohort with id {cohort_id}"+ if cohort_state == "deleted_unnamed"+ else f"Cohort 'Retired cohort' (ID {cohort_id})")+ return f"{label} has been deleted. Restore the cohort, choose another cohort, or remove this condition."+ @parameterized.expand(+ [+ ("missing_post", "missing", "post"),+ ("deleted_post", "deleted", "post"),+ ("deleted_patch", "deleted", "patch"),+ ("deleted_unnamed_post", "deleted_unnamed", "post"),+ ]+ )+ def test_writing_filters_with_missing_or_deleted_cohort_is_rejected(+ self, _name: str, cohort_state: str, method: str+ ) -> None:+ cohort_id = self._unusable_cohort_id(cohort_state)+ filters = self._cohort_condition_filters(cohort_id)+ url = f"/api/projects/{self.team.id}/feature_flags/"+ if method == "patch":+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="cohort-flag", filters=filters)+ response = self.client.patch(f"{url}{flag.id}/", {"filters": filters}, format="json")+ else:+ response = self.client.post(url, {"key": "cohort-flag", "filters": filters}, format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())self.assertLessEqual({"type": "validation_error","code": "cohort_does_not_exist",- "detail": "Cohort with id 5151 does not exist",+ "detail": self._unusable_cohort_detail(cohort_state, cohort_id),"attr": "filters",}.items(),- cohort_request.json().items(),+ response.json().items(),+ )++ @parameterized.expand(+ [(mode, mode, "deleted") for mode in (*TURN_ON_MODES, "restore_disabled", "unarchive")]+ + [+ ("patch_missing_cohort", "patch", "missing"),+ ("patch_malformed_cohort", "patch", "malformed"),+ ("patch_boolean_cohort", "patch", "boolean"),+ ]+ )+ def test_enabling_restoring_or_unarchiving_checks_stored_cohorts(+ self, _name: str, mode: str, cohort_state: str+ ) -> None:+ cohort_id = self._unusable_cohort_id(cohort_state)+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="cohort-flag",+ filters=self._cohort_condition_filters(cohort_id),+ active=mode == "restore",+ deleted=mode in ("restore", "restore_disabled"),+ archived=mode == "unarchive",+ version=7,+ )+ url = f"/api/projects/{self.team.id}/feature_flags/{flag.id}/"++ if mode == "restore_disabled":+ response = self.client.patch(url, {"deleted": False}, format="json")+ elif mode == "unarchive":+ response = self.client.post(f"{url}unarchive/", {}, format="json")+ else:+ response = turn_flag_on(self.client, url, mode)++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertLessEqual(+ {+ "code": "cohort_does_not_exist",+ "detail": self._unusable_cohort_detail(cohort_state, cohort_id),+ "attr": "filters",+ }.items(),+ response.json().items(),)+ flag.refresh_from_db()+ self.assertEqual(flag.version, 7)++ @parameterized.expand([("disable",), ("archive",), ("delete",), ("delete_archived",), ("rename_archived",)])+ def test_restrictive_writes_succeed_with_stored_deleted_cohort(self, action: str) -> None:+ archived = action.endswith("_archived")+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="cohort-flag",+ filters=self._cohort_condition_filters(self._unusable_cohort_id("deleted")),+ active=not archived,+ archived=archived,+ )+ url = f"/api/projects/{self.team.id}/feature_flags/{flag.id}/"+ if action.startswith("delete"):+ response = self.client.patch(url, {"deleted": True}, format="json")+ elif action == "rename_archived":+ response = self.client.patch(url, {"name": "Renamed"}, format="json")+ else:+ response = self.client.post(f"{url}{action}/", {}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)def test_validation_payloads(self):self._create_flag_with_properties(diff --git a/products/feature_flags/backend/api/test/test_feature_flag_dependency_formats.py b/products/feature_flags/backend/api/test/test_feature_flag_dependency_formats.pyindex b2c0fd3a5f5f..d9975e8410d5 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_dependency_formats.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_dependency_formats.py@@ -16,6 +16,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.team.team import Teamfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.api.test.feature_flag_write_test_helpers import TURN_ON_MODES, turn_flag_onfrom products.feature_flags.backend.dependency_formats import DEPENDENCY_BATCH_SIZEfrom products.feature_flags.backend.facade.api import create_flag, set_flag_active, update_flagfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -183,15 +184,7 @@ class TestFeatureFlagDependencyFormats(APIBaseTest):assert source.version == (7 if expected == 400 else 8)assert source.filters == ({"groups": []} if _name == "remove" else before)- @parameterized.expand(- [- ("enable_patch", "patch", False),- ("enable_empty_filters", "empty", False),- ("enable_action", "action", False),- ("restore_active", "restore", False),- ("enable_action_transitive", "action", True),- ]- )+ @parameterized.expand([(mode, mode, False) for mode in TURN_ON_MODES] + [("action_transitive", "action", True)])def test_enabling_or_restoring_checks_stored_reachable_formats(self, _name: str, mode: str, transitive: bool) -> None:@@ -204,15 +197,7 @@ class TestFeatureFlagDependencyFormats(APIBaseTest):deleted=mode == "restore",version=7,)- url = f"/api/projects/{self.team.id}/feature_flags/{source.id}/"- if mode == "action":- response = self.client.post(f"{url}enable/", {}, format="json")- elif mode == "restore":- response = self.client.patch(url, {"deleted": False}, format="json")- elif mode == "empty":- response = self.client.patch(url, {"active": True, "filters": {}}, format="json")- else:- response = self.client.patch(url, {"active": True}, format="json")+ response = turn_flag_on(self.client, f"/api/projects/{self.team.id}/feature_flags/{source.id}/", mode)assert response.status_code == 400, response.json()assert response.json()["code"] == "unsupported_dependency_config_version"assert response.json()["detail"] == (diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.pyindex fd990a7cd8ec..20e9e6743911 100644--- a/products/feature_flags/backend/facade/api.py+++ b/products/feature_flags/backend/facade/api.py@@ -39,7 +39,10 @@ from posthog.models.user import Userfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.approvals.backend.policies import PolicyEngine-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.api.feature_flag import (+ FeatureFlagSerializer,+ validate_stored_cohort_references as _validate_stored_cohort_references,+)from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUEfrom products.feature_flags.backend.facade.config import detect_config_formatfrom products.feature_flags.backend.facade.filters import set_feature_enrollment@@ -211,11 +214,24 @@ def unarchive_flag(flag: FeatureFlag, *, team: Team, user: Any, request: Any | N"""Unarchive a flag through the gated serializer path.The flag stays disabled; re-enabling it is a separate, explicit write- (``set_flag_active``).+ (``set_flag_active``). Raises ``ValidationError`` when a release condition targets a+ deleted cohort."""return update_flag(flag, {"archived": False}, team=team, user=user, request=request)+def validate_flag_restorable(flag_id: int, *, team_id: int) -> None:+ """Raise ``ValidationError`` when a release condition targets a missing or deleted cohort.++ A restored flag with such a condition fails every evaluation that reaches it. ``update_flag`` runs this+ check on a restore. A caller that restores a flag another way must run it first. A+ hard-deleted id or another team's flag has nothing to check.+ """+ flag = FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id, team_id=team_id).first()+ if flag is not None:+ _validate_stored_cohort_references(flag)++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).diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 242113da84e5..2931f6fe599a 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -433,6 +433,7 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixseen_cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,sort_by_topological_order=False,stop_traversal_at_static: bool = False,+ invalid_cohort_ids: InvalidIds | None = None,) -> list[int]:from products.cohorts.backend.models.util import get_all_cohort_dependencies, sort_cohorts_topologically@@ -440,10 +441,11 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixseen_cohorts_cache = {}cohort_ids = set()- # Unreadable formats raise. A non-integer id raises in v1, as it always did; v2 skips it, as Rust does.+ # Unreadable formats raise. By default, v1 raises on a non-integer id. v2 skips it, as Rust does.config = decode_config(self.get_filters())- invalid_ids: InvalidIds = "raise" if isinstance(config, ConfigV1) else "skip"- direct_ids = references(config, invalid_cohort_ids=invalid_ids).cohort_ids+ if invalid_cohort_ids is None:+ invalid_cohort_ids = "raise" if isinstance(config, ConfigV1) else "skip"+ direct_ids = references(config, invalid_cohort_ids=invalid_cohort_ids).cohort_idsfor cohort_id in direct_ids:try:if cohort_id in seen_cohorts_cache:diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex fc6acf2ca43e..0b66403c8588 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -848,7 +848,8 @@ export const getFeatureFlagsEnableCreateUrl = (projectId: string, id: number) =>* Sets `active` to true and changes nothing else. Targeting, variants, payloads, tags and* archived state are left as they are. An archived flag is refused: unarchive it first. A* flag whose own flag dependencies are disabled or use an unsupported configuration- * format is also refused. An already-enabled flag is returned unchanged.+ * format is also refused, as is a flag whose release conditions target a deleted cohort.+ * An already-enabled flag is returned unchanged.*/export const featureFlagsEnableCreate = async (projectId: string,@@ -1009,7 +1010,8 @@ export const getFeatureFlagsUnarchiveCreateUrl = (projectId: string, id: number)* Restore an archived feature flag to the default flag list.** Sets `archived` to false and changes nothing else. The flag stays disabled; enable it- * with a separate call. An already-unarchived flag is returned unchanged.+ * with a separate call. A flag whose release conditions target a deleted cohort is+ * refused: remove that condition first. An already-unarchived flag is returned unchanged.*/export const featureFlagsUnarchiveCreate = async (projectId: string,diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 57b4a2230b05..adfd4ba4594a 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -220,9 +220,10 @@ tools:the flag is served to, use `update-feature-flag`.- Returns 400 when the flag is archived (call `feature-flag-unarchive` first) or when a flag it depends on is- disabled. Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and- changes nothing, so retrying is safe.+ Returns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is+ disabled, or when a release condition targets a deleted cohort (remove that condition with+ `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag+ succeeds and changes nothing, so retrying is safe.`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags@@ -486,6 +487,10 @@ tools:The flag stays turned off. Call `feature-flag-enable` when the user also wants it serving again. Unarchivinga flag that is not archived succeeds and changes nothing, so retrying is safe.+++ Returns 400 when a release condition targets a deleted cohort. Remove that condition with+ `update-feature-flag` first.param_overrides:id:cast: string-intdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 11062d074b2d..0d04c0ef74b9 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6106,7 +6106,7 @@}},"feature-flag-enable": {- "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first) or when a flag it depends on is disabled. Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",+ "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.","category": "Feature flags","feature": "flags","summary": "Enable feature flag",@@ -6176,7 +6176,7 @@}},"feature-flag-unarchive": {- "description": "Restore an archived feature flag to the default flag list. Requires the flag's numeric ID; pass `{\"archived\":\"true\"}` to `feature-flag-get-all` to find archived flags.\n\nSets `archived` to false and changes nothing else. This tool never accepts or replaces the `filters` object. There is no request body.\n\nThe flag stays turned off. Call `feature-flag-enable` when the user also wants it serving again. Unarchiving a flag that is not archived succeeds and changes nothing, so retrying is safe.",+ "description": "Restore an archived feature flag to the default flag list. Requires the flag's numeric ID; pass `{\"archived\":\"true\"}` to `feature-flag-get-all` to find archived flags.\n\nSets `archived` to false and changes nothing else. This tool never accepts or replaces the `filters` object. There is no request body.\n\nThe flag stays turned off. Call `feature-flag-enable` when the user also wants it serving again. Unarchiving a flag that is not archived succeeds and changes nothing, so retrying is safe.\n\nReturns 400 when a release condition targets a deleted cohort. Remove that condition with `update-feature-flag` first.","category": "Feature flags","feature": "flags","summary": "Unarchive feature flag",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 4297f1533567..b426205a58be 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6261,7 +6261,7 @@}},"feature-flag-enable": {- "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first) or when a flag it depends on is disabled. Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",+ "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.","category": "Feature flags","feature": "flags","summary": "Enable feature flag",@@ -6345,7 +6345,7 @@}},"feature-flag-unarchive": {- "description": "Restore an archived feature flag to the default flag list. Requires the flag's numeric ID; pass `{\"archived\":\"true\"}` to `feature-flag-get-all` to find archived flags.\n\nSets `archived` to false and changes nothing else. This tool never accepts or replaces the `filters` object. There is no request body.\n\nThe flag stays turned off. Call `feature-flag-enable` when the user also wants it serving again. Unarchiving a flag that is not archived succeeds and changes nothing, so retrying is safe.",+ "description": "Restore an archived feature flag to the default flag list. Requires the flag's numeric ID; pass `{\"archived\":\"true\"}` to `feature-flag-get-all` to find archived flags.\n\nSets `archived` to false and changes nothing else. This tool never accepts or replaces the `filters` object. There is no request body.\n\nThe flag stays turned off. Call `feature-flag-enable` when the user also wants it serving again. Unarchiving a flag that is not archived succeeds and changes nothing, so retrying is safe.\n\nReturns 400 when a release condition targets a deleted cohort. Remove that condition with `update-feature-flag` first.","category": "Feature flags","feature": "flags","summary": "Unarchive feature flag",diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.tsindex fc68f92bd901..8c4c41d45543 100644--- a/services/mcp/src/generated/feature_flags/api.ts+++ b/services/mcp/src/generated/feature_flags/api.ts@@ -976,7 +976,8 @@ export const FeatureFlagsDisableCreateParams = () => zod.object({* Sets `active` to true and changes nothing else. Targeting, variants, payloads, tags and* archived state are left as they are. An archived flag is refused: unarchive it first. A* flag whose own flag dependencies are disabled or use an unsupported configuration- * format is also refused. An already-enabled flag is returned unchanged.+ * format is also refused, as is a flag whose release conditions target a deleted cohort.+ * An already-enabled flag is returned unchanged.*/export const FeatureFlagsEnableCreateParams = () => zod.object({id: zod.number().describe('A unique integer value identifying this feature flag.'),@@ -1144,7 +1145,8 @@ export const FeatureFlagsTestEvaluationCreateBody = () => zod.object({* Restore an archived feature flag to the default flag list.** Sets `archived` to false and changes nothing else. The flag stays disabled; enable it- * with a separate call. An already-unarchived flag is returned unchanged.+ * with a separate call. A flag whose release conditions target a deleted cohort is+ * refused: remove that condition first. An already-unarchived flag is returned unchanged.*/export const FeatureFlagsUnarchiveCreateParams = () => zod.object({id: zod.number().describe('A unique integer value identifying this feature flag.'),