: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): allow static snapshot cohorts in flag conditions (#65355)
Ryan Chung5a77b3e699d5
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 463e9e25ff2e..fd7d690f5ad0 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -4,6 +4,7 @@ import timeimport uuidimport hashlibfrom collections.abc import Iterator+from copy import deepcopyfrom typing import Annotated, Any, Literal, Optional, Union, castfrom django.db.models import OuterRef, QuerySet, Subquery@@ -921,14 +922,34 @@ class CohortSerializer(serializers.ModelSerializer):raise ValidationError(f"Query must be an ActorsQuery or HogQLQuery. Got: {query.get('kind')}")return query+ def _cohort_will_be_static(self) -> bool:+ if "is_static" in self.initial_data:+ return str_to_bool(self.initial_data["is_static"])+ return bool(getattr(self.instance, "is_static", False))++ def _effective_filters_after_update(self, attrs: dict) -> dict | None:+ # PATCH may send legacy groups without filters, derive the post-update properties for validation+ instance = cast(Cohort, self.instance)+ filters = attrs.get("filters", instance.filters)+ if filters:+ return filters++ groups = attrs.get("groups", instance.groups)+ if not groups:+ return None++ cohort = Cohort(team=instance.team, filters=None, groups=deepcopy(groups))+ return {"properties": cohort.properties.to_dict()}+def validate_filters(self, raw: dict):"""1. structural/schema check → pydantic2. domain rules (feature-flag gotchas) → bespoke fn3. bytecode generation → add bytecode fields to filters"""- is_static = self.initial_data.get("is_static") or getattr(self.instance, "is_static", False)- if is_static and not cohort_filters_have_values(raw):+ cohort_will_be_static = self._cohort_will_be_static()++ if cohort_will_be_static and not cohort_filters_have_values(raw):return rawif not isinstance(raw, dict) or "properties" not in raw:raise ValidationError(@@ -947,9 +968,26 @@ class CohortSerializer(serializers.ModelSerializer):# pydantic → drf error shaperaise ValidationError(detail=self._cohort_error_message(exc))- self._validate_feature_flag_constraints(raw) # keep your side-rules+ self._validate_feature_flag_constraints(raw, cohort_will_be_static) # keep your side-rulesreturn raw+ def validate(self, attrs: dict) -> dict:+ # Field-level validate_filters only runs when the PATCH body includes `filters`. This+ # object-level guard covers the static-to-dynamic flip when it does not, re-checking the+ # instance's preserved behavioral filters against the feature-flag rule.+ attrs = super().validate(attrs)++ if self.context["request"].method != "PATCH" or self.instance is None:+ return attrs++ instance = cast(Cohort, self.instance)+ if instance.is_static and attrs.get("is_static") is False:+ effective_filters = self._effective_filters_after_update(attrs)+ if effective_filters is not None and cohort_filters_have_values(effective_filters):+ self._validate_feature_flag_constraints(effective_filters, cohort_will_be_static=False)++ return attrs+@staticmethoddef _cohort_error_message(exc: PydanticValidationError) -> str:"""@@ -974,16 +1012,19 @@ class CohortSerializer(serializers.ModelSerializer):return f"Missing required keys for {kind} filter: {missing_field}"return str(exc.errors())- def _validate_feature_flag_constraints(self, request_filters: dict):+ def _validate_feature_flag_constraints(self, request_filters: dict, cohort_will_be_static: bool):if self.context["request"].method != "PATCH":returnparsed_filter = Filter(data=request_filters)instance = cast(Cohort, self.instance)+ if instance.is_static and cohort_will_be_static:+ return+cohort_id = instance.pkflags = FeatureFlag.objects.filter(team__project_id=self.context["project_id"], active=True)- cohort_used_in_flags = len([flag for flag in flags if cohort_id in flag.get_cohort_ids()]) > 0+ cohort_used_in_flags = any(cohort_id in flag.get_cohort_ids(stop_traversal_at_static=True) for flag in flags)if not cohort_used_in_flags:return@@ -1000,9 +1041,13 @@ class CohortSerializer(serializers.ModelSerializer):def _validate_nested_cohort_behavioral_filters(self, prop: Any, cohort_used_in_flags: bool):nested_cohort = Cohort.objects.get(pk=prop.value, team__project_id=self.context["project_id"])- dependency_cohorts = get_all_cohort_dependencies(nested_cohort)+ dependency_cohorts = get_all_cohort_dependencies(nested_cohort, stop_traversal_at_static=True)for dependency_cohort in [nested_cohort, *dependency_cohorts]:+ # Static cohorts have materialized membership, any preserved behavioral+ # filters are display-only and never evaluated, so skip them.+ if dependency_cohort.is_static:+ continueif cohort_used_in_flags and any(p.type == "behavioral" for p in dependency_cohort.properties.flat):raise serializers.ValidationError(detail=f"A cohort dependency ({dependency_cohort.name}) has filters based on events. These cohorts can't be used in feature flags.",@@ -1229,7 +1274,9 @@ def _directly_referenced_cohort_ids(flags: list[FeatureFlag]) -> set[int]:}-def _filter_flags_referencing_cohort(flags: QuerySet[FeatureFlag], cohort: Cohort) -> list[FeatureFlag]:+def _filter_flags_referencing_cohort(+ flags: QuerySet[FeatureFlag], cohort: Cohort, *, stop_traversal_at_static: bool = False+) -> list[FeatureFlag]:"""Expand each flag's cohort references in Python and keep flags that reach this cohort.The cache is seeded with the target cohort and bulk-loaded with every cohort the@@ -1248,7 +1295,15 @@ def _filter_flags_referencing_cohort(flags: QuerySet[FeatureFlag], cohort: Cohorseen_cohorts_cache[direct_cohort.pk] = direct_cohortfor missing_id in direct_ids - seen_cohorts_cache.keys():seen_cohorts_cache[missing_id] = ""- return [flag for flag in flag_list if cohort.id in flag.get_cohort_ids(seen_cohorts_cache=seen_cohorts_cache)]+ return [+ flag+ for flag in flag_list+ if cohort.id+ in flag.get_cohort_ids(+ seen_cohorts_cache=seen_cohorts_cache,+ stop_traversal_at_static=stop_traversal_at_static,+ )+ ]def get_active_flags_using_cohort(cohort: Cohort) -> list[FeatureFlag]:@@ -1256,7 +1311,11 @@ def get_active_flags_using_cohort(cohort: Cohort) -> list[FeatureFlag]:Used by deletion protection: only live flags should block cohort deletion."""- return _filter_flags_referencing_cohort(_flags_with_cohort_filters(cohort).filter(active=True), cohort)+ return _filter_flags_referencing_cohort(+ _flags_with_cohort_filters(cohort).filter(active=True),+ cohort,+ stop_traversal_at_static=True,+ )def get_insights_using_cohort(cohort: Cohort) -> QuerySet[Insight]:@@ -1653,7 +1712,7 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelViflags_qs = uac.filter_queryset_by_access_level(_flags_with_cohort_filters(cohort), include_all_if_admin=True).order_by("id")- flags = _filter_flags_referencing_cohort(flags_qs, cohort)+ flags = _filter_flags_referencing_cohort(flags_qs, cohort, stop_traversal_at_static=True)flags_data = [{"id": flag.id, "key": flag.key, "name": flag.name} for flag in flags]insights_qs = uac.filter_queryset_by_access_level(get_insights_using_cohort(cohort))diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 70df9d1d84ab..83a48d17117d 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -24,7 +24,7 @@ from rest_framework import statusfrom posthog.schema import PersonsOnEventsMode, PropertyOperator-from posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE+from posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE, CohortFiltersfrom posthog.clickhouse.client.execute import sync_executefrom posthog.models import Person, Userfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -3303,6 +3303,305 @@ [email protected],response.json().items(),)+ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_update_cohort_used_in_flags_allows_static_snapshot_cohort_that_preserves_behavioral_filters(+ self, patch_calculate_cohort, patch_capture+ ) -> None:+ def cohort_filter(cohort_id: int) -> dict[str, Any]:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ def filters_for(prop: dict[str, Any]) -> dict[str, Any]:+ return {"properties": {"type": "OR", "values": [prop]}}++ behavioral_filter = {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }++ cohort = Cohort.objects.create(+ team=self.team,+ name="cohort A",+ filters=filters_for({"key": "$some_prop", "value": "something", "type": "person", "operator": "exact"}),+ )+ static_snapshot_cohort = Cohort.objects.create(+ team=self.team,+ name="static snapshot cohort",+ is_static=True,+ filters=filters_for(behavioral_filter),+ )+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [cohort_filter(cohort.pk)]}]},+ name="This is a cohort-based flag",+ key="cohort-flag",+ created_by=self.user,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort.pk}",+ data={"name": "cohort A", "filters": filters_for(cohort_filter(static_snapshot_cohort.pk))},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)++ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_update_cohort_used_in_flags_allows_cohort_depending_on_static_snapshot_cohort(+ self, patch_calculate_cohort, patch_capture+ ) -> None:+ def cohort_filter(cohort_id: int) -> dict[str, Any]:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ def filters_for(prop: dict[str, Any]) -> dict[str, Any]:+ return {"properties": {"type": "OR", "values": [prop]}}++ behavioral_filter = {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }++ cohort = Cohort.objects.create(+ team=self.team,+ name="cohort A",+ filters=filters_for({"key": "$some_prop", "value": "something", "type": "person", "operator": "exact"}),+ )+ behavioral_cohort = Cohort.objects.create(+ team=self.team, name="behavioral cohort", filters=filters_for(behavioral_filter)+ )+ static_cohort = Cohort.objects.create(+ team=self.team,+ name="static cohort",+ is_static=True,+ filters=filters_for(cohort_filter(behavioral_cohort.pk)),+ )+ nested_cohort = Cohort.objects.create(+ team=self.team,+ name="nested cohort",+ filters=filters_for(cohort_filter(static_cohort.pk)),+ )+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [cohort_filter(cohort.pk)]}]},+ name="This is a cohort-based flag",+ key="cohort-flag",+ created_by=self.user,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort.pk}",+ data={"name": "cohort A", "filters": filters_for(cohort_filter(nested_cohort.pk))},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)++ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_update_cohort_behind_static_snapshot_used_in_flag_allows_behavioral_filters(+ self, patch_calculate_cohort, patch_capture+ ) -> None:+ def cohort_filter(cohort_id: int) -> dict[str, Any]:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ def filters_for(prop: dict[str, Any]) -> dict[str, Any]:+ return {"properties": {"type": "OR", "values": [prop]}}++ source_cohort = Cohort.objects.create(+ team=self.team,+ name="source cohort",+ filters=filters_for({"key": "$some_prop", "value": "something", "type": "person", "operator": "exact"}),+ )+ static_snapshot_cohort = Cohort.objects.create(+ team=self.team,+ name="static snapshot cohort",+ is_static=True,+ filters=filters_for(cohort_filter(source_cohort.pk)),+ )+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [cohort_filter(static_snapshot_cohort.pk)]}]},+ name="This is a static cohort-based flag",+ key="static-cohort-flag",+ created_by=self.user,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{source_cohort.pk}",+ data={+ "name": "source cohort",+ "filters": filters_for(+ {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }+ ),+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)++ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_update_static_cohort_used_in_flag_preserves_behavioral_filters(+ self, patch_calculate_cohort, patch_capture+ ) -> None:+ def cohort_filter(cohort_id: int) -> dict[str, Any]:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ def filters_for(prop: dict[str, Any]) -> dict[str, Any]:+ return {"properties": {"type": "OR", "values": [prop]}}++ behavioral_filter = {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }+ static_filters = CohortFilters.model_validate(+ filters_for(behavioral_filter), context={"team": self.team}+ ).model_dump(exclude_none=True)+ static_cohort = Cohort.objects.create(+ team=self.team,+ name="static cohort",+ is_static=True,+ filters=static_filters,+ )+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [cohort_filter(static_cohort.pk)]}]},+ name="This is a static cohort-based flag",+ key="static-cohort-flag",+ created_by=self.user,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{static_cohort.pk}",+ data={+ "name": "renamed static cohort",+ "filters": static_filters,+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)++ @parameterized.expand([("with_filters", True), ("without_filters", False)])+ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_update_static_cohort_used_in_flag_rejects_static_to_dynamic_behavioral_filters(+ self, _name: str, include_filters: bool, patch_calculate_cohort, patch_capture+ ) -> None:+ def cohort_filter(cohort_id: int) -> dict[str, Any]:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ def filters_for(prop: dict[str, Any]) -> dict[str, Any]:+ return {"properties": {"type": "OR", "values": [prop]}}++ behavioral_filter = {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }+ static_filters = CohortFilters.model_validate(+ filters_for(behavioral_filter), context={"team": self.team}+ ).model_dump(exclude_none=True)+ static_cohort = Cohort.objects.create(+ team=self.team,+ name="static cohort",+ is_static=True,+ filters=static_filters,+ )+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [cohort_filter(static_cohort.pk)]}]},+ name="This is a static cohort-based flag",+ key="static-cohort-flag",+ created_by=self.user,+ )++ data = {+ "name": "static cohort",+ "is_static": False,+ }+ if include_filters:+ data["filters"] = static_filters++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{static_cohort.pk}",+ data=data,+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ self.assertLessEqual(+ {+ "type": "validation_error",+ "code": "behavioral_cohort_found",+ "detail": "Behavioral filters cannot be added to cohorts used in feature flags.",+ "attr": "filters" if include_filters else None,+ }.items(),+ response.json().items(),+ )++ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_update_static_cohort_used_in_flag_rejects_static_to_dynamic_behavioral_groups(+ self, patch_calculate_cohort, patch_capture+ ) -> None:+ def cohort_filter(cohort_id: int) -> dict[str, Any]:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ behavioral_filter = {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }+ static_cohort = Cohort.objects.create(+ team=self.team,+ name="static cohort",+ is_static=True,+ groups=[{"properties": [behavioral_filter]}],+ )+ self.assertIsNone(static_cohort.filters)+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [cohort_filter(static_cohort.pk)]}]},+ name="This is a static cohort-based flag",+ key="static-cohort-flag",+ created_by=self.user,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{static_cohort.pk}",+ data={+ "name": "static cohort",+ "is_static": False,+ },+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ self.assertLessEqual(+ {+ "type": "validation_error",+ "code": "behavioral_cohort_found",+ "detail": "Behavioral filters cannot be added to cohorts used in feature flags.",+ "attr": None,+ }.items(),+ response.json().items(),+ )+@patch("django.db.transaction.on_commit", side_effect=lambda func: func())def test_duplicating_dynamic_cohort_as_static(self, patch_on_commit):_create_person(@@ -5289,6 +5588,34 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):)return cohort_a_id, cohort_b_id+ def _create_flag_referencing_cohort_through_static_snapshot(self) -> tuple[int, int]:+ def cohort_filter(cohort_id: int) -> dict[str, Any]:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ def filters_for(prop: dict[str, Any]) -> dict[str, Any]:+ return {"properties": {"type": "OR", "values": [prop]}}++ source_cohort = Cohort.objects.create(+ team=self.team,+ name="Source cohort",+ filters=filters_for({"key": "$some_prop", "value": "something", "type": "person", "operator": "exact"}),+ )+ static_snapshot_cohort = Cohort.objects.create(+ team=self.team,+ name="Static snapshot cohort",+ is_static=True,+ filters=filters_for(cohort_filter(source_cohort.pk)),+ )+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [cohort_filter(static_snapshot_cohort.pk)]}]},+ name="Static snapshot flag",+ key="static-snapshot-flag",+ created_by=self.user,+ active=True,+ )+ return source_cohort.pk, static_snapshot_cohort.pk+@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_used_in_returns_feature_flags(self, patch_calculate_cohort, patch_capture):@@ -5372,6 +5699,15 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):self.assertEqual(len(flags), 1)self.assertEqual(flags[0]["key"], "transitive-flag")+ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_used_in_excludes_flags_behind_static_snapshot(self, patch_calculate_cohort, patch_capture):+ source_cohort_id, _ = self._create_flag_referencing_cohort_through_static_snapshot()++ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{source_cohort_id}/used_in")+ 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_used_in_excludes_flags_referencing_a_different_cohort(self, patch_calculate_cohort, patch_capture):@@ -5840,6 +6176,23 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):response.json()["detail"],)+ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_deletion_protection_ignores_flags_behind_static_snapshot(self, patch_calculate_cohort, patch_capture):+ source_cohort_id, _ = self._create_flag_referencing_cohort_through_static_snapshot()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{source_cohort_id}",+ data={"deleted": True},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertNotIn("active feature flag", response.json()["detail"])+ self.assertIn(+ "This cohort is used as criteria in 1 other cohort(s): Static snapshot cohort",+ response.json()["detail"],+ )+class TestCalculateCohortCommand(APIBaseTest):def test_calculate_cohort_command_success(self):diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.pyindex 7f153348e5b9..354c53b3c1ea 100644--- a/products/cohorts/backend/models/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -714,6 +714,22 @@ class TestDependentCohorts(BaseTest):self.assertEqual(get_all_cohort_dependencies(cohort1), [])self.assertEqual(get_all_cohort_dependencies(cohort2), [cohort1])+ def test_dependent_cohorts_stop_traversal_at_static_root_cohort(self) -> None:+ cohort1 = _create_cohort(+ team=self.team,+ name="cohort1",+ groups=[{"properties": [{"key": "name", "value": "test", "type": "person"}]}],+ )++ static_cohort = _create_cohort(+ team=self.team,+ name="static-cohort",+ groups=[{"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]}],+ is_static=True,+ )++ self.assertEqual(get_all_cohort_dependencies(static_cohort, stop_traversal_at_static=True), [])+def test_dependent_cohorts_for_deeply_nested_cohort(self):cohort1 = _create_cohort(team=self.team,diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex b86a26f5c63d..225175989058 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -956,10 +956,21 @@ def get_all_cohort_dependencies(cohort: Cohort,using_database: str = "default",seen_cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,+ stop_traversal_at_static: bool = False,) -> list[Cohort]:+ """+ Return cohorts referenced by this cohort, recursively.++ When stop_traversal_at_static is True, a static root cohort returns no dependencies.+ Static nested cohorts are still returned, but their own dependencies are not traversed.+ """+if seen_cohorts_cache is None:seen_cohorts_cache = {}+ if stop_traversal_at_static and cohort.is_static:+ return []+cohorts = []seen_cohort_ids = set()seen_cohort_ids.add(cohort.id)@@ -982,7 +993,8 @@ def get_all_cohort_dependencies(cohorts.append(current_cohort)seen_cohort_ids.add(current_cohort.id)- queue.extend(get_nested_cohort_ids(current_cohort))+ if not (stop_traversal_at_static and current_cohort.is_static):+ queue.extend(get_nested_cohort_ids(current_cohort))except Cohort.DoesNotExist:seen_cohorts_cache[cohort_id] = ""diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 7ee010308e73..c589e81e6cf8 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -1341,9 +1341,13 @@ class FeatureFlagSerializer(initial_cohort: Cohort = Cohort.objects.get(pk=cast(str | int, prop.value), team__project_id=self.context["project_id"])- dependency_cohorts = get_all_cohort_dependencies(initial_cohort)+ dependency_cohorts = get_all_cohort_dependencies(initial_cohort, stop_traversal_at_static=True)for cohort in [initial_cohort, *dependency_cohorts]:- if [prop for prop in cohort.properties.flat if prop.type == "behavioral"]:+ # Static cohorts have materialized membership, any preserved behavioral+ # filters are display-only and never evaluated, so skip them.+ if cohort.is_static:+ continue+ if any(cohort_prop.type == "behavioral" for cohort_prop in cohort.properties.flat):_validate_behavioral_cohort_for_feature_flag(cohort, allow_realtime_backfilled=self._allow_realtime_backfilled)diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex b6b493307878..971a69ffda27 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -5045,6 +5045,71 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):response.json().items(),)+ def test_creating_feature_flag_with_static_snapshot_cohort_that_preserves_behavioral_filters(self) -> None:+ cohort = Cohort.objects.create(+ team=self.team,+ is_static=True,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }+ ],+ }+ },+ )++ self._create_flag_with_properties(+ "cohort-flag",+ [{"key": "id", "type": "cohort", "value": cohort.id}],+ expected_status=status.HTTP_201_CREATED,+ )++ def test_creating_feature_flag_with_cohort_depending_on_static_snapshot_cohort(self) -> None:+ behavioral_cohort = Cohort.objects.create(+ team=self.team,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "event_type": "events",+ "explicit_datetime": "-14d",+ "key": "$pageview",+ "value": "performed_event_first_time",+ "type": "behavioral",+ }+ ],+ }+ },+ )+ static_cohort = Cohort.objects.create(+ team=self.team,+ is_static=True,+ filters={+ "properties": {+ "type": "AND",+ "values": [{"key": "id", "type": "cohort", "value": behavioral_cohort.id}],+ }+ },+ )+ cohort = Cohort.objects.create(+ team=self.team,+ groups=[{"properties": [{"key": "id", "type": "cohort", "value": static_cohort.id}]}],+ )++ self._create_flag_with_properties(+ "cohort-flag",+ [{"key": "id", "type": "cohort", "value": cohort.id}],+ expected_status=status.HTTP_201_CREATED,+ )+def test_creating_feature_flag_with_nested_behavioral_cohort(self):cohort_not_valid_for_ff = Cohort.objects.create(team=self.team,diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 8da139176d5b..fc208516d4ae 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -435,6 +435,7 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsusing_database: str = "default",seen_cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,sort_by_topological_order=False,+ stop_traversal_at_static: bool = False,) -> list[int]:from products.cohorts.backend.models.util import get_all_cohort_dependencies, sort_cohorts_topologically@@ -468,6 +469,7 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelscohort,using_database=using_database,seen_cohorts_cache=seen_cohorts_cache,+ stop_traversal_at_static=stop_traversal_at_static,)])