: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): reserve null as a variant key for new variants (#118224)
Phil Haack54d1a044d7a4
diff --git a/docs/internal/feature-flags/api-writes.md b/docs/internal/feature-flags/api-writes.mdindex c0af382ff5d3..e944378327d1 100644--- a/docs/internal/feature-flags/api-writes.md+++ b/docs/internal/feature-flags/api-writes.md@@ -14,6 +14,10 @@ Other stored formats fail with `unsupported_config_version` before v1 normalizatEvery incoming `filters.version`, including numeric 1, still fails with `reserved_config_version`, except a version 2 document sent to a project the writer policy admits.Supplied 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.+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.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.@@ -77,8 +81,8 @@ A stored version 2 row that is not remote-configured and carries no encrypted pa- A new row is created disabled with server-owned rule IDs and seeds; the request document is resolved against an empty stored document and validated strictly before it is persisted exactly. No v1 row is converted.- A supplied `filters` object replaces the whole configuration. There is no top-level merge, no rule merge by index, no filling of omitted fields from the stored document, and no v1 normalization. `{}`, `null`, a list, and an incomplete object are invalid; a complete document with `rules: []` is valid.-- `return_type` is `boolean`, `string`, `number` or `object` and cannot change after creation. `default_value` is null or the declared type; every rule `value` is the declared type. Strings are non-empty and not `$false` or `$true`, the event-storage sentinels that v1 also reserves as variant keys; numbers lie within ±(2^53 − 1); objects nest at most 20 object or array levels with numbers in the same range.-- Writer-only rules (`check_writer_rules` in `facade/config_writes.py`, currently the `$false` and `$true` reservation and the regex check below) apply to a created or replacing document and to the stored document being enabled. The shared validator, and with it the flags caches and the stored side of an update, does not apply them: tightening a writer rule never hides a stored row from evaluation or blocks replacing it.+- `return_type` is `boolean`, `string`, `number` or `object` and cannot change after creation. `default_value` is null or the declared type; every rule `value` is the declared type. Strings are non-empty and not `$false`, `$true` or `"null"`, the values v1 also reserves as variant keys; numbers lie within ±(2^53 − 1); objects nest at most 20 object or array levels with numbers in the same range.+- Writer-only rules (`check_writer_rules` in `facade/config_writes.py`, currently the `$false`, `$true` and `"null"` reservation and the regex check below) apply to a created or replacing document and to the stored document being enabled. The shared validator, and with it the flags caches and the stored side of an update, does not apply them: tightening a writer rule never hides a stored row from evaluation or blocks replacing it. A `"null"` value the stored document already serves passes the reservation, as in v1.- `regex` and `not_regex` patterns must compile with Python's `re`, as on the v1 write path. This is a writer-only rule: readers store an uncompilable pattern and report an evaluation error when evaluation reaches it. The flags service compiles with `fancy_regex`, whose dialect differs at the edges, so, as in v1, a pattern the stored document already holds is not checked again, and enabling checks no pattern.- Rule IDs and percentage-rollout seeds are server-owned and identify rules rather than list positions. An echoed ID keeps its seed through reordering and unrelated edits; a rule that omits its ID is new and receives fresh identity. An unknown ID, an ID used twice, a client-chosen seed, and a changed seed are all rejected.- `FeatureFlag.version` is required on every update and must equal the locked row's value. Unlike v1 there is no `original_flag` merge: a stale token is a conflict even when no individual field clashes. The token applies to disabling and deleting too.diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsxindex 59eca961a232..48e4318c9be1 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx@@ -442,6 +442,7 @@ export default function FeatureFlagSchedule(): JSX.Element {scheduleTimelineOccurrences,scheduleFormState,scheduleFormCollapsible,+ savedVariantKeys,} = useValues(featureFlagLogic)// The Schedule tab is not offered for another config version (availableTabs), so the document is v1.const featureFlag = loadedFeatureFlag as FeatureFlagWithV1Config@@ -527,7 +528,7 @@ export default function FeatureFlagSchedule(): JSX.Element {)const variantErrors = displayVariants.map(({ key: variantKey }) => ({- key: validateFeatureFlagVariantKey(variantKey),+ key: validateFeatureFlagVariantKey(variantKey, savedVariantKeys),}))// A bad sum is rejected when the change fires. Other operations leave variants untouched.diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex b8bcfd1acd10..c4aa69291d24 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -4097,8 +4097,11 @@ describe('validateFeatureFlagVariantKey', () => {{ key: 'provider/model-1.2', desc: 'slashes and dots (model-id style)' },{ key: '0.85', desc: 'dotted number' },{ key: 'a/b/c.d_e-f', desc: 'mixed dots, slashes, hyphens, underscores' },- ])('accepts valid variant key: $desc', ({ key }) => {- expect(validateFeatureFlagVariantKey(key)).toBeUndefined()+ { key: 'NULL', desc: 'uppercase NULL' },+ { key: 'Null', desc: 'title-case Null' },+ { key: 'null', savedKeys: ['control', 'null'], desc: 'null the saved flag already has' },+ ])('accepts valid variant key: $desc', ({ key, savedKeys }) => {+ expect(validateFeatureFlagVariantKey(key, savedKeys)).toBeUndefined()})it.each([@@ -4107,8 +4110,10 @@ describe('validateFeatureFlagVariantKey', () => {{ key: 'foo?bar', error: 'Only letters', desc: 'question marks' },{ key: '', error: 'Please set a key', desc: 'empty key' },{ key: 'a'.repeat(401), error: '400 characters', desc: 'over 400 characters' },- ])('rejects variant key with $desc', ({ key, error }) => {- expect(validateFeatureFlagVariantKey(key)).toContain(error)+ { key: 'null', error: 'reserved', desc: 'null on a new flag' },+ { key: 'null', savedKeys: ['control', 'test'], error: 'reserved', desc: 'null the saved flag lacks' },+ ])('rejects variant key with $desc', ({ key, savedKeys, error }) => {+ expect(validateFeatureFlagVariantKey(key, savedKeys)).toContain(error)})})diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 26480c6e05ac..53669149ebf9 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -510,17 +510,23 @@ export function validateFeatureFlagKey(key: string): string | undefined {: undefined}+// Mirrors RESERVED_NEW_VARIANT_KEYS in products/feature_flags/backend/reserved_variant_keys.py.+const RESERVED_NEW_VARIANT_KEYS: readonly string[] = ['null']+/** Check whether a string is a valid variant key. If not, a reason string is returned - otherwise undefined.* Wider than flag keys: dots and slashes are allowed because variant keys often carry values SDKs consume- * directly (e.g. model IDs like "provider/model-1.2"), and the API has always accepted them. */-export function validateFeatureFlagVariantKey(key: string): string | undefined {+ * directly (e.g. model IDs like "provider/model-1.2"), and the API has always accepted them.+ * `savedKeys` are the saved flag's variant keys. A reserved key passes when the saved flag already has it. */+export function validateFeatureFlagVariantKey(key: string, savedKeys: readonly string[] = []): string | undefined {return !key? 'Please set a key': key.length > 400? 'Key must be 400 characters or less.': !key.match?.(/^[a-zA-Z0-9_\-./]+$/)? 'Only letters, numbers, hyphens (-), underscores (_), dots (.) & slashes (/) are allowed.'- : undefined+ : RESERVED_NEW_VARIANT_KEYS.includes(key) && !savedKeys.includes(key)+ ? `The key "${key}" is reserved. Choose another key.`+ : undefined}function getVariantRolloutSum(variants: MultivariateFlagVariant[] = []): number {@@ -1144,6 +1150,7 @@ export interface featureFlagLogicValues {version?: number}rulesV2DraftDirty: boolean+ savedVariantKeys: string[]scheduleDateMarker: anyscheduleDefaultsAppliedFromFlag: booleanscheduleFormCollapsible: boolean@@ -2260,7 +2267,8 @@ export interface featureFlagLogicMeta {showStaleFlagBanner: (featureFlag: FeatureFlagType, flagStatus: FeatureFlagStatusResponseApi | null) => booleanisDraftExperiment: (experiment: any) => booleanproperties: (featureFlag: FeatureFlagType) => AnyPropertyFilter[]- variantErrors: (variants: MultivariateFlagVariant[]) => VariantError[]+ savedVariantKeys: (originalFeatureFlag: FeatureFlagType | null) => string[]+ variantErrors: (variants: MultivariateFlagVariant[], savedVariantKeys: string[]) => VariantError[]repeatsValue: (isRecurring: boolean,cronExpression: string | null,@@ -2465,7 +2473,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([multivariate: {variants: filters?.multivariate?.variants?.map(({ key: variantKey }: MultivariateFlagVariant) => ({- key: validateFeatureFlagVariantKey(variantKey),+ key: validateFeatureFlagVariantKey(variantKey, values.savedVariantKeys),// One string on the array key (the usual form) can't say which// panels to expand, so the set-level error fans out per index.rollout_percentage: rolloutSumError,@@ -5272,11 +5280,18 @@ export const featureFlagLogic = kea<featureFlagLogicType>([return featureFlag?.filters?.groups?.flatMap((g) => g.properties ?? []) ?? []},],+ savedVariantKeys: [+ (s) => [s.originalFeatureFlag],+ (originalFeatureFlag: FeatureFlagType | null): string[] =>+ originalFeatureFlag?.id+ ? (originalFeatureFlag.filters.multivariate?.variants ?? []).map(({ key }) => key)+ : [],+ ],variantErrors: [- (s) => [s.variants],- (variants: MultivariateFlagVariant[]) => {+ (s) => [s.variants, s.savedVariantKeys],+ (variants: MultivariateFlagVariant[], savedVariantKeys: string[]) => {const errors: VariantError[] = variants.map(({ key: variantKey }: MultivariateFlagVariant) => ({- key: validateFeatureFlagVariantKey(variantKey),+ key: validateFeatureFlagVariantKey(variantKey, savedVariantKeys),}))return errors},diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex f59da1de0626..f297f3502ac2 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -39,8 +39,6 @@ from rest_framework.settings import api_settingsfrom posthog.schema import ProductKey-from posthog.hogql.constants import FEATURE_FLAG_VARIANT_SENTINELS-from posthog.api.cohort import CohortSerializerfrom posthog.api.documentation import FeatureFlagFiltersSchemaSerializer, extend_schemafrom posthog.api.forbid_destroy_model import ForbidDestroyModel@@ -154,6 +152,7 @@ from products.feature_flags.backend.models.evaluation_context import normalize_cfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboardsfrom products.feature_flags.backend.models.team_feature_flag_policy_config import team_requires_flag_tagsfrom products.feature_flags.backend.realtime_targeting import is_realtime_cohort_flag_targeting_enabled+from products.feature_flags.backend.reserved_variant_keys import is_reserved_variant_keyfrom products.feature_flags.backend.session_recording_links import (REPLAY_GATE_DELETE_ERROR,ReplayFlagGates,@@ -933,29 +932,26 @@ class EvaluationContextSerializerMixin(serializers.Serializer):_RUST_PROPERTY_TYPES: frozenset[str] = frozenset({*FEATURE_FLAG_PROPERTY_TYPES, "person_metadata"})-def _reserved_variant_key(filters: dict) -> str | None:- """The first `multivariate.variants[].key` that is a sentinel the ingest cleaner stores a variant named "false" or- "true" under, if any.-- Checked on the raw request shape ahead of every validation tier, so the rejection does not depend on the #50084- rollout switch.- """+def _variant_keys(filters: Mapping[str, Any]) -> Iterator[str]:multivariate = filters.get("multivariate")if not isinstance(multivariate, dict):- return None+ returnvariants = multivariate.get("variants")if not isinstance(variants, list):- return None- return next(- (- variant["key"]- for variant in variants- if isinstance(variant, dict)- and isinstance(variant.get("key"), str)- and variant["key"] in FEATURE_FLAG_VARIANT_SENTINELS- ),- None,- )+ return+ for variant in variants:+ if isinstance(variant, dict) and isinstance(variant.get("key"), str):+ yield variant["key"]+++def _reserved_variant_key(filters: dict, *, stored: Mapping[str, Any]) -> str | None:+ """The first `multivariate.variants[].key` in `filters` that a write may not store over `stored`, if any.++ Checked on the raw request shape ahead of every validation tier, so the rejection does not depend on the #50084+ rollout switch.+ """+ held = set(_variant_keys(stored))+ return next((key for key in _variant_keys(filters) if is_reserved_variant_key(key, held=held)), None)def _filters_rule_is_enforced(rule_id: str | None) -> bool:@@ -2015,7 +2011,8 @@ class FeatureFlagSerializer(raise self._v2_validation_error(exc) from excdef _validate_filters_inner(self, filters, operation: str):- reserved_variant_key = _reserved_variant_key(filters)+ 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.",diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.pyindex b970577134e0..3882ce3686e8 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py@@ -732,26 +732,18 @@ def string_config(value: str, default: str | None, rule_id: str | None = RULE_A)return config(targeted(rule_id=rule_id, value=value), return_type="string", default_value=default)+RULE_VALUE_DETAIL = 'Must be a non-empty string other than $false, $true or "null".'+DEFAULT_VALUE_DETAIL = 'Must be null or a non-empty string other than $false, $true or "null".'RESERVED_STRING_VALUES = [- (- "rule_value",- "$false",- None,- "filters__rules__0__value",- "Must be a non-empty string other than $false or $true.",- ),- (- "default_value",- "compact",- "$true",- "filters__default_value",- "Must be a non-empty string other than $false or $true, or null.",- ),+ ("rule_value", "$false", None, "filters__rules__0__value", RULE_VALUE_DETAIL),+ ("default_value", "compact", "$true", "filters__default_value", DEFAULT_VALUE_DETAIL),+ ("null_rule_value", "null", None, "filters__rules__0__value", RULE_VALUE_DETAIL),+ ("null_default_value", "compact", "null", "filters__default_value", DEFAULT_VALUE_DETAIL),]class TestWriterOnlyRules(AdmittedV2TestCase):- """The writer reserves `$false` and `$true` as string values; the caches accept them, so a stored one stays replaceable."""+ """The writer reserves `$false`, `$true` and `"null"` as string values. The caches accept them, so a stored one stays replaceable."""@parameterized.expand(RESERVED_STRING_VALUES)def test_create_rejects_a_reserved_value(@@ -793,6 +785,21 @@ class TestWriterOnlyRules(AdmittedV2TestCase):flag.refresh_from_db()assert (flag.filters, flag.version) == (string_config("compact", None), 4)+ def test_an_update_keeps_a_null_value_the_row_already_holds(self) -> None:+ flag = self.flag(string_config("null", "null"))+ replacement = config(targeted(value="null", description="Reviewed"), return_type="string", default_value="null")+ response = self.patch_flag(flag, {"version": 3, "filters": replacement})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert (flag.filters, flag.version) == (replacement, 4)++ def test_a_stored_null_value_can_be_enabled(self) -> None:+ flag = self.flag(string_config("null", "null"), active=False)+ response = self.patch_flag(flag, {"version": 3, "active": True})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert (flag.active, flag.version) == (True, 4)+def test_a_stored_reserved_value_can_be_disabled(self) -> None:flag = self.flag(string_config("$false", None), active=True)response = self.patch_flag(flag, {"version": 3, "active": False})diff --git a/products/feature_flags/backend/facade/config_writes.py b/products/feature_flags/backend/facade/config_writes.pyindex 718ff49086fc..bab43e656df3 100644--- a/products/feature_flags/backend/facade/config_writes.py+++ b/products/feature_flags/backend/facade/config_writes.py@@ -32,8 +32,6 @@ from django.conf import settingsimport structlog-from posthog.hogql.constants import FEATURE_FLAG_VARIANT_SENTINELS-from posthog.dataclasses import frozenfrom posthog.ph_client import feature_enabled_or_false@@ -46,6 +44,7 @@ from products.feature_flags.backend.facade.config_validation import ()from products.feature_flags.backend.facade.rule_warnings import review_configfrom products.feature_flags.backend.facade.warnings import ManagementWarning+from products.feature_flags.backend.reserved_variant_keys import is_reserved_variant_keylogger = structlog.get_logger(__name__)@@ -55,6 +54,8 @@ _SEEDED_RULE_TYPE = "percentage_rollout"V2_WRITES_FLAG = "feature-flag-rules-v2-writes"V2_CREATION_FLAG = "feature-flag-rules-v2-creation"+_RESERVED_STRING_VALUES_TEXT = '$false, $true or "null"'+def _flag_enabled(key: str, team_id: int) -> bool:# Local evaluation only, so a write never waits on a remote call; an unresolved flag reads as closed.@@ -277,16 +278,17 @@ def check_writer_rules(document: Mapping[str, Any], *, stored: Mapping[str, Any]raise ConfigValidationError(errors)-def _reserved_string_values(document: Mapping[str, Any], _stored: Mapping[str, Any]) -> Iterator[ConfigError]:- # A string value is served as the variant, and the event-storage sentinels are the keys v1 reserves as variant keys.+def _reserved_string_values(document: Mapping[str, Any], stored: Mapping[str, Any]) -> Iterator[ConfigError]:+ # The flag serves a string value as its variant, so this rule reserves the keys v1 reserves as variant keys.if document["return_type"] != "string":return- detail = f"Must be a non-empty string other than {' or '.join(FEATURE_FLAG_VARIANT_SENTINELS)}"- if document["default_value"] in FEATURE_FLAG_VARIANT_SENTINELS:- yield ConfigError(code="invalid", detail=f"{detail}, or null.", attr="filters.default_value")+ held = {stored["default_value"], *(rule.get("value") for rule in stored["rules"])} if stored else set()+ detail = f"a non-empty string other than {_RESERVED_STRING_VALUES_TEXT}"+ if is_reserved_variant_key(document["default_value"], held=held):+ yield ConfigError(code="invalid", detail=f"Must be null or {detail}.", attr="filters.default_value")for index, rule in enumerate(document["rules"]):- if rule.get("value") in FEATURE_FLAG_VARIANT_SENTINELS:- yield ConfigError(code="invalid", detail=f"{detail}.", attr=f"filters.rules[{index}].value")+ if is_reserved_variant_key(rule.get("value"), held=held):+ yield ConfigError(code="invalid", detail=f"Must be {detail}.", attr=f"filters.rules[{index}].value")def _compilable_patterns(document: Mapping[str, Any], stored: Mapping[str, Any]) -> Iterator[ConfigError]:diff --git a/products/feature_flags/backend/reserved_variant_keys.py b/products/feature_flags/backend/reserved_variant_keys.pynew file mode 100644index 000000000000..7491204658da--- /dev/null+++ b/products/feature_flags/backend/reserved_variant_keys.py@@ -0,0 +1,20 @@+"""Shared rule for the variant keys a flag write may not store, on the v1 and v2 write paths.++The ingest cleaner stores a variant named "false" or "true" under a sentinel in the `$feature_flags` map, so every+write 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.+"""++from collections.abc import Collection+from typing import Any++from 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"})+++def is_reserved_variant_key(value: Any, *, held: Collection[Any]) -> bool:+ """Whether a write may not store ``value`` as a variant, given the variants the stored flag ``held``."""+ return value in FEATURE_FLAG_VARIANT_SENTINELS or (value in RESERVED_NEW_VARIANT_KEYS and value not in held)diff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.pyindex 9880d7a64eac..bbb577e8b473 100644--- a/products/feature_flags/backend/test/test_filters_validation.py+++ b/products/feature_flags/backend/test/test_filters_validation.py@@ -1,3 +1,4 @@+from types import SimpleNamespacefrom typing import Anyfrom django.test import SimpleTestCase, override_settings@@ -21,6 +22,7 @@ from products.feature_flags.backend.filters_validation import (collect_filters_violations,flatten_structural_errors,)+from products.feature_flags.backend.models import FeatureFlagdef _multivariate(*variants: tuple[str, float]) -> dict[str, Any]:@@ -473,29 +475,60 @@ class TestRejectSerdeUnsafeFilters(SimpleTestCase):_reject_serde_unsafe_filters(filters)+def _variant_filters(*keys: str) -> dict[str, Any]:+ return {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": _multivariate(*((key, 100 / len(keys)) for key in keys)),+ }+++def _new_variant_serializer(key: str, stored_keys: list[str] | None) -> FeatureFlagSerializer:+ instance = FeatureFlag(filters=_variant_filters(*stored_keys)) if stored_keys is not None else None+ request = SimpleNamespace(method="POST" if instance is None else "PATCH")+ return FeatureFlagSerializer(+ instance, data={"filters": _variant_filters("control", key)}, partial=True, context={"request": request}+ )++class TestReservedVariantKey(SimpleTestCase):@parameterized.expand([- (f"{sentinel}_{name}", sentinel, enforced_rules)- for sentinel in FEATURE_FLAG_VARIANT_SENTINELS- for name, enforced_rules in (("log_only", set()), ("full", {"*"}))+ *(+ (f"{key}_{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"{sentinel}_kept_on_update", sentinel, set(), ["control", sentinel])+ for sentinel in FEATURE_FLAG_VARIANT_SENTINELS+ ),])- def test_sentinel_is_rejected_as_a_variant_key(self, _name: str, sentinel: str, enforced_rules: set[str]) -> None:- filters = {- "groups": [{"properties": [], "rollout_percentage": 100}],- "multivariate": {- "variants": [- {"key": "control", "rollout_percentage": 50},- {"key": sentinel, "rollout_percentage": 50},- ]- },- }+ def test_reserved_key_is_rejected_as_a_variant_key(+ self, _name: str, key: str, enforced_rules: set[str], stored_keys: list[str] | None+ ) -> None:with override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES=enforced_rules):- serializer = FeatureFlagSerializer(data={"filters": filters}, partial=True)+ serializer = _new_variant_serializer(key, stored_keys)assert not serializer.is_valid()assert serializer.errors["filters"][0].code == "reserved_variant_key"- assert sentinel in str(serializer.errors["filters"][0])+ assert key 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"]),+ ]+ )+ def test_unreserved_key_is_accepted_as_a_variant_key(+ self, _name: str, key: str, stored_keys: list[str] | None+ ) -> None:+ with override_settings(FEATURE_FLAG_FILTERS_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"])+ assert [variant["key"] for variant in validated["multivariate"]["variants"]] == ["control", key]@parameterized.expand([("list", ["$true"]), ("dict", {"key": "$true"})])def test_non_string_key_is_a_validation_error(self, _name: str, key: Any) -> None: