Skip to content

: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.

fix(flags): resolve cohort names per page in the flag list (#118100)

Matheus Batistadcaf4e13c3f4
diff --git a/products/access_control/backend/tests/test_access_control.py b/products/access_control/backend/tests/test_access_control.py
index eee745d608bc..8cade81a9d13 100644
--- a/products/access_control/backend/tests/test_access_control.py
+++ b/products/access_control/backend/tests/test_access_control.py
@@ -1333,7 +1333,7 @@ class TestAccessControlQueryCounts(BaseAccessControlTest):
for i in range(10):
FeatureFlag.objects.create(team=self.team, created_by=self.other_user, key=f"flag-{i}")
- baseline = 16 # This is a lot! There is currently an n+1 issue with the legacy access control system
+ baseline = 14 # This is a lot! There is currently an n+1 issue with the legacy access control system
# +8: org, roles, preloaded permissions acs, preloaded acs for the list, survey internal flag
# IDs, the project's replay gates
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index bcbdc040f861..fb7a54c01f57 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -187,8 +187,6 @@ def is_cohort_recalculation_only_save(kwargs: dict) -> bool:
class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
name = models.CharField(max_length=400, null=True, blank=True)
description = models.CharField(max_length=1000, blank=True)
- # Not sealed: the feature flag list endpoint prefetches team__cohort_set
- # into available_cohorts.
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
deleted = models.BooleanField(default=False)
filters = models.JSONField(
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 1ca75f78e83a..ef8547bffc58 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -3541,7 +3541,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
# TODO: Make sure permission bool doesn't cause n + 1
# +1 query for survey internal flag IDs lookup, +1 for the project's replay gates
- with self.assertNumQueries(23):
+ with self.assertNumQueries(21):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
result = response.json()
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 21b6a6908548..f59da1de0626 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -1295,6 +1295,41 @@ class FeatureFlagExperimentSetMetadataSerializer(serializers.Serializer):
)
+COHORT_NAMES_CONTEXT_KEY = "feature_flag_cohort_names"
+
+
+class FeatureFlagListSerializer(serializers.ListSerializer):
+ """Resolves the cohort names of every flag on a page in one query, instead of one query per flag.
+
+ The cohort ids live in each flag's JSON filters, so a queryset prefetch cannot select them. This is
+ the only hook DRF gives that sees the whole page.
+ """
+
+ def to_representation(self, data: Any) -> Any:
+ flags = list(data)
+ assert isinstance(self.child, FeatureFlagSerializer)
+ cohort_ids: set[int] = set()
+ for flag in flags:
+ config = decode_config(flag.get_filters())
+ # A document no reader can parse has no cohort names to show, and must not fail the page.
+ if isinstance(config, UnsupportedConfig):
+ continue
+ cohort_ids.update(references(config).cohort_ids)
+ cohort_names: dict[str, str | None] = {}
+ if cohort_ids:
+ cohort_names = {
+ str(cohort_id): name
+ for cohort_id, name in Cohort.objects.filter(
+ id__in=cohort_ids, team__project_id=self.child.context["project_id"], deleted=False
+ ).values_list("id", "name")
+ }
+ self.child.context[COHORT_NAMES_CONTEXT_KEY] = cohort_names
+ try:
+ return super().to_representation(flags)
+ finally:
+ self.child.context.pop(COHORT_NAMES_CONTEXT_KEY, None)
+
+
class FeatureFlagSerializer(
TaggedItemSerializerMixin,
EvaluationContextSerializerMixin,
@@ -1364,6 +1399,7 @@ class FeatureFlagSerializer(
class Meta:
model = FeatureFlag
+ list_serializer_class = FeatureFlagListSerializer
fields = [
"id",
"name",
@@ -2953,20 +2989,10 @@ class FeatureFlagSerializer(
representation = super().to_representation(instance)
filters = representation.get("filters", {})
- # Get all cohort IDs used in the feature flag
- cohort_ids = set()
- for cohort_prop in self._get_cohort_properties_from_filters(filters):
- cohort_ids.add(cohort_prop.get("value"))
-
- # Use prefetched cohorts if available
- if hasattr(instance.team, "available_cohorts"):
- cohorts = {
- str(cohort.id): cohort.name
- for cohort in instance.team.available_cohorts
- if str(cohort.id) in map(str, cohort_ids)
- }
- else:
- # Fallback to database query if cohorts weren't prefetched
+ # FeatureFlagListSerializer resolves the names of a whole page. Retrieve and writes serialize one flag.
+ cohorts = self.context.get(COHORT_NAMES_CONTEXT_KEY)
+ if cohorts is None:
+ cohort_ids = {cohort_prop.get("value") for cohort_prop in self._get_cohort_properties_from_filters(filters)}
cohorts = {
str(cohort.id): cohort.name
for cohort in Cohort.objects.filter(id__in=cohort_ids, team__project_id=self.context["project_id"])
@@ -4049,13 +4075,6 @@ class FeatureFlagViewSet(
).prefetch_related("actions"),
)
)
- .prefetch_related(
- Prefetch(
- "team__cohort_set",
- queryset=Cohort.objects.filter(deleted=False).only("id", "name"),
- to_attr="available_cohorts",
- )
- )
)
survey_flag_ids = Survey.get_internal_flag_ids(project_id=self.project_id)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index fb5a3a4f84b6..a1ee5ad88abd 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -4555,33 +4555,41 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert keys & {"flag-with-contexts", "flag-without-contexts"} == expected_keys
def test_getting_flags_is_not_nplus1(self) -> None:
- self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- data={
- "name": f"flag",
- "key": f"flag_0",
- "filters": {"groups": [{"rollout_percentage": 5}]},
- },
- format="json",
- ).json()
-
- with self.assertNumQueries(FuzzyInt(19, 20)):
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- for i in range(1, 5):
- self.client.post(
+ def create_flag_targeting_a_new_cohort(i: int) -> None:
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name=f"cohort_{i}",
+ groups=[{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}],
+ )
+ response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
data={
"name": f"flag",
"key": f"flag_{i}",
- "filters": {"groups": [{"rollout_percentage": 5}]},
+ "filters": {
+ "groups": [
+ {
+ "properties": [{"key": "id", "type": "cohort", "value": cohort.pk}],
+ "rollout_percentage": 5,
+ }
+ ]
+ },
},
format="json",
- ).json()
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ create_flag_targeting_a_new_cohort(0)
+
+ with self.assertNumQueries(FuzzyInt(18, 19)):
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ for i in range(1, 5):
+ create_flag_targeting_a_new_cohort(i)
- # Query count should stay constant regardless of flag count (no N+1)
- with self.assertNumQueries(FuzzyInt(19, 20)):
+ # Query count should stay constant regardless of flag and cohort count (no N+1)
+ with self.assertNumQueries(FuzzyInt(18, 19)):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -4605,7 +4613,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
name="Flag role access",
)
- with self.assertNumQueries(FuzzyInt(19, 20)):
+ with self.assertNumQueries(FuzzyInt(17, 18)):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 2)
@@ -4644,7 +4652,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
# Capture query count with 5 flags
- with self.assertNumQueries(FuzzyInt(17, 22)):
+ with self.assertNumQueries(FuzzyInt(17, 21)):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 5)
@@ -4668,7 +4676,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
# Query count should remain similar (not scale linearly with flag count)
- with self.assertNumQueries(FuzzyInt(17, 24)):
+ with self.assertNumQueries(FuzzyInt(17, 20)):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 30)
@@ -4719,7 +4727,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
# Should not cause extra queries for the targeting flags
- with self.assertNumQueries(FuzzyInt(15, 22)):
+ with self.assertNumQueries(FuzzyInt(15, 21)):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Should include main_flag but not targeting flags (they're filtered out)
@@ -7216,38 +7224,47 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
response.json().items(),
)
- def test_feature_flag_includes_cohort_names(self):
- cohort = Cohort.objects.create(
+ @parameterized.expand([("retrieve",), ("list",)])
+ def test_feature_flag_includes_cohort_names(self, endpoint: str):
+ groups = [{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}]
+ cohort = Cohort.objects.create(team=self.team, name="test_cohort", groups=groups)
+ other_project_team = Team.objects.create(organization=self.organization, name="Other project")
+ other_project_cohort = Cohort.objects.create(team=other_project_team, name="other_cohort", groups=groups)
+ flag = FeatureFlag.objects.create(
team=self.team,
- name="test_cohort",
- groups=[{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}],
- )
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Alpha feature",
- "key": "alpha-feature",
- "filters": {
- "groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}],
- },
+ created_by=self.user,
+ key="alpha-feature",
+ filters={
+ "groups": [
+ {"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]},
+ {"properties": [{"key": "id", "type": "cohort", "value": str(cohort.pk)}]},
+ {"properties": [{"key": "id", "type": "cohort", "value": other_project_cohort.pk}]},
+ ]
},
- format="json",
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- # Get the flag
- response = self.client.get(
- f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="legacy-malformed-cohort-value",
+ filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": "not-a-cohort-id"}]}]},
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ if endpoint == "list":
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ filters = next(result for result in response.json()["results"] if result["id"] == flag.id)["filters"]
+ else:
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ filters = response.json()["filters"]
+
self.assertEqual(
- response.json()["filters"]["groups"][0]["properties"][0],
- {
- "key": "id",
- "type": "cohort",
- "value": cohort.pk,
- "cohort_name": "test_cohort",
- },
+ [group["properties"][0] for group in filters["groups"]],
+ [
+ {"key": "id", "type": "cohort", "value": cohort.pk, "cohort_name": "test_cohort"},
+ {"key": "id", "type": "cohort", "value": str(cohort.pk), "cohort_name": "test_cohort"},
+ {"key": "id", "type": "cohort", "value": other_project_cohort.pk, "cohort_name": None},
+ ],
)
def test_feature_flag_includes_group_key_names(self):
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 12edd87f7a42..998a581254cc 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -1601,7 +1601,7 @@ class TestSurvey(APIBaseTest):
).json()
# Includes one query for the project's replay gates
- with self.assertNumQueries(21):
+ with self.assertNumQueries(19):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
result = response.json()