: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): reject empty variant keys for new variants (#118803)
Phil Haack8007584e65e8
diff --git a/docs/internal/feature-flags/api-writes.md b/docs/internal/feature-flags/api-writes.mdindex e944378327d1..84921dde3722 100644--- a/docs/internal/feature-flags/api-writes.md+++ b/docs/internal/feature-flags/api-writes.md@@ -15,9 +15,11 @@ Every incoming `filters.version`, including numeric 1, still fails with `reserveSupplied top-level v1 filter keys replace those keys in the stored state; `{}` retains targeting and `groups: []` clears it.The existing validation rollout controls normalization and unknown-key preservation.Every write rejects the variant keys `$false` and `$true` with `reserved_variant_key`, whatever the validation rollout enforces.-It also rejects a `"null"` variant key unless the stored flag already has a variant with that key, because `flag_evaluations` stores a `"null"` response the same as a null one.+It also rejects a `"null"` or empty `""` variant key unless the stored flag already has a variant with that key.+`flag_evaluations` stores a `"null"` response the same as a null one, and a `""` response the same as a missing one.+The validation rollout's `structural.multivariate.variants[].key.blank` rule rejects every `""` key, including one the stored flag has, once that rule is enforced.Copies follow the target flag, not the source.-Duplicating an experiment with a new flag key, copying a flag or experiment to a project without that flag, and copying onto a target flag without a `"null"` variant all fail when the source flag has one.+Duplicating an experiment with a new flag key, copying a flag or experiment to a project without that flag, and copying onto a target flag that lacks the source flag's `"null"` or `""` variant all fail.Dependency targets must also use v1 configurations.The dependency validator resolves IDs within the existing project scope, rejects disabled targets, and checks `filters.version` before accepting an edge.diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex f297f3502ac2..fd89685e2612 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -2014,10 +2014,12 @@ class FeatureFlagSerializer(stored_filters = (self.instance.filters or {}) if self.instance is not None else {}reserved_variant_key = _reserved_variant_key(filters, stored=stored_filters)if reserved_variant_key is not None:- raise serializers.ValidationError(- f"The variant key {reserved_variant_key} is reserved. Choose another key.",- code="reserved_variant_key",+ message = (+ "Variant keys can't be empty. Enter a key for each variant."+ if reserved_variant_key == ""+ else f"The variant key {reserved_variant_key} is reserved. Choose another key.")+ raise serializers.ValidationError(message, code="reserved_variant_key")if self._v2_limits is not None:# An admitted v2 document passes through untouched (no v1 merge or normalization): adiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 800058552cb6..a303fc342ae8 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -8569,11 +8569,18 @@ class TestFeatureFlagFiltersEnforcement(APIBaseTest):def test_structural_tier_also_rejects_only_the_enforced_rule(self) -> None:# The structural tier decides separately from the cross-field one, so it needs its own# case. Both violations are on variant keys, which the serde guard only type-checks, so- # they reach the structural tier instead of being rejected before it.- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",+ # they reach the structural tier instead of being rejected before it. Every write rejects+ # a new empty key, so the stored flag holds the blank key that the write keeps.+ flag = self._create_flag_via_orm(+ "mixed-structural-violations",+ {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {"variants": [{"key": "", "rollout_percentage": 100}]},+ },+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",{- "key": "mixed-structural-violations","filters": {"groups": [{"properties": [], "rollout_percentage": 100}],"multivariate": {@@ -8594,22 +8601,22 @@ class TestFeatureFlagFiltersEnforcement(APIBaseTest):@override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES=set())def test_kill_switch_logs_new_rules_but_still_rejects_serde_unsafe_input(self):- # An empty variant key is structurally invalid but still deserializes as a Rust String,- # so log-only mode records it without widening the cache-poisoning surface.+ # A variant key over 400 characters is structurally invalid but still deserializes as a+ # Rust String, so log-only mode records it without widening the cache-poisoning surface.new_rule_only = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",{"key": "bypassed-flag","filters": {"groups": [{"properties": [], "rollout_percentage": None}],- "multivariate": {"variants": [{"key": "", "rollout_percentage": 100}]},+ "multivariate": {"variants": [{"key": "x" * 401, "rollout_percentage": 100}]},},},format="json",)self.assertEqual(new_rule_only.status_code, status.HTTP_201_CREATED, new_rule_only.json())flag = FeatureFlag.objects.get(id=new_rule_only.json()["id"])- self.assertEqual(flag.filters["multivariate"]["variants"][0]["key"], "")+ self.assertEqual(flag.filters["multivariate"]["variants"][0]["key"], "x" * 401)# But the pre-enforcement type/bounds checks stay active: cache-poisoning input is# rejected exactly as before enforcement shipped, switch or no switch.@@ -15300,7 +15307,7 @@ class TestFeatureFlagFiltersMetrics(APIBaseTest):"key": "metrics-bypassed","filters": {"groups": [{"properties": [], "rollout_percentage": 100}],- "multivariate": {"variants": [{"key": "", "rollout_percentage": 100}]},+ "multivariate": {"variants": [{"key": "x" * 401, "rollout_percentage": 100}]},},},format="json",@@ -15440,7 +15447,7 @@ class TestFeatureFlagFiltersMetrics(APIBaseTest):# The dashboard has to see that, or a bare zero reads as "nothing left to fix".not_evaluated_before = self._violation_count("cross_field", "not_evaluated", "create")- # A blank variant key fails the structural tier but not the serde guard, which rejects+ # An overlong variant key fails the structural tier but not the serde guard, which rejects# regardless of the switch. A guard-rejected shape would never reach this branch.response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -15448,7 +15455,7 @@ class TestFeatureFlagFiltersMetrics(APIBaseTest):"key": "metrics-not-evaluated","filters": {"groups": [{"properties": [], "rollout_percentage": 100}],- "multivariate": {"variants": [{"key": "", "rollout_percentage": 100}]},+ "multivariate": {"variants": [{"key": "x" * 401, "rollout_percentage": 100}]},},},format="json",diff --git a/products/feature_flags/backend/reserved_variant_keys.py b/products/feature_flags/backend/reserved_variant_keys.pyindex 7491204658da..e601aba1b602 100644--- a/products/feature_flags/backend/reserved_variant_keys.py+++ b/products/feature_flags/backend/reserved_variant_keys.py@@ -2,8 +2,10 @@The ingest cleaner stores a variant named "false" or "true" under a sentinel in the `$feature_flags` map, so everywrite refuses the sentinels. flag_evaluations stores `$feature_flag_response` with the JSON quotes trimmed, so a variant-named "null" stores the same 'null' as a flag that returned null, and reads turn both into NULL. A flag that already-serves a key in `RESERVED_NEW_VARIANT_KEYS` keeps it, because renaming a variant breaks experiment and chart continuity.+named "null" stores the same 'null' as a flag that returned null, and reads turn both into NULL. A variant with an+empty key stores ''. That is the value flag_evaluations stores for a missing response. HogQL reads '' as NULL on a+materialized events column. A flag that already serves a key in `RESERVED_NEW_VARIANT_KEYS` keeps it, because renaming+a variant breaks experiment and chart continuity."""from collections.abc import Collection@@ -11,8 +13,9 @@ from typing import Anyfrom posthog.hogql.constants import FEATURE_FLAG_VARIANT_SENTINELS-# Mirrored by RESERVED_NEW_VARIANT_KEYS in featureFlagLogic.ts.-RESERVED_NEW_VARIANT_KEYS: frozenset[str] = frozenset({"null"})+# Mirrored by RESERVED_NEW_VARIANT_KEYS in featureFlagLogic.ts. That list leaves out "", because the editor rejects+# every empty variant key before it checks the list.+RESERVED_NEW_VARIANT_KEYS: frozenset[str] = frozenset({"null", ""})def is_reserved_variant_key(value: Any, *, held: Collection[Any]) -> bool:diff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.pyindex 60897cba0a52..79326dc7d96a 100644--- a/products/feature_flags/backend/test/test_filters_validation.py+++ b/products/feature_flags/backend/test/test_filters_validation.py@@ -494,11 +494,11 @@ class TestReservedVariantKey(SimpleTestCase):@parameterized.expand([*(- (f"{key}_{name}", key, enforced_rules, None)- for key in (*FEATURE_FLAG_VARIANT_SENTINELS, "null")+ (f"{key or 'empty'}_{name}", key, enforced_rules, None)+ for key in (*FEATURE_FLAG_VARIANT_SENTINELS, "null", "")for name, enforced_rules in (("log_only", set()), ("full", {"*"}))),- ("null_added_on_update", "null", set(), ["control"]),+ *((f"{key or 'empty'}_added_on_update", key, set(), ["control"]) for key in ("null", "")),*((f"{sentinel}_kept_on_update", sentinel, set(), ["control", sentinel])for sentinel in FEATURE_FLAG_VARIANT_SENTINELS@@ -512,19 +512,21 @@ class TestReservedVariantKey(SimpleTestCase):serializer = _new_variant_serializer(key, stored_keys)assert not serializer.is_valid()assert serializer.errors["filters"][0].code == "reserved_variant_key"- assert key in str(serializer.errors["filters"][0])+ assert (key or "can't be empty") in str(serializer.errors["filters"][0])@parameterized.expand([- ("uppercase_on_create", "NULL", None),- ("title_case_on_create", "Null", None),- ("null_kept_on_update", "null", ["control", "null"]),+ ("uppercase_on_create", "NULL", {"*"}, None),+ ("title_case_on_create", "Null", {"*"}, None),+ ("null_kept_on_update", "null", {"*"}, ["control", "null"]),+ # A structural rule rejects a blank key under full enforcement. This case therefore runs log-only.+ ("empty_kept_on_update", "", set(), ["control", ""]),])def test_unreserved_key_is_accepted_as_a_variant_key(- self, _name: str, key: str, stored_keys: list[str] | None+ self, _name: str, key: str, enforced_rules: set[str], stored_keys: list[str] | None) -> None:- with override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES={"*"}):+ with override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES=enforced_rules):serializer = _new_variant_serializer(key, stored_keys)# is_valid() would go on to the object-level validate(), which reads the team from the database.validated = serializer.validate_filters(serializer.initial_data["filters"])