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.

chore(flags): move the usage dashboard builder into a test fixture (#114085)

Phil Haack650a138861a4
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
index 9f135d332e50..a7afdee939bf 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
@@ -1,10 +1,12 @@
// The Usage tab renders these charts inline for flags without a usage dashboard. Event names,
-// property keys, breakdown, and math must stay identical to the saved-dashboard insight definitions
-// in posthog/helpers/dashboard_templates.py (create_feature_flag_dashboard and
-// add_enriched_insights_to_feature_flag_dashboard), so both surfaces report the same numbers.
+// property keys, breakdown, and math must stay identical to the insights on existing usage
+// dashboards, so that both surfaces report the same numbers. The test fixture in
+// products/feature_flags/backend/test/usage_dashboard_fixtures.py reproduces the total volume and
+// unique calls insights. The function add_enriched_insights_to_feature_flag_dashboard in
+// posthog/helpers/dashboard_templates.py adds the enriched insights.
// Titles differ on purpose: update_feature_flag_dashboard looks tiles up by name, so the Python
// names are pinned, while these use sentence case. The interval here follows the user's date range
-// rather than the template's fixed "day".
+// rather than the saved dashboards' fixed "day".
import { dateMapping, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'
import { BREAKDOWN_NULL_DISPLAY } from 'scenes/insights/utils'
diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.py
index 1b601c32c56b..0ecdf47a10c2 100644
--- a/posthog/helpers/dashboard_templates.py
+++ b/posthog/helpers/dashboard_templates.py
@@ -736,12 +736,12 @@ FEATURE_FLAG_ENRICHED_INSIGHT_DESCRIPTION = (
def feature_flag_generated_insight_q() -> Q:
- """Match the insights this module generated for a feature flag usage dashboard.
+ """Match the generated insights on a feature flag usage dashboard.
- A name on its own is not provenance, because a person can type any of these, so each name is
- paired with the description the template writes beside it. That makes this narrower than
- `delete_feature_flag_usage_insights._classifier_q`, which matches a name or a description so a
- cleanup sweep still reaches rows an older template version wrote.
+ A name on its own is not provenance, because a person can type any of these. This query
+ therefore pairs each name with the description that PostHog generated beside it. That makes
+ this narrower than `delete_feature_flag_usage_insights._classifier_q`, which matches a name or a
+ description so a cleanup sweep still reaches rows an older template version wrote.
"""
return Q(
Q(name=FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME)
@@ -778,52 +778,6 @@ def _get_aggregation_entity_labels(feature_flag) -> tuple[str | None, str | None
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:
@@ -831,104 +785,6 @@ def _get_feature_flag_unique_calls_insight_name(feature_flag) -> str:
return f"{FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_PREFIX}{plural}{FEATURE_FLAG_UNIQUE_CALLS_INSIGHT_NAME_SUFFIX}"
-# The feature flag Usage tab renders these same charts inline for flags without a usage dashboard —
-# keep frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts in sync with this template.
-def create_feature_flag_dashboard(feature_flag, dashboard: Dashboard, user) -> None:
- dashboard.filters = {"date_from": "-30d"}
- tag, _ = Tag.objects.get_or_create(
- name="feature flags",
- team_id=dashboard.team_id,
- defaults={"team_id": dashboard.team_id},
- )
- dashboard.tagged_items.create(tag_id=tag.id)
- dashboard.save(update_fields=["filters"])
-
- # 1 row
- _create_tile_for_insight(
- dashboard,
- name=FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME,
- description=_get_feature_flag_total_volume_insight_description(feature_flag),
- query={
- "kind": "InsightVizNode",
- "source": {
- "breakdownFilter": {"breakdown": "$feature_flag_response", "breakdown_type": "event"},
- "dateRange": {"date_from": "-30d", "explicitDate": False},
- "filterTestAccounts": False,
- "interval": "day",
- "kind": "TrendsQuery",
- "properties": _build_feature_flag_called_property_group(feature_flag),
- "series": [{"event": "$feature_flag_called", "kind": "EventsNode", "name": "$feature_flag_called"}],
- "trendsFilter": {
- "aggregationAxisFormat": "numeric",
- "display": "ActionsLineGraph",
- "showAlertThresholdLines": False,
- "showLegend": False,
- "showPercentStackView": False,
- "showValuesOnSeries": False,
- "smoothingIntervals": 1,
- "yAxisScaleType": "linear",
- },
- },
- },
- layouts={
- "sm": {"i": "21", "x": 0, "y": 0, "w": 6, "h": 5, "minW": 3, "minH": 5},
- "xs": {
- "w": 1,
- "h": 5,
- "x": 0,
- "y": 0,
- "i": "21",
- "minW": 1,
- "minH": 5,
- },
- },
- color="blue",
- user=user,
- )
-
- _create_tile_for_insight(
- dashboard,
- name=_get_feature_flag_unique_calls_insight_name(feature_flag),
- description=_get_feature_flag_unique_calls_insight_description(feature_flag),
- query={
- "kind": "InsightVizNode",
- "source": {
- "breakdownFilter": {"breakdown": "$feature_flag_response", "breakdown_type": "event"},
- "dateRange": {"date_from": "-30d", "explicitDate": False},
- "filterTestAccounts": False,
- "interval": "day",
- "kind": "TrendsQuery",
- "properties": _build_feature_flag_called_property_group(feature_flag),
- "series": [_get_feature_flag_unique_calls_series(feature_flag)],
- "trendsFilter": {
- "aggregationAxisFormat": "numeric",
- "display": "ActionsTable",
- "showAlertThresholdLines": False,
- "showLegend": False,
- "showPercentStackView": False,
- "showValuesOnSeries": False,
- "smoothingIntervals": 1,
- "yAxisScaleType": "linear",
- },
- },
- },
- layouts={
- "sm": {"i": "22", "x": 6, "y": 0, "w": 6, "h": 5, "minW": 3, "minH": 5},
- "xs": {
- "w": 1,
- "h": 5,
- "x": 0,
- "y": 5,
- "i": "22",
- "minW": 1,
- "minH": 5,
- },
- },
- color="green",
- user=user,
- )
-
-
def create_group_type_mapping_detail_dashboard(group_type_mapping, user) -> Dashboard:
singular = group_type_mapping.name_singular or group_type_mapping.group_type
plural = group_type_mapping.name_plural or group_type_mapping.group_type + "s"
diff --git a/posthog/test/test_feature_flag_analytics.py b/posthog/test/test_feature_flag_analytics.py
index 8d1bf2318665..fdddd563b427 100644
--- a/posthog/test/test_feature_flag_analytics.py
+++ b/posthog/test/test_feature_flag_analytics.py
@@ -31,7 +31,6 @@ from posthog.helpers.dashboard_templates import (
from posthog.models.team.team import Team
from posthog.tasks.tasks import find_flags_with_enriched_analytics as find_flags_with_enriched_analytics_task
-from products.feature_flags.backend.api.feature_flag import _create_usage_dashboard
from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.flag_analytics import (
SDK_LIBRARIES,
@@ -48,6 +47,7 @@ from products.feature_flags.backend.flag_analytics import (
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
+from products.feature_flags.backend.test.usage_dashboard_fixtures import create_usage_dashboard
class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
@@ -945,8 +945,8 @@ class TestEnrichedAnalytics(BaseTest):
)
# create usage dashboard for f1 and f3
- _create_usage_dashboard(f1, self.user)
- _create_usage_dashboard(f3, self.user)
+ create_usage_dashboard(f1, self.user)
+ create_usage_dashboard(f3, self.user)
# create some enriched analytics events
_create_event(
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index fff9c5cfe466..a9a97b38020d 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -3036,26 +3036,6 @@ USAGE_DASHBOARD_NAME_PREFIX = "Generated Dashboard: "
USAGE_DASHBOARD_DESCRIPTION_PREFIX = "This dashboard was generated by the feature flag with key ("
-def _create_usage_dashboard(feature_flag: FeatureFlag, user):
- from posthog.helpers.dashboard_templates import create_feature_flag_dashboard
-
- from products.dashboards.backend.models.dashboard import Dashboard
-
- usage_dashboard = Dashboard.objects.create(
- name=USAGE_DASHBOARD_NAME_PREFIX + feature_flag.key + " Usage",
- description=USAGE_DASHBOARD_DESCRIPTION_PREFIX + feature_flag.key + ")",
- team=feature_flag.team,
- created_by=user,
- creation_mode="template",
- )
- create_feature_flag_dashboard(feature_flag, usage_dashboard, user)
-
- feature_flag.usage_dashboard = usage_dashboard
- feature_flag.save()
-
- return usage_dashboard
-
-
def _update_feature_flag_dashboard(feature_flag: FeatureFlag, old_key: str) -> None:
from posthog.helpers.dashboard_templates import update_feature_flag_dashboard
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 e1d5509e0bf7..fb5a3a4f84b6 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -69,7 +69,6 @@ from products.feature_flags.backend.api.feature_flag import (
FLAG_FILTERS_WRITE_COUNTER,
FeatureFlagSerializer,
FeatureFlagStatusResponseSerializer,
- _create_usage_dashboard,
_flag_write_source,
parse_created_by_ids,
)
@@ -84,6 +83,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag, Feat
from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig
from products.feature_flags.backend.realtime_targeting import REALTIME_COHORT_FLAG_TARGETING_FLAG
from products.feature_flags.backend.test.replay_gate_fixtures import set_linked_flag, set_trigger_groups, trigger_groups
+from products.feature_flags.backend.test.usage_dashboard_fixtures import create_usage_dashboard
from products.feature_flags.backend.user_blast_radius import get_user_blast_radius, get_user_blast_radius_persons
from products.product_analytics.backend.facade.models import Insight
from products.product_tours.backend.models import ProductTour
@@ -133,7 +133,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
return query["source"]["properties"]["values"][0]["values"][0]["value"]
def _generate_usage_dashboard(self, flag_id: int) -> None:
- _create_usage_dashboard(FeatureFlag.objects.get(id=flag_id), self.user)
+ create_usage_dashboard(FeatureFlag.objects.get(id=flag_id), self.user)
def test_cant_create_flag_with_duplicate_key(self):
FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
diff --git a/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py b/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py
index 79149d7a6473..a4613a00ce2f 100644
--- a/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py
+++ b/products/feature_flags/backend/management/commands/delete_feature_flag_usage_insights.py
@@ -47,7 +47,7 @@ def _classifier_q() -> Q:
Keys on name and description, not on `is_sample`: every dashboard template sets that, so on its
own it would also match billing/usage and onboarding insights. Callers wanting a second signal
add it on top of this (see `_delete_orphaned`).
- Names come from constants in posthog/helpers/dashboard_templates.py, which is what creates them.
+ Names come from constants in posthog/helpers/dashboard_templates.py.
Descriptions interpolate the flag key, so those are matched by fragment instead.
"""
return (
diff --git a/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py b/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py
index 2950dc3b8ff2..b7578185ea04 100644
--- a/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py
+++ b/products/feature_flags/backend/management/commands/test/test_delete_feature_flag_usage_insights.py
@@ -24,8 +24,8 @@ from posthog.test.persons import create_group_type_mapping
from products.alerts.backend.models.alert import AlertConfiguration
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
-from products.feature_flags.backend.api.feature_flag import _create_usage_dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.test.usage_dashboard_fixtures import create_usage_dashboard
from products.product_analytics.backend.facade.models import Insight
from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription
@@ -51,8 +51,7 @@ class TestDeleteFeatureFlagUsageInsights(BaseTest):
# `FeatureFlag.aggregation_group_type_index` reads through to filters.
filters["aggregation_group_type_index"] = aggregation_group_type_index
flag = FeatureFlag.objects.create(team=team, created_by=self.user, key=key, filters=filters)
- # Built through the API's own helper so the dashboard is shaped the way production shapes it.
- dashboard = _create_usage_dashboard(flag, self.user)
+ dashboard = create_usage_dashboard(flag, self.user)
if enriched:
add_enriched_insights_to_feature_flag_dashboard(flag, dashboard)
return flag
diff --git a/products/feature_flags/backend/test/usage_dashboard_fixtures.py b/products/feature_flags/backend/test/usage_dashboard_fixtures.py
new file mode 100644
index 000000000000..63f6030b6a15
--- /dev/null
+++ b/products/feature_flags/backend/test/usage_dashboard_fixtures.py
@@ -0,0 +1,177 @@
+"""Builder for the usage dashboard that older feature flags carry.
+
+No production code creates these dashboards. Teams still have them. The flag rename path, the usage
+insights cleanup command, and the enriched analytics job act on them. Their tests build one with
+this module.
+
+The names, descriptions, and queries below reproduce the dashboards that teams already have. Do not
+change them to follow the Usage tab's inline charts in featureFlagUsageQueries.ts, because the
+existing dashboards do not change with that file.
+"""
+
+from typing import Any
+
+from posthog.helpers.dashboard_templates import (
+ FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME,
+ _create_tile_for_insight,
+ _get_feature_flag_total_volume_insight_description,
+ _get_feature_flag_unique_calls_insight_description,
+ _get_feature_flag_unique_calls_insight_name,
+)
+from posthog.models.tag import Tag
+from posthog.models.user import User
+
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.feature_flags.backend.api.feature_flag import (
+ USAGE_DASHBOARD_DESCRIPTION_PREFIX,
+ USAGE_DASHBOARD_NAME_PREFIX,
+)
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+def _build_feature_flag_called_property_group(feature_flag: FeatureFlag) -> 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: FeatureFlag) -> 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 create_usage_dashboard(feature_flag: FeatureFlag, user: User) -> Dashboard:
+ dashboard = Dashboard.objects.create(
+ name=USAGE_DASHBOARD_NAME_PREFIX + feature_flag.key + " Usage",
+ description=USAGE_DASHBOARD_DESCRIPTION_PREFIX + feature_flag.key + ")",
+ team=feature_flag.team,
+ created_by=user,
+ creation_mode="template",
+ filters={"date_from": "-30d"},
+ )
+ tag, _ = Tag.objects.get_or_create(name="feature flags", team_id=dashboard.team_id)
+ dashboard.tagged_items.create(tag_id=tag.id)
+
+ _create_tile_for_insight(
+ dashboard,
+ name=FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME,
+ description=_get_feature_flag_total_volume_insight_description(feature_flag),
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "breakdownFilter": {"breakdown": "$feature_flag_response", "breakdown_type": "event"},
+ "dateRange": {"date_from": "-30d", "explicitDate": False},
+ "filterTestAccounts": False,
+ "interval": "day",
+ "kind": "TrendsQuery",
+ "properties": _build_feature_flag_called_property_group(feature_flag),
+ "series": [{"event": "$feature_flag_called", "kind": "EventsNode", "name": "$feature_flag_called"}],
+ "trendsFilter": {
+ "aggregationAxisFormat": "numeric",
+ "display": "ActionsLineGraph",
+ "showAlertThresholdLines": False,
+ "showLegend": False,
+ "showPercentStackView": False,
+ "showValuesOnSeries": False,
+ "smoothingIntervals": 1,
+ "yAxisScaleType": "linear",
+ },
+ },
+ },
+ layouts={
+ "sm": {"i": "21", "x": 0, "y": 0, "w": 6, "h": 5, "minW": 3, "minH": 5},
+ "xs": {
+ "w": 1,
+ "h": 5,
+ "x": 0,
+ "y": 0,
+ "i": "21",
+ "minW": 1,
+ "minH": 5,
+ },
+ },
+ color="blue",
+ user=user,
+ )
+
+ _create_tile_for_insight(
+ dashboard,
+ name=_get_feature_flag_unique_calls_insight_name(feature_flag),
+ description=_get_feature_flag_unique_calls_insight_description(feature_flag),
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "breakdownFilter": {"breakdown": "$feature_flag_response", "breakdown_type": "event"},
+ "dateRange": {"date_from": "-30d", "explicitDate": False},
+ "filterTestAccounts": False,
+ "interval": "day",
+ "kind": "TrendsQuery",
+ "properties": _build_feature_flag_called_property_group(feature_flag),
+ "series": [_get_feature_flag_unique_calls_series(feature_flag)],
+ "trendsFilter": {
+ "aggregationAxisFormat": "numeric",
+ "display": "ActionsTable",
+ "showAlertThresholdLines": False,
+ "showLegend": False,
+ "showPercentStackView": False,
+ "showValuesOnSeries": False,
+ "smoothingIntervals": 1,
+ "yAxisScaleType": "linear",
+ },
+ },
+ },
+ layouts={
+ "sm": {"i": "22", "x": 6, "y": 0, "w": 6, "h": 5, "minW": 3, "minH": 5},
+ "xs": {
+ "w": 1,
+ "h": 5,
+ "x": 0,
+ "y": 5,
+ "i": "22",
+ "minW": 1,
+ "minH": 5,
+ },
+ },
+ color="green",
+ user=user,
+ )
+
+ feature_flag.usage_dashboard = dashboard
+ feature_flag.save()
+
+ return dashboard