: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): filter group flag usage insights to group evaluations (#65981)
Lucky negi9b05e9d4a516
diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.pyindex 396dfbc33b18..95b64a4e5994 100644--- a/posthog/helpers/dashboard_templates.py+++ b/posthog/helpers/dashboard_templates.py@@ -702,6 +702,80 @@ FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME = "Feature Flag Called Total Volume"FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME = "Feature Flag calls made by unique users per variant"+def _get_aggregation_entity_labels(feature_flag) -> tuple[str | None, str | None]:+ group_type_index = feature_flag.aggregation_group_type_index+ if group_type_index is None:+ return None, None++ from posthog.models.group_type_mapping import GroupTypeMapping, get_group_type_mapping_instance++ try:+ mapping = get_group_type_mapping_instance(+ feature_flag.team.project_id,+ group_type_index,+ team=feature_flag.team,+ )+ except GroupTypeMapping.DoesNotExist:+ return "group", "groups"++ singular = mapping.name_singular or mapping.group_type+ plural = mapping.name_plural or f"{mapping.group_type}s"+ return singular, plural+++def _build_feature_flag_called_property_group(feature_flag) -> dict[str, Any]:+ filter_values: list[dict[str, Any]] = [+ {+ "key": "$feature_flag",+ "operator": "exact",+ "type": "event",+ "value": feature_flag.key,+ }+ ]+ group_type_index = feature_flag.aggregation_group_type_index+ if group_type_index is not None:+ filter_values.append(+ {+ "key": f"$group_{group_type_index}",+ "operator": "is_set",+ "type": "event",+ "value": "is_set",+ }+ )++ return {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": filter_values,+ }+ ],+ }+++def _get_feature_flag_unique_calls_series(feature_flag) -> dict[str, Any]:+ series: dict[str, Any] = {+ "event": "$feature_flag_called",+ "kind": "EventsNode",+ "name": "$feature_flag_called",+ }+ group_type_index = feature_flag.aggregation_group_type_index+ if group_type_index is not None:+ series["math"] = "unique_group"+ series["math_group_type_index"] = group_type_index+ else:+ series["math"] = "dau"+ return series+++def _get_feature_flag_unique_calls_insight_name(feature_flag) -> str:+ _, plural = _get_aggregation_entity_labels(feature_flag)+ if plural is None:+ return FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME+ return f"Feature Flag calls made by unique {plural} per variant"++def create_feature_flag_dashboard(feature_flag, dashboard: Dashboard, user) -> None:dashboard.filters = {"date_from": "-30d"}tag, _ = Tag.objects.get_or_create(@@ -716,7 +790,7 @@ def create_feature_flag_dashboard(feature_flag, dashboard: Dashboard, user) -> N_create_tile_for_insight(dashboard,name=FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME,- description=_get_feature_flag_total_volume_insight_description(feature_flag.key),+ description=_get_feature_flag_total_volume_insight_description(feature_flag),query={"kind": "InsightVizNode","source": {@@ -725,22 +799,7 @@ def create_feature_flag_dashboard(feature_flag, dashboard: Dashboard, user) -> N"filterTestAccounts": False,"interval": "day","kind": "TrendsQuery",- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$feature_flag",- "operator": "exact",- "type": "event",- "value": feature_flag.key,- }- ],- }- ],- },+ "properties": _build_feature_flag_called_property_group(feature_flag),"series": [{"event": "$feature_flag_called", "kind": "EventsNode", "name": "$feature_flag_called"}],"trendsFilter": {"aggregationAxisFormat": "numeric",@@ -772,8 +831,8 @@ def create_feature_flag_dashboard(feature_flag, dashboard: Dashboard, user) -> N_create_tile_for_insight(dashboard,- name=FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME,- description=_get_feature_flag_unique_users_insight_description(feature_flag.key),+ name=_get_feature_flag_unique_calls_insight_name(feature_flag),+ description=_get_feature_flag_unique_calls_insight_description(feature_flag),query={"kind": "InsightVizNode","source": {@@ -782,30 +841,8 @@ def create_feature_flag_dashboard(feature_flag, dashboard: Dashboard, user) -> N"filterTestAccounts": False,"interval": "day","kind": "TrendsQuery",- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$feature_flag",- "operator": "exact",- "type": "event",- "value": feature_flag.key,- }- ],- }- ],- },- "series": [- {- "event": "$feature_flag_called",- "kind": "EventsNode",- "math": "dau",- "name": "$feature_flag_called",- }- ],+ "properties": _build_feature_flag_called_property_group(feature_flag),+ "series": [_get_feature_flag_unique_calls_series(feature_flag)],"trendsFilter": {"aggregationAxisFormat": "numeric","display": "ActionsTable",@@ -1079,12 +1116,16 @@ def create_data_ops_dashboard(team, user) -> Dashboard:return dashboard-def _get_feature_flag_total_volume_insight_description(feature_flag_key: str) -> str:- return f"Shows the number of total calls made on feature flag with key: {feature_flag_key}"+def _get_feature_flag_total_volume_insight_description(feature_flag, *, key: str | None = None) -> str:+ return f"Shows the number of total calls made on feature flag with key: {key or feature_flag.key}"-def _get_feature_flag_unique_users_insight_description(feature_flag_key: str) -> str:- return f"Shows the number of unique user calls made on feature flag per variant with key: {feature_flag_key}"+def _get_feature_flag_unique_calls_insight_description(feature_flag, *, key: str | None = None) -> str:+ singular, _ = _get_aggregation_entity_labels(feature_flag)+ flag_key = key or feature_flag.key+ if singular is None:+ return f"Shows the number of unique user calls made on feature flag per variant with key: {flag_key}"+ return f"Shows the number of unique {singular} calls made on feature flag per variant with key: {flag_key}"def update_feature_flag_dashboard(feature_flag, old_key: str) -> None:@@ -1098,24 +1139,33 @@ def update_feature_flag_dashboard(feature_flag, old_key: str) -> None:if total_volume_insight:_update_tile_with_new_key(total_volume_insight,- feature_flag.key,+ feature_flag,old_key,_get_feature_flag_total_volume_insight_description,)- unique_users_insight = dashboard.insights.filter(name=FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME).first()- if unique_users_insight:+ unique_calls_insight = dashboard.insights.filter(+ name=_get_feature_flag_unique_calls_insight_name(feature_flag)+ ).first()+ if unique_calls_insight is None:+ unique_calls_insight = dashboard.insights.filter(name=FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME).first()+ if unique_calls_insight:_update_tile_with_new_key(- unique_users_insight,- feature_flag.key,+ unique_calls_insight,+ feature_flag,old_key,- _get_feature_flag_unique_users_insight_description,+ _get_feature_flag_unique_calls_insight_description,)-def _update_tile_with_new_key(insight, new_key: str, old_key: str, descriptionFunction: Callable[[str], str]) -> None:- old_description = descriptionFunction(old_key)- new_description = descriptionFunction(new_key)+def _update_tile_with_new_key(+ insight,+ feature_flag,+ old_key: str,+ description_fn: Callable[..., str],+) -> None:+ old_description = description_fn(feature_flag, key=old_key)+ new_description = description_fn(feature_flag, key=feature_flag.key)if insight.description != old_description: # We don't touch insights that have been manually editedreturn@@ -1127,15 +1177,16 @@ def _update_tile_with_new_key(insight, new_key: str, old_key: str, descriptionFuproperty_group = property_values[0]values = property_group.get("values", [])- # Only proceed if there's exactly one value and it's a feature flag- if len(values) == 1 and values[0].get("key") == "$feature_flag" and values[0].get("value") == old_key:- values[0]["value"] = new_key- insight.query = insight.query # Trigger field update- # Only update the insight if it matches what we expect for the system created insights- insight.description = new_description- insight.save()+ feature_flag_filter = next((value for value in values if value.get("key") == "$feature_flag"), None)+ if feature_flag_filter is None or feature_flag_filter.get("value") != old_key:return+ feature_flag_filter["value"] = feature_flag.key+ insight.query = insight.query # Trigger field update+ # Only update the insight if it matches what we expect for the system created insights+ insight.description = new_description+ insight.save()+def add_enriched_insights_to_feature_flag_dashboard(feature_flag, dashboard: Dashboard) -> None:# 1 rowdiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 971a69ffda27..bff009ca539f 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -4427,6 +4427,130 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):},)+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")+ def test_create_group_feature_flag_usage_dashboard(self, mock_report_user_action):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "name": "Group feature",+ "key": "group-feature",+ "filters": {+ "aggregation_group_type_index": 0,+ "groups": [+ {+ "rollout_percentage": 50,+ "properties": [+ {+ "key": "industry",+ "value": "finance",+ "type": "group",+ "group_type_index": 0,+ }+ ],+ }+ ],+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ instance = FeatureFlag.objects.get(id=response.json()["id"])++ dashboard = instance.usage_dashboard+ assert dashboard is not None+ assert dashboard.tiles is not None+ tiles = sorted(+ dashboard.tiles.all(),+ key=lambda x: str(x.insight.name if x.insight is not None else ""),+ )+ self.assertEqual(len(tiles), 2)++ group_property_filter = {+ "key": "$group_0",+ "type": "event",+ "value": "is_set",+ "operator": "is_set",+ }+ flag_property_filter = {+ "key": "$feature_flag",+ "type": "event",+ "value": "group-feature",+ "operator": "exact",+ }++ assert tiles[0].insight is not None+ total_volume_query = cast(dict[str, Any], tiles[0].insight.query)+ total_volume_properties = total_volume_query["source"]["properties"]["values"][0]["values"]+ self.assertEqual(total_volume_properties, [flag_property_filter, group_property_filter])++ assert tiles[1].insight is not None+ self.assertEqual(tiles[1].insight.name, "Feature Flag calls made by unique groups per variant")+ self.assertEqual(+ tiles[1].insight.description,+ "Shows the number of unique group calls made on feature flag per variant with key: group-feature",+ )+ unique_calls_query = cast(dict[str, Any], tiles[1].insight.query)+ unique_calls_series = unique_calls_query["source"]["series"][0]+ self.assertEqual(unique_calls_series["math"], "unique_group")+ self.assertEqual(unique_calls_series["math_group_type_index"], 0)+ unique_calls_properties = unique_calls_query["source"]["properties"]["values"][0]["values"]+ self.assertEqual(unique_calls_properties, [flag_property_filter, group_property_filter])++ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")+ def test_update_group_feature_flag_key_updates_usage_dashboard(self, mock_report_user_action):+ create = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "name": "Group feature",+ "key": "group-feature",+ "filters": {+ "aggregation_group_type_index": 0,+ "groups": [{"rollout_percentage": 50}],+ },+ },+ format="json",+ )+ self.assertEqual(create.status_code, status.HTTP_201_CREATED)+ flag_id = create.json()["id"]++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag_id}",+ {+ "key": "renamed-group-feature",+ "filters": {+ "aggregation_group_type_index": 0,+ "groups": [{"rollout_percentage": 50}],+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ dashboard = FeatureFlag.objects.get(id=flag_id).usage_dashboard+ assert dashboard is not None+ assert dashboard.tiles is not None+ tiles = sorted(+ dashboard.tiles.all(),+ key=lambda x: str(x.insight.name if x.insight is not None else ""),+ )++ expected_properties = [+ {"key": "$feature_flag", "type": "event", "value": "renamed-group-feature", "operator": "exact"},+ {"key": "$group_0", "type": "event", "value": "is_set", "operator": "is_set"},+ ]++ assert tiles[0].insight is not None+ total_volume_query = cast(dict[str, Any], tiles[0].insight.query)+ self.assertEqual(total_volume_query["source"]["properties"]["values"][0]["values"], expected_properties)++ assert tiles[1].insight is not None+ unique_calls_query = cast(dict[str, Any], tiles[1].insight.query)+ self.assertEqual(unique_calls_query["source"]["properties"]["values"][0]["values"], expected_properties)+ self.assertEqual(+ tiles[1].insight.description,+ "Shows the number of unique group calls made on feature flag per variant with key: renamed-group-feature",+ )+@freeze_time("2021-08-25T22:09:14.252Z")@patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_dashboard_enrichment_fails_if_already_enriched(self, mock_report_user_action):