: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
feat(feature-flags): attribute filters violations to the caller (#98424)
Patricio14a6ffd04068
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 11ca54988659..57a6c24ed873 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -170,8 +170,8 @@ FLAG_FILTERS_WRITE_COUNTER = Counter(FLAG_FILTERS_VIOLATION_COUNTER = Counter("posthog_feature_flag_filters_violation_total",- "Filters validation violations, by tier and rule",- labelnames=["stage", "rule", "operation"],+ "Filters validation violations, by tier, rule and write source",+ labelnames=["stage", "rule", "operation", "source"],)@@ -179,6 +179,10 @@ def _flag_write_source(request: Any) -> str:"""Coarse write-source attribution for metrics. Never returns unbounded values."""if request is None:return "internal"+ # ServiceRequest declares a system write and carries no authenticator, so the checks+ # below would read it as an unidentified caller.+ if getattr(request, "is_system", False):+ return "internal"headers = getattr(request, "headers", None) or {}if headers.get("x-posthog-mcp-user-agent") or "posthog-mcp" in (headers.get("User-Agent") or ""):return "mcp"@@ -199,9 +203,11 @@ def _count_filters_write(operation: str, outcome: str, request: Any) -> None:FLAG_FILTERS_WRITE_COUNTER.labels(operation=operation, outcome=outcome, source=_flag_write_source(request)).inc()-def _count_filters_violations(stage: str, operation: str, rule_ids: Iterable[str | None]) -> None:+def _count_filters_violations(stage: str, operation: str, rule_ids: Iterable[str | None], source: str) -> None:for rule_id in rule_ids:- FLAG_FILTERS_VIOLATION_COUNTER.labels(stage=stage, rule=rule_id or "unknown", operation=operation).inc()+ FLAG_FILTERS_VIOLATION_COUNTER.labels(+ stage=stage, rule=rule_id or "unknown", operation=operation, source=source+ ).inc()def _mark_filters_bypassed(serializer: serializers.Serializer) -> None:@@ -1604,6 +1610,7 @@ class FeatureFlagSerializer(# `filters` arrives as the raw request dict, so the structural tier runs once below,# on the merged state.fully_enforced = _all_filters_rules_are_enforced()+ source = _flag_write_source(self.context.get("request"))# A rule that only logs must never accept what the pre-enforcement validator rejected,# so the cache-poisoning class stays rejected throughout the rollout. Once every rule@@ -1613,7 +1620,7 @@ class FeatureFlagSerializer(try:_reject_serde_unsafe_filters(filters)except serializers.ValidationError:- _count_filters_violations("serde_fidelity", operation, ["serde_fidelity"])+ _count_filters_violations("serde_fidelity", operation, ["serde_fidelity"], source)raise# Updates validate and store the merged final state (#50084): incoming top-level keys@@ -1668,12 +1675,12 @@ class FeatureFlagSerializer(ErrorDetail(f"{violation.path}: {violation.message}", code=violation.rule_id)for violation in flatten_structural_errors(structural.errors)]- _count_filters_violations("merged_structural", operation, [detail.code for detail in details])+ _count_filters_violations("merged_structural", operation, [detail.code for detail in details], source)# Cross-field collectors trust structurally valid input, so they never run for this# write. Record that rather than leaving the stage silent: the flags this rollout is# about are mostly cross-field violators whose merged state fails structurally, so a# bare zero on the cross_field series would read as "none left to fix".- _count_filters_violations("cross_field", operation, ["not_evaluated"])+ _count_filters_violations("cross_field", operation, ["not_evaluated"], source)# Only the enforced rules reject, and only they are reported: a rule still rolling# out must not turn into a 400 by sharing a request with one that is enforced.enforced_details = [detail for detail in details if _filters_rule_is_enforced(detail.code)]@@ -1789,7 +1796,7 @@ class FeatureFlagSerializer(cross_field_violations = collect_cross_field_violations(merged)if cross_field_violations:_count_filters_violations(- "cross_field", operation, [violation.rule_id for violation in cross_field_violations]+ "cross_field", operation, [violation.rule_id for violation in cross_field_violations], source)enforced_violations = [violation for violation in cross_field_violations if _filters_rule_is_enforced(violation.rule_id)diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex c600de95af1b..837668a8b2be 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -33,6 +33,7 @@ from posthog.hogql.database.database import Databasefrom posthog import redisfrom posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_actors_for_feature_flagfrom posthog.api.services.flags_service import FlagVersionConflictError, PropertyMatchingVersionConflictError+from posthog.api.utils import ServiceRequestfrom posthog.constants import AvailableFeaturefrom posthog.models import TaggedItem, Userfrom posthog.models.group.util import create_group, raw_create_group_ch@@ -63,6 +64,7 @@ from products.feature_flags.backend.api.feature_flag import (FLAG_FILTERS_WRITE_COUNTER,FeatureFlagSerializer,FeatureFlagStatusResponseSerializer,+ _flag_write_source,parse_created_by_ids,)from products.feature_flags.backend.encrypted_flag_payloads import (@@ -14652,7 +14654,10 @@ class TestFeatureFlagFiltersMetrics(APIBaseTest):accepted_before = self._write_count("create", "accepted")rejected_before = self._write_count("create", "rejected")violation_before = FLAG_FILTERS_VIOLATION_COUNTER.labels(- stage="merged_structural", rule="structural.groups[].rollout_percentage.max_value", operation="create"+ stage="merged_structural",+ rule="structural.groups[].rollout_percentage.max_value",+ operation="create",+ source="ui",)._value.get()ok = self.client.post(@@ -14673,7 +14678,10 @@ class TestFeatureFlagFiltersMetrics(APIBaseTest):self.assertEqual(self._write_count("create", "rejected"), rejected_before + 1)self.assertEqual(FLAG_FILTERS_VIOLATION_COUNTER.labels(- stage="merged_structural", rule="structural.groups[].rollout_percentage.max_value", operation="create"+ stage="merged_structural",+ rule="structural.groups[].rollout_percentage.max_value",+ operation="create",+ source="ui",)._value.get(),violation_before + 1,)@@ -14699,8 +14707,53 @@ class TestFeatureFlagFiltersMetrics(APIBaseTest):self.assertEqual(self._write_count("create", "bypassed"), bypassed_before + 1)self.assertEqual(self._write_count("create", "accepted"), accepted_before)- def _violation_count(self, stage: str, rule: str, operation: str) -> float:- return FLAG_FILTERS_VIOLATION_COUNTER.labels(stage=stage, rule=rule, operation=operation)._value.get()+ @parameterized.expand(+ [+ ("no request at all", None, "internal"),+ ("facade system write", ServiceRequest(None, is_system=True), "internal"),+ ("facade write for a user", ServiceRequest(object()), "other"),+ ]+ )+ def test_write_source_of_non_http_callers(self, _name: str, request: object, expected: str) -> None:+ self.assertEqual(_flag_write_source(request), expected)++ @override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES=set())+ def test_violations_are_attributed_to_the_caller_that_made_them(self) -> None:+ rule = "cross_field.variant_rollout_sum_not_100"+ ui_before = self._violation_count("cross_field", rule, "create", "ui")+ api_before = self._violation_count("cross_field", rule, "create", "api")+ filters = {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [{"key": "a", "rollout_percentage": 30}, {"key": "b", "rollout_percentage": 30}]+ },+ }++ session_write = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/", {"key": "from-ui", "filters": filters}, format="json"+ )+ self.assertEqual(session_write.status_code, status.HTTP_201_CREATED, session_write.json())++ auth_token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="metrics-source", user=self.user, scopes=["*"], secure_value=hash_key_value(auth_token)+ )+ self.client.logout()+ api_write = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"key": "from-api", "filters": filters},+ format="json",+ headers={"authorization": f"Bearer {auth_token}"},+ )+ self.assertEqual(api_write.status_code, status.HTTP_201_CREATED, api_write.json())++ self.assertEqual(self._violation_count("cross_field", rule, "create", "ui"), ui_before + 1)+ self.assertEqual(self._violation_count("cross_field", rule, "create", "api"), api_before + 1)++ def _violation_count(self, stage: str, rule: str, operation: str, source: str = "ui") -> float:+ return FLAG_FILTERS_VIOLATION_COUNTER.labels(+ stage=stage, rule=rule, operation=operation, source=source+ )._value.get()def _create_flag_via_orm(self, key: str, filters: dict) -> FeatureFlag:return FeatureFlag.objects.create(team=self.team, created_by=self.user, key=key, name=key, filters=filters)