: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(customer-analytics): return 400 for invalid usage metric saves (#118570)
posthog[bot]c79c100b0978
diff --git a/posthog/models/group_usage_metric.py b/posthog/models/group_usage_metric.pyindex 8d265401f57a..1366d0b28014 100644--- a/posthog/models/group_usage_metric.py+++ b/posthog/models/group_usage_metric.py@@ -70,3 +70,18 @@ class GroupUsageMetric(UUIDModel, BytecodeModelMixin):from products.cdp.backend.filters import hog_function_filters_to_exprreturn hog_function_filters_to_expr(self.filters, self.team, {})++ def get_cohort_filter_errors(self) -> list[str]:+ """Return why the test account cohorts can't be inlined into the metric's real-time filter."""+ from posthog.hogql.errors import BaseHogQLError++ from products.cdp.backend.filters import CohortInlineError++ try:+ self.get_expr()+ except CohortInlineError as e:+ return e.reasons+ except BaseHogQLError:+ # save() stores these as bytecode_error, so they don't block the save.+ pass+ return []diff --git a/products/groups/backend/presentation/views.py b/products/groups/backend/presentation/views.pyindex f80abb13955a..774f3dfe004f 100644--- a/products/groups/backend/presentation/views.py+++ b/products/groups/backend/presentation/views.py@@ -1037,8 +1037,37 @@ class GroupUsageMetricSerializer(serializers.ModelSerializer, UserAccessControlSelse:raise serializers.ValidationError({"filters": f"Unknown source: {source!r}"})+ if "name" in data:+ self._validate_unique_name(data["name"])+ if source != GroupUsageMetric.Source.DATA_WAREHOUSE and "filters" in data:+ self._validate_cohort_filters(cast(dict, filters))+return data+ def _validate_unique_name(self, name: str) -> None:+ group_type_index = self.instance.group_type_index if self.instance else self.context["group_type_index"]+ existing = GroupUsageMetric.objects.filter(+ team=self.context["get_team"](), group_type_index=group_type_index, name=name+ )+ if self.instance:+ existing = existing.exclude(pk=self.instance.pk)+ if existing.exists():+ raise serializers.ValidationError({"name": f"A usage metric named {name!r} already exists."})++ def _validate_cohort_filters(self, filters: dict) -> None:+ metric = GroupUsageMetric(team=self.context["get_team"](), filters=filters)+ reasons = metric.get_cohort_filter_errors()+ if reasons:+ raise serializers.ValidationError(+ {+ "filters": (+ f"Your internal and test account filters use cohorts that usage metrics can't use: "+ f"{'; '.join(reasons)}. Use a cohort with only person property filters, "+ f"or turn off the internal and test account filter for this metric."+ )+ }+ )+def _validate_events(self, math: str, math_property: str | None) -> None:if math == GroupUsageMetric.Math.SUM and not math_property:raise serializers.ValidationError({"math_property": "math_property is required when math is 'sum'."})diff --git a/products/groups/backend/tests/test_clickhouse_groups.py b/products/groups/backend/tests/test_clickhouse_groups.pyindex a278d7ca65ed..40783dfa82ce 100644--- a/products/groups/backend/tests/test_clickhouse_groups.py+++ b/products/groups/backend/tests/test_clickhouse_groups.py@@ -2208,6 +2208,32 @@ class GroupUsageMetricViewSetTestCase(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["attr"], "filters")+ @parameterized.expand(+ [+ ("duplicate_name_on_create", "post", {"name": "Events", "filters": {}}, 400, "name"),+ ("duplicate_name_on_rename", "patch", {"name": "Events"}, 400, "name"),+ ("own_name_on_update", "patch", {"name": "Signups"}, 200, None),+ (+ "test_account_cohort_filter",+ "post",+ {"name": "Pageviews", "filters": {"filter_test_accounts": True}},+ 400,+ "filters",+ ),+ ]+ )+ def test_save_rejects_invalid_input_with_400(self, _name, method, payload, expected_status, expected_attr):+ self._create_metric(name="Events")+ signups = self._create_metric(name="Signups")+ self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": 999999}]+ self.team.save()+ url = self.url if method == "post" else f"{self.url}/{signups.id}"++ response = getattr(self.client, method)(url, payload, format="json")++ self.assertEqual(response.status_code, expected_status, response.json())+ self.assertEqual(response.json().get("attr"), expected_attr)+def test_create_data_warehouse_metric_accepts_table_with_null_deleted(self):table = self._create_dw_table()table.deleted = None