: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(flags): enforce structural and cross-field filters validation (#74761)
Patricio52d2b94808bc
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex ca824b3c4601..84f736484eb8 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -37,6 +37,7 @@ import {hasZeroRollout,featureFlagLogic as sceneFeatureFlagLogic,validateFeatureFlagKey,+ validateFeatureFlagVariantKey,} from 'scenes/feature-flags/featureFlagLogic'import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'@@ -4251,9 +4252,7 @@ export const experimentLogic = kea<experimentLogicType>([filters: {multivariate: {variants: feature_flag_config?.filters?.multivariate?.variants?.map(({ key }) => ({- key: !key.match?.(/^([A-z]|[a-z]|[0-9]|-|_)+$/)- ? 'Only letters, numbers, hyphens (-) & underscores (_) are allowed.'- : undefined,+ key: validateFeatureFlagVariantKey(key),})),},},diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 990e94d0d44c..f62ea2165a9d 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -3,7 +3,8 @@ import jsonfrom contextlib import suppressfrom posthog.settings.access import SECRET_KEY-from posthog.settings.utils import get_from_env, get_list+from posthog.settings.base_variables import TEST+from posthog.settings.utils import get_from_env, get_list, str_to_bool# Used mostly by the hobby install to have some feature flags enabled by default# NOTE: This only affects the frontend, the same FFs will still be considered disabled on the backend@@ -124,6 +125,20 @@ MAX_FEATURE_FLAG_FILTER_SIZE_BYTES: int = get_from_env(type_cast=int, # 512KB)+# Staged rollout switch for feature flag filters validation (#50084). When off (the+# production default for now), the new structural and cross-field filter tiers on the flag+# API log violations (`feature_flag_filters_enforcement_bypassed`) instead of rejecting+# them. Not gated by this switch: the pre-enforcement type/bounds checks+# (_reject_serde_unsafe_filters — the cache-poisoning class) and contextual checks (cohort+# existence, circular dependencies, size limits) always reject, so off means exactly the+# protection that predated enforcement, plus observation logging. Rollout: ship with the+# default off, compare the bypass-log volume against the audit's per-rule predictions for+# a few days of live traffic (the audit measured stored data, never request-shaped input),+# then enable via env var. The follow-up flip PR removes this switch and the now-redundant+# _reject_serde_unsafe_filters. Defaults on under TEST so the suite validates the enforced+# behavior.+FEATURE_FLAG_FILTERS_ENFORCEMENT: bool = get_from_env("FEATURE_FLAG_FILTERS_ENFORCEMENT", TEST, type_cast=str_to_bool)+# Team ID for the local-evaluation canary. Unset disables the canary task.FEATURE_FLAGS_CANARY_TEAM_ID: int | None = get_from_env("FEATURE_FLAGS_CANARY_TEAM_ID", optional=True, type_cast=int)diff --git a/posthog/tasks/test/test_process_scheduled_changes.py b/posthog/tasks/test/test_process_scheduled_changes.pyindex 02b5bcf0f14c..176126455692 100644--- a/posthog/tasks/test/test_process_scheduled_changes.py+++ b/posthog/tasks/test/test_process_scheduled_changes.py@@ -809,8 +809,9 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):# Verify the flag was updated correctlyupdated_flag = FeatureFlag.objects.get(key="test-variant-flag")- # Check that variants were cleared- self.assertEqual(updated_flag.filters["multivariate"]["variants"], [])+ # Clearing variants stores the canonical boolean shape (multivariate: null), not+ # the invalid {"variants": []} the filters serializer rejects (#50084).+ self.assertIsNone(updated_flag.filters["multivariate"])self.assertEqual(updated_flag.filters["payloads"], {})def test_schedule_feature_flag_update_variants_with_mismatched_payload_keys_fails(self) -> None:@@ -995,9 +996,11 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):# This should not raise any exception (empty variants should be allowed)feature_flag.scheduled_changes_dispatcher(empty_payload, self.user)- # Verify the flag was updated correctly with empty variants+ # Verify clearing variants stored the canonical boolean shape (multivariate: null)+ # and dropped the now-orphaned payloadsfeature_flag.refresh_from_db()- self.assertEqual(feature_flag.filters["multivariate"]["variants"], [])+ self.assertIsNone(feature_flag.filters["multivariate"])+ self.assertEqual(feature_flag.filters["payloads"], {})def test_scheduled_changes_dispatcher_validates_payload_keys_match_variants(self) -> None:"""Test that scheduled_changes_dispatcher validates that payload keys match variant keys"""diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 02b35033f556..8e02969fc76e 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -3716,7 +3716,9 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):],)- # Test removing aggregation_group_type_index+ # Test removing aggregation_group_type_index. PATCH filters merge with the stored+ # state per top-level key (#50084), so clearing requires an explicit null rather+ # than omitting the key.response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{feature_flag_id}",{@@ -3726,6 +3728,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):{"properties": [], "rollout_percentage": 1},],"payloads": {},+ "aggregation_group_type_index": None,"multivariate": {"variants": [{"key": "control", "rollout_percentage": 10},diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex b0e058d451c1..553884e6ef74 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -6,6 +6,7 @@ import jsonimport mathimport loggingimport functools+from collections.abc import Iterable, Iteratorfrom dataclasses import asdictfrom datetime import datetime, timedeltafrom typing import Any, NoReturn, Optional, cast@@ -22,13 +23,13 @@ import structlogfrom cryptography.fernet import InvalidTokenfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse, extend_schema_field+from prometheus_client import Counterfrom rest_framework import exceptions, request, serializers, status, viewsets+from rest_framework.exceptions import ErrorDetailfrom rest_framework.permissions import BasePermissionfrom rest_framework.response import Response-from posthog.schema import ProductKey, PropertyOperator--from posthog.hogql.property import parse_semver+from posthog.schema import ProductKeyfrom posthog.api.cohort import CohortSerializerfrom posthog.api.documentation import FeatureFlagFiltersSchemaSerializer, extend_schema@@ -49,6 +50,7 @@ from posthog.auth import ()from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.constants import FlagRequestType+from posthog.dataclasses import frozenfrom posthog.event_usage import report_user_actionfrom posthog.exceptions import Conflictfrom posthog.exceptions_capture import capture_exception@@ -63,10 +65,8 @@ from posthog.models.person.point_in_time_properties import (get_person_and_distinct_ids_for_identifier,)from posthog.models.property import Property-from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORSfrom posthog.permissions import TeamSecretTokenPermission, get_authenticator_scopes, is_service_authfrom posthog.ph_client import feature_enabled_or_false-from posthog.queries.base import determine_parsed_date_for_property_matchingfrom posthog.rate_limit import (ClickHouseBurstRateThrottle,ClickHouseSustainedRateThrottle,@@ -85,12 +85,25 @@ from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.util import get_all_cohort_dependenciesfrom products.dashboards.backend.api.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experiment, flag_has_live_experiment+from products.feature_flags.backend.api.filters_schema import (+ FEATURE_FLAG_OPERATOR_ALIASES,+ FEATURE_FLAG_PROPERTY_TYPES,+ FEATURE_FLAG_SUPPORTED_OPERATORS,+ FLAG_ID_CONTEXT_KEY,+ I32_MAX,+ I32_MIN,+ I64_MAX,+ I64_MIN,+ PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY,+ FeatureFlagFiltersSerializer,+)from products.feature_flags.backend.api.remote_config_shadow import shadow_compare_remote_configfrom products.feature_flags.backend.encrypted_flag_payloads import (REDACTED_PAYLOAD_VALUE,encrypt_flag_payloads,get_decrypted_flag_payloads_protected,)+from products.feature_flags.backend.filters_validation import collect_cross_field_violations, flatten_structural_errorsfrom products.feature_flags.backend.flag_analytics import increment_request_countfrom products.feature_flags.backend.flag_limits import get_max_feature_flags_for_teamfrom products.feature_flags.backend.flag_status import (@@ -119,6 +132,81 @@ logger = logging.getLogger(__name__)# results in a disabled logger because `posthog.api.feature_flag` is loaded during# Django startup. Remove this logger together with the helper once the scope is enforced.scope_audit_logger = structlog.get_logger("posthog.feature_flag_scope_audit")+# Dedicated name for the same startup-ordering reason as scope_audit_logger above. Emits+# the violations that would have been 400s while the #50084 enforcement kill switch is off.+filters_enforcement_logger = structlog.get_logger("posthog.feature_flag_filters_enforcement")++# DRF error messages echo caller-controlled input (a ChoiceField repeats the rejected value)+# and bodies up to 20MB reach validation before the filter-size check runs, so an unbounded+# log line is one PATCH away. The bake depends on these logs staying countable.+MAX_LOGGED_ENFORCEMENT_ERRORS = 20+MAX_LOGGED_ENFORCEMENT_ERROR_CHARS = 300++# Rollout observability for #50084 enforcement. Writes counted once per flag write that+# carries `filters`; `bypassed` is the series to watch during the log-only window (would+# have been rejected with enforcement on). Labels are bounded: rule ids come from the+# fixed rule set in filters_validation.py / flatten_structural_errors.+FLAG_FILTERS_WRITE_COUNTER = Counter(+ "posthog_feature_flag_filters_write_total",+ "Feature flag writes carrying filters, by validation outcome",+ labelnames=["operation", "outcome", "source"],+)++FLAG_FILTERS_VIOLATION_COUNTER = Counter(+ "posthog_feature_flag_filters_violation_total",+ "Filters validation violations, by tier and rule",+ labelnames=["stage", "rule", "operation"],+)+++def _flag_write_source(request: Any) -> str:+ """Coarse write-source attribution for metrics. Never returns unbounded values."""+ if request is None:+ 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"+ authenticator = getattr(request, "successful_authenticator", None)+ auth_class = type(authenticator).__name__ if authenticator is not None else ""+ if auth_class == "SessionAuthentication":+ return "ui"+ if auth_class in (+ "PersonalAPIKeyAuthentication",+ "ProjectSecretAPIKeyAuthentication",+ "OAuthAccessTokenAuthentication",+ ):+ return "api"+ return "other"+++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:+ for rule_id in rule_ids:+ FLAG_FILTERS_VIOLATION_COUNTER.labels(stage=stage, rule=rule_id or "unknown", operation=operation).inc()+++def _mark_filters_bypassed(serializer: serializers.Serializer) -> None:+ root = serializer.root if serializer.root is not None else serializer+ root._filters_bypassed = True # type: ignore[attr-defined]+++def _mark_filters_enforced_rejection(serializer: serializers.Serializer) -> None:+ """Marks a rejection as coming from a switch-gated tier, so the counter can tell it apart+ from the checks that rejected long before enforcement (cohort existence, circular+ dependencies, regex, size cap, the early_exit gate, the serde guard). Without the split,+ the rejected series is dominated by those and says nothing about the flip's impact."""+ root = serializer.root if serializer.root is not None else serializer+ root._filters_enforced_rejection = True # type: ignore[attr-defined]+++def _count_filters_write_success(serializer: serializers.Serializer, operation: str, request: Any) -> None:+ root = serializer.root if serializer.root is not None else serializer+ outcome = "bypassed" if getattr(root, "_filters_bypassed", False) else "accepted"+ _count_filters_write(operation, outcome, request)+BEHAVIOURAL_COHORT_FOUND_ERROR_CODE = "behavioral_cohort_found"@@ -350,49 +438,6 @@ def _validate_behavioral_cohort_for_feature_flag()-# Operators the Rust feature-flag evaluation service supports (OperatorType in property_models.rs).-# None means "no operator specified" which defaults to exact.-FEATURE_FLAG_SUPPORTED_OPERATORS: frozenset[str | None] = frozenset(- {- None,- "exact",- "is_not",- "icontains",- "not_icontains",- "icontains_multi",- "not_icontains_multi",- "regex",- "not_regex",- "gt",- "gte",- "lt",- "lte",- "semver_gt",- "semver_gte",- "semver_lt",- "semver_lte",- "semver_eq",- "semver_neq",- "semver_tilde",- "semver_caret",- "semver_wildcard",- "is_set",- "is_not_set",- "is_date_exact",- "is_date_after",- "is_date_before",- "in",- "not_in",- "flag_evaluates_to",- }- | set(STRING_PREFIX_SUFFIX_OPERATORS)-)--FEATURE_FLAG_OPERATOR_ALIASES: dict[str, str] = {- "min": "gte",- "max": "lte",-}-FEATURE_FLAG_CREATION_CONTEXT_CHOICES = ("feature_flags","experiments",@@ -789,6 +834,225 @@ class EvaluationContextSerializerMixin(serializers.Serializer):return ret+# Master constructed Property(**prop) on every write, so it accepted any type the Property+# model knows; the narrower flags-only set belongs to the switch-gated structural tier.+# Exactly the variants Rust's flag-side PropertyType deserializes. Not the generic PostHog+# PropertyType union, which includes types like "event" that the flag service has no variant+# for: the hypercache payload is deserialized whole, so one such property fails the team's+# entire cached flag set. person_metadata is here because Rust accepts it — the narrower+# four-type set the structural tier enforces is a policy choice, not a serde limit.+_RUST_PROPERTY_TYPES: frozenset[str] = frozenset({*FEATURE_FLAG_PROPERTY_TYPES, "person_metadata"})+++def _reject_serde_unsafe_filters(filters: Any) -> None:+ """Unconditional serde-fidelity guard on incoming filters, active regardless of the+ FEATURE_FLAG_FILTERS_ENFORCEMENT switch.++ These are the pre-#50084 procedural type/bounds checks: values that fail serde in the+ Rust flag service and poison the team's flag cache. While the enforcement switch is off,+ the structural tier only logs, so this keeps the poisoning class rejected exactly as it+ was before enforcement shipped. Only called while the switch is off: with it on, the+ structural tier covers all of this with better per-rule error codes. DELETE together with+ the switch in the follow-up PR that defaults enforcement on.+ """+ if not isinstance(filters, dict):+ raise serializers.ValidationError(f"Filters must be a dictionary, got {type(filters).__name__}")++ def _validate_rollout_percentage(value: Any, path: str, *, allow_null: bool = True) -> None:+ if value is None:+ if not allow_null:+ raise serializers.ValidationError(f"{path} must be a number, got null")+ return+ # Check bool before int/float because bool is a subclass of int+ if isinstance(value, bool) or not isinstance(value, int | float):+ expected = "a number or null" if allow_null else "a number"+ raise serializers.ValidationError(f"{path} must be {expected}, got {type(value).__name__}")+ if not math.isfinite(value):+ raise serializers.ValidationError(f"{path} must be finite, got {value}")+ if value < 0 or value > 100:+ raise serializers.ValidationError(f"{path} must be between 0 and 100, got {value}")++ def _validate_integer(value: Any, path: str, *, min_value: int, max_value: int) -> None:+ # Check bool before int because bool is a subclass of int+ if value is not None and (isinstance(value, bool) or not isinstance(value, int)):+ raise serializers.ValidationError(f"{path} must be an integer or null, got {type(value).__name__}")+ if value is not None and (value < min_value or value > max_value):+ raise serializers.ValidationError(f"{path} must be between {min_value} and {max_value}, got {value}")++ _validate_integer(+ filters.get("aggregation_group_type_index"),+ "aggregation_group_type_index",+ min_value=I32_MIN,+ max_value=I32_MAX,+ )++ early_exit = filters.get("early_exit")+ if early_exit is not None and not isinstance(early_exit, bool):+ raise serializers.ValidationError(f"early_exit must be a boolean or null, got {type(early_exit).__name__}")+ feature_enrollment = filters.get("feature_enrollment")+ if feature_enrollment is not None and not isinstance(feature_enrollment, bool):+ raise serializers.ValidationError(+ f"feature_enrollment must be a boolean or null, got {type(feature_enrollment).__name__}"+ )++ holdout = filters.get("holdout")+ if holdout is not None:+ if not isinstance(holdout, dict):+ raise serializers.ValidationError(f"holdout must be a dictionary or null, got {type(holdout).__name__}")+ _validate_integer(holdout.get("id"), "holdout.id", min_value=I64_MIN, max_value=I64_MAX)+ if "id" not in holdout or holdout.get("id") is None:+ raise serializers.ValidationError("holdout.id must be an integer")+ exclusion_percentage = holdout.get("exclusion_percentage")+ if isinstance(exclusion_percentage, bool) or not isinstance(exclusion_percentage, int | float):+ raise serializers.ValidationError("holdout.exclusion_percentage must be a number")+ if not math.isfinite(exclusion_percentage):+ raise serializers.ValidationError("holdout.exclusion_percentage must be finite")++ groups = filters.get("groups", [])+ if not isinstance(groups, list):+ raise serializers.ValidationError(f"groups must be a list, got {type(groups).__name__}")+ for group_index, group in enumerate(groups):+ if not isinstance(group, dict):+ raise serializers.ValidationError(f"groups[{group_index}] must be a dictionary, got {type(group).__name__}")+ variant = group.get("variant")+ if variant is not None and not isinstance(variant, str):+ raise serializers.ValidationError(+ f"groups[{group_index}].variant must be a string or null, got {type(variant).__name__}"+ )+ _validate_rollout_percentage(group.get("rollout_percentage"), f"groups[{group_index}].rollout_percentage")+ _validate_integer(+ group.get("aggregation_group_type_index"),+ f"groups[{group_index}].aggregation_group_type_index",+ min_value=I32_MIN,+ max_value=I32_MAX,+ )++ # `or []` would let a falsy non-list (an empty dict) skip the type check below, and+ # Rust can't deserialize an object into Vec<PropertyFilter>. Null stays allowed:+ # properties is Option<Vec<..>> there.+ properties = group.get("properties")+ properties = [] if properties is None else properties+ if not isinstance(properties, list):+ raise serializers.ValidationError(+ f"groups[{group_index}].properties must be a list, got {type(properties).__name__}"+ )+ for prop_index, prop in enumerate(properties):+ if not isinstance(prop, dict):+ raise serializers.ValidationError(+ f"groups[{group_index}].properties[{prop_index}] must be a dictionary, got {type(prop).__name__}"+ )+ _validate_integer(+ prop.get("group_type_index"),+ f"groups[{group_index}].properties[{prop_index}].group_type_index",+ min_value=I32_MIN,+ max_value=I32_MAX,+ )+ negation = prop.get("negation")+ if negation is not None and not isinstance(negation, bool):+ raise serializers.ValidationError(+ f"groups[{group_index}].properties[{prop_index}].negation must be a boolean or null"+ )++ multivariate = filters.get("multivariate")+ if multivariate is not None and not isinstance(multivariate, dict):+ raise serializers.ValidationError(+ f"multivariate must be a dictionary or null, got {type(multivariate).__name__}"+ )+ if isinstance(multivariate, dict) and multivariate.get("variants") is None:+ raise serializers.ValidationError("multivariate.variants must be a list")+ variants = (multivariate or {}).get("variants")+ variants = [] if variants is None else variants+ if not isinstance(variants, list):+ raise serializers.ValidationError(f"multivariate.variants must be a list, got {type(variants).__name__}")+ for var_index, variant_item in enumerate(variants):+ if not isinstance(variant_item, dict):+ raise serializers.ValidationError(+ f"multivariate.variants[{var_index}] must be a dictionary, got {type(variant_item).__name__}"+ )+ # Rust declares MultivariateFlagVariant.key as a required String, so a variant without+ # one fails the team's whole hypercache payload rather than just its own flag.+ if not isinstance(variant_item.get("key"), str):+ raise serializers.ValidationError(f"multivariate.variants[{var_index}].key must be a string")+ name = variant_item.get("name")+ if name is not None and not isinstance(name, str):+ raise serializers.ValidationError(f"multivariate.variants[{var_index}].name must be a string or null")+ _validate_rollout_percentage(+ variant_item.get("rollout_percentage"),+ f"multivariate.variants[{var_index}].rollout_percentage",+ allow_null=False,+ )++ # An operator or type string Rust doesn't know fails serde on the hypercache blob, which+ # Django serializes whole — the per-flag skip in the Rust Postgres path never sees it, so+ # one bad property takes out the team's cached flag set. Aliases count as known: master+ # canonicalized them before checking.+ for located in _iter_flag_filter_properties(filters.get("groups")):+ operator = located.prop.get("operator")+ if operator is not None and (+ not isinstance(operator, str)+ or (operator not in FEATURE_FLAG_SUPPORTED_OPERATORS and operator not in FEATURE_FLAG_OPERATOR_ALIASES)+ ):+ raise serializers.ValidationError(f"{located.path}.operator: unsupported operator for feature flags")+ # Rust's PropertyFilter declares key and type as required (Option-typed fields are the+ # optional ones), so a property missing either fails the whole payload, not just itself.+ prop_key = located.prop.get("key")+ if prop_key is None or isinstance(prop_key, bool) or not isinstance(prop_key, str | int | float):+ raise serializers.ValidationError(f"{located.path}.key: a property key is required")+ prop_type = located.prop.get("type")+ if not isinstance(prop_type, str) or prop_type not in _RUST_PROPERTY_TYPES:+ raise serializers.ValidationError(f"{located.path}.type: invalid property type")++ # Explicit null is allowed (Rust reads payloads as an Option) even though the old check+ # rejected it — the structural tier owns that looser, serde-faithful contract.+ payloads = filters.get("payloads")+ if payloads is not None and not isinstance(payloads, dict):+ raise serializers.ValidationError("Payloads must be passed as a dictionary")+ # A payload string that doesn't parse is one an SDK can't JSON.parse at evaluation time,+ # and master rejected it. Plain json.loads on purpose: NaN tolerance matches master, while+ # the stricter allow_nan=False contract belongs to the switch-gated structural tier.+ for payload_key, payload_value in (payloads or {}).items():+ if isinstance(payload_value, str):+ try:+ json.loads(payload_value)+ except json.JSONDecodeError:+ raise serializers.ValidationError(f"Payload for key '{payload_key}' is not valid JSON.")+++@frozen+class _FlagFilterProperty:+ group_index: int+ property_index: int+ prop: dict[str, Any]++ @property+ def path(self) -> str:+ """Error-message prefix pointing at this property inside `filters`."""+ return f"groups[{self.group_index}].properties[{self.property_index}]"+++def _iter_flag_filter_properties(groups: Any) -> Iterator[_FlagFilterProperty]:+ """Yield each well-formed property filter found under `groups`.++ Malformed entries are skipped instead of crashing: they can only occur while the #50084+ enforcement kill switch is off, and log-only mode must never 500.+ """+ if not isinstance(groups, list):+ return+ for group_index, group in enumerate(groups):+ if not isinstance(group, dict):+ continue+ properties = group.get("properties")+ if not isinstance(properties, list):+ continue+ for prop_index, prop in enumerate(properties):+ if isinstance(prop, dict):+ yield _FlagFilterProperty(+ group_index=group_index,+ property_index=prop_index,+ prop=cast(dict[str, Any], prop),+ )++class FeatureFlagCreateRequestSchemaSerializer(serializers.Serializer):key = serializers.CharField(required=False, help_text="Feature flag key.")name = serializers.CharField(@@ -1231,65 +1495,127 @@ class FeatureFlagSerializer(return _is_realtime_cohort_flag_targeting_enabled(self.context["request"])def validate_filters(self, filters):- # For some weird internal REST framework reason this field gets validated on a partial PATCH call, even if filters isn't being updatd- # If we see this, just return the current filters- if "groups" not in filters and self.context["request"].method == "PATCH":- # mypy cannot tell that self.instance is a FeatureFlag+ # Metrics wrapper: one increment per rejected write. `rejected` means a switch-gated+ # tier raised, so the series answers "what does enforcement reject"; everything that+ # already rejected before this rollout lands in `rejected_preexisting`. `accepted` and+ # `bypassed` are counted at save time in create()/update().+ operation = "create" if self.instance is None else "update"+ try:+ return self._validate_filters_inner(filters, operation)+ except serializers.ValidationError:+ root = self.root if self.root is not None else self+ enforced = getattr(root, "_filters_enforced_rejection", False)+ _count_filters_write(+ operation, "rejected" if enforced else "rejected_preexisting", self.context.get("request")+ )+ raise++ def _validate_filters_inner(self, filters, operation: str):+ # An empty filters dict on an update carries no instruction, so the merged state is+ # the stored state and there is nothing to validate. Returning it untouched also+ # keeps normalization off flags the request never addressed: DRF hands DictField an+ # empty dict rather than "absent" for form-encoded requests, so a PATCH of just+ # `active` would otherwise rewrite stored filters. Creates still fall through, where+ # the empty-groups rule rejects them.+ if self.instance is not None and not filters:assert isinstance(self.instance, FeatureFlag)return self.instance.filters- filters.setdefault("groups", [])-- # Only validate empty groups for new flag creation (POST), not updates (PUT/PATCH)- # Existing flags may legitimately have empty groups temporarily during scheduled changes- if self.context["request"].method == "POST":- if not filters["groups"]:- raise serializers.ValidationError("Feature flags must have at least one condition set (group).")-- flag_level_aggregation = filters.get("aggregation_group_type_index", None)-- # Validate filter field types to prevent serde deserialization failures in the- # Rust flag evaluation service. Non-conforming types poison the entire team's- # flag cache and cause 500s on every /flags request.- def _validate_rollout_percentage(value: Any, path: str, *, allow_null: bool = True) -> None:- if value is None:- if not allow_null:- raise serializers.ValidationError(f"{path} must be a number, got null")- return- # Check bool before int/float because bool is a subclass of int- if isinstance(value, bool) or not isinstance(value, (int, float)):- expected = "a number or null" if allow_null else "a number"- raise serializers.ValidationError(f"{path} must be {expected}, got {type(value).__name__}")- if not math.isfinite(value):- raise serializers.ValidationError(f"{path} must be finite, got {value}")- if value < 0 or value > 100:- raise serializers.ValidationError(f"{path} must be between 0 and 100, got {value}")-- def _validate_integer(value: Any, path: str) -> None:- # Check bool before int because bool is a subclass of int- if value is not None and (isinstance(value, bool) or not isinstance(value, int)):- raise serializers.ValidationError(f"{path} must be an integer or null, got {type(value).__name__}")-- def _validate_regex_pattern(value: Any, path: str, existing_patterns: set[str]) -> None:- if not isinstance(value, str):- return- if value not in existing_patterns and not is_valid_regex(value):- raise serializers.ValidationError(f"{path}: invalid regex pattern")-- _validate_integer(flag_level_aggregation, "aggregation_group_type_index")+ # `filters` arrives as the raw request dict, so the structural tier runs once below,+ # on the merged state.+ enforcement: bool = settings.FEATURE_FLAG_FILTERS_ENFORCEMENT- # Collect existing regex patterns so we don't reject unchanged patterns on- # PATCH — flags may contain regexes valid in fancy_regex/PG ARE but not Python re.- existing_patterns: set[str] = set()+ # Log-only mode must never accept what the pre-enforcement validator rejected, so the+ # cache-poisoning class stays rejected while the switch is off. With the switch on the+ # structural tier covers every one of these rules and reports them with per-rule codes+ # instead of this guard's flat messages, so it would only shadow the better errors.+ if not enforcement:+ try:+ _reject_serde_unsafe_filters(filters)+ except serializers.ValidationError:+ _count_filters_violations("serde_fidelity", operation, ["serde_fidelity"])+ raise++ # Updates validate and store the merged final state (#50084): incoming top-level keys+ # replace stored ones atomically, so `filters: {}` is a validated no-op and+ # `groups: []` an intentional clear-targeting request. Keyed on instance presence,+ # not request method: several callers drive partial updates under other methods+ # (e.g. experiment holdout detach runs under DELETE).if self.instance is not None:- for g in (self.instance.filters or {}).get("groups", []) or []:- for p in g.get("properties", []) or []:- if p.get("operator") in ("regex", "not_regex") and isinstance(p.get("value"), str):- existing_patterns.add(p["value"])+ # mypy cannot tell that self.instance is a FeatureFlag+ assert isinstance(self.instance, FeatureFlag)+ stored_filters = self.instance.filters or {}+ merged = {**copy.deepcopy(stored_filters), **filters}+ # Stored encrypted payloads are ciphertext, not JSON: they would fail structural+ # validation below and, worse, get re-encrypted by update()'s reconciliation if+ # they flowed through the merge as if this request had sent them. When the+ # request doesn't replace payloads, validate the redacted sentinel instead;+ # update() swaps the stored ciphertext back in before saving.+ if self.instance.has_encrypted_payloads and "payloads" not in filters:+ stored_payloads = stored_filters.get("payloads") or {}+ if stored_payloads:+ merged["payloads"] = dict.fromkeys(stored_payloads, REDACTED_PAYLOAD_VALUE)+ else:+ # deepcopy: the normalization below writes into the condition dicts, and on create+ # these are the request body's own objects.+ merged = copy.deepcopy(filters)++ # Size first: validating a 20MB filters object materializes a violation and a metric+ # increment per offending entry, so the cheap check has to come before that work+ # rather than after it. Re-checked post-normalization below, since normalizing+ # payloads changes the encoded size.+ self._reject_oversized_filters(merged)++ # Re-validate the merged state structurally: the stored side of the merge never went+ # through FeatureFlagFiltersField on this request, and the cross-field collectors+ # below are only safe on structurally valid input. For stored filters that predate+ # enforcement (#50084 leave-and-block), this blocks the first filters edit until the+ # violation is fixed; reads and non-filter updates of such flags are untouched.+ structural = FeatureFlagFiltersSerializer(+ data=merged,+ context={+ FLAG_ID_CONTEXT_KEY: getattr(self.instance, "id", None),+ PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY: not enforcement,+ },+ )+ structurally_valid = structural.is_valid()+ if structurally_valid:+ # Also normalizes the stored side (operator aliases, payload encoding, groups+ # default) and drops unknown keys, logging non-legacy ones.+ merged = structural.validated_data+ else:+ details = [+ 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])+ # 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"])+ if enforcement:+ _mark_filters_enforced_rejection(self)+ raise serializers.ValidationError(details)+ _mark_filters_bypassed(self)+ filters_enforcement_logger.warning(+ "feature_flag_filters_enforcement_bypassed",+ stage="merged_structural",+ flag_id=getattr(self.instance, "id", None),+ error_count=len(details),+ errors=[+ str(detail)[:MAX_LOGGED_ENFORCEMENT_ERROR_CHARS]+ for detail in details[:MAX_LOGGED_ENFORCEMENT_ERRORS]+ ],+ )+ merged.setdefault("groups", [])- early_exit = filters.get("early_exit")- if early_exit is not None and not isinstance(early_exit, bool):- raise serializers.ValidationError(f"early_exit must be a boolean or null, got {type(early_exit).__name__}")+ # Only validate empty groups for new flag creation (POST), not updates (PUT/PATCH).+ # Locked #50084 asymmetry: existing flags may legitimately have empty groups (e.g.+ # temporarily during scheduled changes) and PATCH {"groups": []} is a deliberate+ # clear-targeting request — do not unify this with the update path in either direction.+ if self.context["request"].method == "POST" and not merged["groups"]:+ raise serializers.ValidationError("Feature flags must have at least one condition set (group).")# Gate enabling early_exit behind the feature-flag-early-exit flag. The UI hides# the toggle, but the public REST API, MCP tools, and terraform provider all reach@@ -1297,65 +1623,41 @@ class FeatureFlagSerializer(# local evaluation honors it. Only block newly turning it on: leaving an existing# truthy value unchanged (or turning it off) always passes, so flags created while# the feature was enabled keep working if access is later revoked.+ early_exit = merged.get("early_exit")previously_enabled = (bool((self.instance.filters or {}).get("early_exit")) if self.instance is not None else False)if early_exit and not previously_enabled and not self._is_early_exit_enabled():raise serializers.ValidationError("early_exit is not available for this organization.")- for group_index, group in enumerate(filters.get("groups", [])):- variant = group.get("variant")- if variant is not None and not isinstance(variant, str):- raise serializers.ValidationError(- f"groups[{group_index}].variant must be a string or null, got {type(variant).__name__}"- )-- _validate_rollout_percentage(group.get("rollout_percentage"), f"groups[{group_index}].rollout_percentage")- _validate_integer(- group.get("aggregation_group_type_index"),- f"groups[{group_index}].aggregation_group_type_index",- )-- for prop_index, prop in enumerate(group.get("properties", [])):- _validate_integer(- prop.get("group_type_index"),- f"groups[{group_index}].properties[{prop_index}].group_type_index",- )-- if prop.get("operator") in ("regex", "not_regex"):- _validate_regex_pattern(- prop.get("value"),- f"groups[{group_index}].properties[{prop_index}].value",- existing_patterns,- )-- for var_index, variant in enumerate((filters.get("multivariate") or {}).get("variants", [])):- _validate_rollout_percentage(- variant.get("rollout_percentage"),- f"multivariate.variants[{var_index}].rollout_percentage",- allow_null=False,- )+ # The normalization and the two contextual checks below ran on every write before+ # enforcement, junk shapes and all, so they stay outside the structurally_valid gate:+ # a stored-violating flag in log-only mode must not slip a dependency cycle past them+ # or persist an unnormalized aggregation index. The dict filter keeps them tolerant of+ # the malformed groups the serde guard lets through.+ well_formed_groups = [condition for condition in merged["groups"] if isinstance(condition, dict)]# Normalize: distribute the flag-level aggregation_group_type_index to each# condition set that doesn't already have one, so every condition set# explicitly carries its aggregation mode (including None for person-aggregated).- for condition in filters["groups"]:+ flag_level_aggregation = merged.get("aggregation_group_type_index")+ for condition in well_formed_groups:if "aggregation_group_type_index" not in condition:condition["aggregation_group_type_index"] = flag_level_aggregation# Derive the flag-level field from condition sets for backward compatibility.# If all condition sets share the same aggregation, use that; when mixed,# set to None since the evaluation engine reads per-condition aggregation.- condition_aggregations = [c.get("aggregation_group_type_index") for c in filters["groups"]]+ condition_aggregations = [c.get("aggregation_group_type_index") for c in well_formed_groups]if condition_aggregations:if all(a == condition_aggregations[0] for a in condition_aggregations):- filters["aggregation_group_type_index"] = condition_aggregations[0]+ merged["aggregation_group_type_index"] = condition_aggregations[0]else:- filters["aggregation_group_type_index"] = None+ merged["aggregation_group_type_index"] = None# Check Early Access Feature constraint: no condition set can use group# aggregation if the flag is linked to an Early Access Feature.- has_group_condition = any(c.get("aggregation_group_type_index") is not None for c in filters["groups"])+ has_group_condition = any(c.get("aggregation_group_type_index") is not None for c in well_formed_groups)if (has_group_conditionand self.instance is not None@@ -1366,261 +1668,105 @@ class FeatureFlagSerializer("Cannot use group aggregation in any condition set when the flag is linked to an Early Access Feature.")- # Validate properties per condition set against that condition set's aggregation.- for condition in filters["groups"]:- condition_aggregation = condition.get("aggregation_group_type_index")- condition_props = condition.get("properties", [])-- for prop_dict in condition_props:- prop = Property(**prop_dict)-- if condition_aggregation is None:- # Person-aggregated condition: allow person, cohort, and flag properties- if prop.type not in ["person", "cohort", "flag"]:- raise serializers.ValidationError(- "Filters are not valid (person-aggregated conditions can only use person, cohort, and flag properties)"- )- if prop.type == "flag":- if prop_dict.get("operator") != "flag_evaluates_to":- raise serializers.ValidationError(- "Flag properties must use the 'flag_evaluates_to' operator"- )- # Flag dependency keys are flag IDs. The Rust flags service declares- # PropertyFilter.key as a string and serde won't coerce a JSON number,- # so a numeric key fails deserialization of the entire team's cached- # flag payload. Persist it as a string so it round-trips cleanly.- dependency_key = prop_dict.get("key")- if dependency_key is not None:- prop_dict["key"] = str(dependency_key)- else:- # Group-aggregated condition: only allow group properties matching the- # condition's group type- if prop.type != "group":- raise serializers.ValidationError(- "Filters are not valid (group-aggregated conditions can only use group properties)"- )- if prop.group_type_index != condition_aggregation:- raise serializers.ValidationError(- "Filters are not valid (group properties must match the condition set's group type)"- )-# Circular dependency checks only apply to person-aggregated conditions# since flag-based property filters only work with person aggregation- has_person_condition = any(c.get("aggregation_group_type_index") is None for c in filters["groups"])+ has_person_condition = any(c.get("aggregation_group_type_index") is None for c in well_formed_groups)if has_person_condition:- self._check_flag_circular_dependencies(filters)-- variant_list = (filters.get("multivariate") or {}).get("variants", [])- variants = {variant["key"] for variant in variant_list}-- # Validate rollout percentages for multivariate variants- if variant_list:- variant_rollout_sum = sum(variant.get("rollout_percentage", 0) for variant in variant_list)- if variant_rollout_sum != 100:- raise serializers.ValidationError(- "Invalid variant definitions: Variant rollout percentages must sum to 100.",- code="invalid_input",+ self._check_flag_circular_dependencies(merged)++ if structurally_valid:+ # Cross-field tier (#50084): variant sums, key uniqueness, payload/variant+ # agreement, operator/value compatibility — see filters_validation.py.+ 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])-- for condition in filters["groups"]:- if condition.get("variant") and condition["variant"] not in variants:- raise serializers.ValidationError("Filters are not valid (variant override does not exist)")-- for property in condition.get("properties", []):- if property.get("operator") in FEATURE_FLAG_OPERATOR_ALIASES:- property["operator"] = FEATURE_FLAG_OPERATOR_ALIASES[property["operator"]]-- prop = Property(**property)-- if prop.operator is not None and prop.operator not in PropertyOperator.__members__.values():+ if enforcement:+ _mark_filters_enforced_rejection(self)raise serializers.ValidationError(- detail=f"Invalid operator: {prop.operator}",- code="invalid_operator",+ [+ ErrorDetail(f"{violation.path}: {violation.message}", code=violation.rule_id)+ for violation in cross_field_violations+ ])+ _mark_filters_bypassed(self)+ filters_enforcement_logger.warning(+ "feature_flag_filters_enforcement_bypassed",+ stage="cross_field",+ flag_id=getattr(self.instance, "id", None),+ error_count=len(cross_field_violations),+ errors=[+ f"{violation.path}: {violation.message}"[:MAX_LOGGED_ENFORCEMENT_ERROR_CHARS]+ for violation in cross_field_violations[:MAX_LOGGED_ENFORCEMENT_ERRORS]+ ],+ )- if prop.operator not in FEATURE_FLAG_SUPPORTED_OPERATORS:- raise serializers.ValidationError(- detail=f"Unsupported operator for feature flags: {prop.operator}",- code="unsupported_operator",- )-- if prop.type == "cohort":- try:- initial_cohort: Cohort = Cohort.objects.get(- pk=cast(str | int, prop.value), team__project_id=self.context["project_id"]- )- # Static cohorts (including one-time snapshots) hold a- # materialised person list. The populating criteria may- # still be stored on the record, but they are inert – the- # cohort no longer re-evaluates them, and the Rust engine's- # extract_dependencies returns an empty set for them. Skip- # both the behavioural property check and the dependency walk- # so snapshot cohorts can be used in flags without an extra- # export step, even when their inert criteria reference- # another cohort. See #65270.- dependency_cohorts = (- []- if initial_cohort.is_static- else get_all_cohort_dependencies(initial_cohort, stop_traversal_at_static=True)- )- for cohort in [initial_cohort, *dependency_cohorts]:- # Static cohorts have materialized membership, any preserved behavioral- # filters are display-only and never evaluated, so skip them.- if cohort.is_static:- continue- behavioral_props = [- cohort_prop- for cohort_prop in cohort.properties.flat- if cohort_prop.type == "behavioral"- ]- # Gate on both signals: cohort.properties.flat parses each leaf into a- # Property() object, so a leaf shape the parser doesn't recognize would- # silently vanish from it and defeat this guard; _has_filter_type walks- # the raw filters JSON instead, so it can't miss an unparsable leaf. But- # _has_filter_type only reads `filters` — legacy cohorts that store their- # condition in the deprecated `groups` field instead (see Cohort.properties)- # would defeat *that* check, so behavioral_props still needs to cover them.- if cohort._has_filter_type("behavioral") or behavioral_props:- _validate_behavioral_cohort_for_feature_flag(- cohort, behavioral_props, allow_realtime_backfilled=self._allow_realtime_backfilled- )- except Cohort.DoesNotExist:- raise serializers.ValidationError(- detail=f"Cohort with id {prop.value} does not exist",- code="cohort_does_not_exist",- )-- if prop.operator in (- PropertyOperator.IS_DATE_BEFORE,- PropertyOperator.IS_DATE_AFTER,- PropertyOperator.IS_DATE_EXACT,- ):- parsed_date = determine_parsed_date_for_property_matching(prop.value)+ # Collect existing regex patterns so we don't reject unchanged patterns on+ # PATCH — flags may contain regexes valid in fancy_regex/PG ARE but not Python re.+ existing_patterns: set[str] = set()+ if self.instance is not None:+ for g in (self.instance.filters or {}).get("groups", []) or []:+ for p in g.get("properties", []) or []:+ if p.get("operator") in ("regex", "not_regex") and isinstance(p.get("value"), str):+ existing_patterns.add(p["value"])- if not parsed_date:- raise serializers.ValidationError(- detail=f"Invalid date value: {prop.value}",- code="invalid_date",- )+ for located in _iter_flag_filter_properties(merged.get("groups")):+ if located.prop.get("operator") in ("regex", "not_regex"):+ pattern = located.prop.get("value")+ if isinstance(pattern, str) and pattern not in existing_patterns and not is_valid_regex(pattern):+ raise serializers.ValidationError(f"{located.path}.value: invalid regex pattern")- # make sure regex, icontains, starts/ends_with, gte, lte, lt, and gt properties have string values- if prop.operator in [- "regex",- "icontains",- "not_regex",- "not_icontains",- "starts_with",- "not_starts_with",- "ends_with",- "not_ends_with",- "gte",- "lte",- "gt",- "lt",- ] and not isinstance(prop.value, str):- raise serializers.ValidationError(- detail=f"Invalid value for operator {prop.operator}: {prop.value}",- code="invalid_value",+ if located.prop.get("type") == "cohort":+ cohort_id = located.prop.get("value")+ try:+ initial_cohort: Cohort = Cohort.objects.get(+ pk=cast(str | int, cohort_id), team__project_id=self.context["project_id"])-- if prop.operator in (PropertyOperator.IN_, PropertyOperator.NOT_IN) and prop.type != "cohort":- raise serializers.ValidationError(- detail=f"The '{prop.operator}' operator is only valid for cohort properties, not '{prop.type}' properties.",- code="invalid_operator",+ # Static cohorts (including one-time snapshots) hold a+ # materialised person list. The populating criteria may+ # still be stored on the record, but they are inert – the+ # cohort no longer re-evaluates them, and the Rust engine's+ # extract_dependencies returns an empty set for them. Skip+ # both the behavioural property check and the dependency walk+ # so snapshot cohorts can be used in flags without an extra+ # export step, even when their inert criteria reference+ # another cohort. See #65270.+ dependency_cohorts = (+ []+ if initial_cohort.is_static+ else get_all_cohort_dependencies(initial_cohort, stop_traversal_at_static=True))-- # Currently unreachable (between/not_between rejected by FEATURE_FLAG_SUPPORTED_OPERATORS),- # but kept so value validation is ready if Rust adds support for these operators.- if prop.operator in (PropertyOperator.BETWEEN, PropertyOperator.NOT_BETWEEN):- if not isinstance(prop.value, list) or len(prop.value) != 2:- raise serializers.ValidationError(- detail=f"{prop.operator} operator requires a two-element array [min, max]",- code="invalid_value",- )- try:- min_val = prop.value[0]- max_val = prop.value[1]- # Type check: ensure both values can be converted to float- if not isinstance(min_val, (int, float, str)) or not isinstance(max_val, (int, float, str)):- raise ValueError("Values must be numeric")- if float(min_val) > float(max_val):- raise serializers.ValidationError(- detail=f"{prop.operator} operator requires min value to be less than or equal to max value",- code="invalid_value",+ for cohort in [initial_cohort, *dependency_cohorts]:+ # Static cohorts have materialized membership, any preserved behavioral+ # filters are display-only and never evaluated, so skip them.+ if cohort.is_static:+ continue+ behavioral_props = [+ cohort_prop for cohort_prop in cohort.properties.flat if cohort_prop.type == "behavioral"+ ]+ # Gate on both signals: cohort.properties.flat parses each leaf into a+ # Property() object, so a leaf shape the parser doesn't recognize would+ # silently vanish from it and defeat this guard; _has_filter_type walks+ # the raw filters JSON instead, so it can't miss an unparsable leaf. But+ # _has_filter_type only reads `filters` — legacy cohorts that store their+ # condition in the deprecated `groups` field instead (see Cohort.properties)+ # would defeat *that* check, so behavioral_props still needs to cover them.+ if cohort._has_filter_type("behavioral") or behavioral_props:+ _validate_behavioral_cohort_for_feature_flag(+ cohort, behavioral_props, allow_realtime_backfilled=self._allow_realtime_backfilled)- except (ValueError, TypeError):- raise serializers.ValidationError(- detail=f"{prop.operator} operator requires numeric values",- code="invalid_value",- )-- semver_operators = (- PropertyOperator.SEMVER_EQ,- PropertyOperator.SEMVER_NEQ,- PropertyOperator.SEMVER_GT,- PropertyOperator.SEMVER_GTE,- PropertyOperator.SEMVER_LT,- PropertyOperator.SEMVER_LTE,- PropertyOperator.SEMVER_TILDE,- PropertyOperator.SEMVER_CARET,- PropertyOperator.SEMVER_WILDCARD,- )- if prop.operator in semver_operators:- if not isinstance(prop.value, str):- raise serializers.ValidationError(- detail=f"Invalid value for operator {prop.operator}: expected a semver string",- code="invalid_value",- )- try:- semver_value = prop.value- if str(prop.operator) == PropertyOperator.SEMVER_WILDCARD:- semver_value = semver_value.rstrip(".*")- parse_semver(semver_value)- except (ValueError, IndexError):- raise serializers.ValidationError(- detail=f"Invalid semver value for operator {prop.operator}: {prop.value}",- code="invalid_value",- )-- if prop.operator in (- PropertyOperator.ICONTAINS_MULTI,- PropertyOperator.NOT_ICONTAINS_MULTI,- ):- if not isinstance(prop.value, list):- raise serializers.ValidationError(- detail=f"{prop.operator} operator requires a list of values",- code="invalid_value",- )-- payloads = filters.get("payloads", {})+ except Cohort.DoesNotExist:+ raise serializers.ValidationError(+ detail=f"Cohort with id {cohort_id} does not exist",+ code="cohort_does_not_exist",+ )- if not isinstance(payloads, dict):- raise serializers.ValidationError("Payloads must be passed as a dictionary")+ self._reject_oversized_filters(merged)- for key, value in payloads.items():- try:- if isinstance(value, str):- # An incoming string is already the canonical stored form; just check it parses.- json.loads(value)- else:- # Normalize any non-string JSON value (objects, arrays, numbers, booleans, null)- # to a JSON string, matching what the UI sends.- payloads[key] = json.dumps(value)- except json.JSONDecodeError:- raise serializers.ValidationError("Payload value is not valid JSON")- except (TypeError, ValueError):- # Defensive: request bodies are JSON-parsed, so values are always JSON-native- # (str/int/float/bool/None/dict/list) and serializable. Unreachable via the API.- raise serializers.ValidationError("Payload value could not be serialized to JSON")-- if filters.get("multivariate"):- if not all(key in variants for key in payloads):- raise serializers.ValidationError("Payload keys must match a variant key for multivariate flags")- else:- if len(payloads) > 1 or any(key != "true" for key in payloads): # only expect one key- raise serializers.ValidationError("Payload keys must be 'true' for boolean flags")+ return merged- # Validate per-flag filter size+ def _reject_oversized_filters(self, filters: Any) -> None:filter_size = calculate_filter_size_bytes(filters)per_flag_limit = settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES@@ -1631,8 +1777,6 @@ class FeatureFlagSerializer(f"Please simplify conditions or reduce payload sizes.")- return filters-def _validate_flag_reference(self, flag_reference):"""Validate and convert flag reference to flag key."""from posthog.utils import safe_int@@ -1847,6 +1991,9 @@ class FeatureFlagSerializer(request=request,)+ if isinstance(self.initial_data, dict) and "filters" in self.initial_data:+ _count_filters_write_success(self, "create", request)+return instance@approval_gate(["feature_flag.enable", "feature_flag.disable", "feature_flag.update"])@@ -2081,6 +2228,9 @@ class FeatureFlagSerializer(request, instance.filters.get("payloads", {}))+ if isinstance(self.initial_data, dict) and "filters" in self.initial_data:+ _count_filters_write_success(self, "update", request)+return instancedef _discard_unchanged_stale_fields(self, validated_data: dict, original_flag: dict | None) -> dict:diff --git a/products/feature_flags/backend/api/filters_schema.py b/products/feature_flags/backend/api/filters_schema.pyindex d0c30efd2c43..65568d64f68b 100644--- a/products/feature_flags/backend/api/filters_schema.py+++ b/products/feature_flags/backend/api/filters_schema.py@@ -8,19 +8,9 @@ Rust poisons the whole team's flag cache, so these serializers reject exactly whreject: no DRF type coercion (`"true"` is not a bool, `"42"` is not an int, `NaN` is not avalid rollout percentage).-Modeled on the OpenAPI-only `FeatureFlagFiltersSchemaSerializer` in `posthog/api/documentation.py`-(which can't validate at runtime — it relies on `PolymorphicProxySerializer`). The two are meant-to converge: once this serializer is wired into `FeatureFlagSerializer` (phase 3 of #50084), it-becomes the OpenAPI source of truth and the documentation.py one is retired. Not wired in yet:-enforcement is gated on the `audit_flag_filters` management command reporting zero violations.--Phase 3 wiring notes:-- When `feature_flag.py` starts importing this module, move `FEATURE_FLAG_SUPPORTED_OPERATORS`- and `FEATURE_FLAG_OPERATOR_ALIASES` here and re-export from `feature_flag.py` to avoid an- import cycle.-- `type` and `operator` are collision-prone enum field names for drf-spectacular; before wiring- this serializer into `@extend_schema`, run `python manage.py find_enum_collisions` and add- `ENUM_NAME_OVERRIDES` entries as needed.+The runtime serializer validates the merged filters state in `FeatureFlagSerializer.validate_filters`.+The public OpenAPI schema stays permissive until enforcement defaults on, so generated clients+cannot reject inputs that the staged server rollout still accepts."""import json@@ -31,13 +21,53 @@ from typing import Any, ClassVar, Protocol, castimport structlogfrom rest_framework import serializers-from products.feature_flags.backend.api.feature_flag import (- FEATURE_FLAG_OPERATOR_ALIASES,- FEATURE_FLAG_SUPPORTED_OPERATORS,-)+from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORSlogger = structlog.get_logger(__name__)+# Operators the Rust feature-flag evaluation service supports (OperatorType in property_models.rs).+# None means "no operator specified" which defaults to exact.+FEATURE_FLAG_SUPPORTED_OPERATORS: frozenset[str | None] = frozenset(+ {+ None,+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "icontains_multi",+ "not_icontains_multi",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_eq",+ "semver_neq",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_after",+ "is_date_before",+ "in",+ "not_in",+ "flag_evaluates_to",+ }+ | set(STRING_PREFIX_SUFFIX_OPERATORS)+)++FEATURE_FLAG_OPERATOR_ALIASES: dict[str, str] = {+ "min": "gte",+ "max": "lte",+}+# The Rust PropertyType enum also accepts "person_metadata"; the locked inventory in #50084# deliberately excludes it. If the audit shows stored flags using it, amend the inventory in# the issue thread before adding it here.@@ -57,8 +87,12 @@ I64_MIN, I64_MAX = -(2**63), 2**63 - 1# Serializer-context keys shared with the audit command; constants so a typo on either side# fails loudly at import instead of silently under-reporting unknown keys.+MAX_LOGGED_UNKNOWN_KEYS = 20+MAX_LOGGED_UNKNOWN_KEY_CHARS = 100+UNKNOWN_KEYS_SINK_CONTEXT_KEY = "unknown_keys_sink"FLAG_ID_CONTEXT_KEY = "flag_id"+PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY = "preserve_unknown_keys"class UnknownKeySink(Protocol):@@ -73,14 +107,19 @@ def _record_dropped_unknown_keys(level: str, keys: Sequence[str], context: Mappisink: UnknownKeySink | None = context.get(UNKNOWN_KEYS_SINK_CONTEXT_KEY)flag_id: int | None = context.get(FLAG_ID_CONTEXT_KEY)if sink is not None:+ # The audit sink gets everything: it counts offline against a stored corpus, not+ # against request bodies, so there is no caller to flood it.sink.record(level=level, keys=keys, flag_id=flag_id)returnnon_legacy = [key for key in keys if not is_legacy_unknown_key(level, key)]if non_legacy:+ # Keys are caller-controlled and a request body can carry megabytes of them, so the+ # log line is capped in both dimensions. key_count keeps the true size visible.logger.warning("feature_flag_filters_unknown_keys_dropped",level=level,- keys=non_legacy,+ key_count=len(non_legacy),+ keys=[key[:MAX_LOGGED_UNKNOWN_KEY_CHARS] for key in non_legacy[:MAX_LOGGED_UNKNOWN_KEYS]],flag_id=flag_id,)@@ -96,12 +135,22 @@ class DropsUnknownKeysMixin:unknown_key_level: ClassVar[str]def to_internal_value(self, data: Any) -> Any:+ unknown_keys: list[str] = []if isinstance(data, dict):serializer = cast(serializers.Serializer, self)unknown_keys = sorted(set(data) - set(serializer.fields))if unknown_keys:_record_dropped_unknown_keys(self.unknown_key_level, unknown_keys, serializer.context)- return super().to_internal_value(data) # type: ignore[misc]+ validated_data = super().to_internal_value(data) # type: ignore[misc]+ if (+ isinstance(data, dict)+ and isinstance(validated_data, dict)+ and cast(serializers.Serializer, self).context.get(PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY)+ ):+ validated_data.update(+ {key: data[key] for key in unknown_keys if not is_legacy_unknown_key(self.unknown_key_level, key)}+ )+ return validated_dataclass StrictCharField(serializers.CharField):@@ -170,7 +219,7 @@ class FiniteFloatField(serializers.FloatField):"""def to_internal_value(self, data: Any) -> float:- if isinstance(data, bool) or not isinstance(data, (int, float)):+ if isinstance(data, bool) or not isinstance(data, int | float):self.fail("invalid")value = float(data)if not math.isfinite(value):@@ -219,6 +268,8 @@ class FlagPayloadsField(serializers.DictField):class FlagPropertySerializer(DropsUnknownKeysMixin, serializers.Serializer):+ """A property condition inside a release condition group."""+unknown_key_level = "property"key = PropertyKeyField(@@ -253,6 +304,33 @@ class FlagPropertySerializer(DropsUnknownKeysMixin, serializers.Serializer):allow_null=True,help_text="Whether the property condition is negated.",)+ # Display-only passthrough (#50084 inventory addendum): the UI stores these inside filters+ # and Rust round-trips them via its extras map, but this serializer drops undeclared keys,+ # so they must be declared to survive writes. Deliberately permissive: display data.+ # (`label` is also passthrough but is injected in get_fields — a class attribute named+ # `label` would shadow DRF's Field.label, the field's own display label, with an+ # incompatible type.)+ cohort_name = StrictCharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Display name of the referenced cohort. Injected on read and echoed back by clients.",+ )+ group_key_names = serializers.JSONField(+ required=False,+ allow_null=True,+ help_text="Display names for group keys, keyed by group key. Injected on read and echoed back by clients.",+ )++ def get_fields(self) -> dict[str, serializers.Field]:+ fields = super().get_fields()+ fields["label"] = StrictCharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Display-only label for this property filter, shown in the UI.",+ )+ return fieldsdef to_internal_value(self, data: Any) -> dict[str, Any]:# Canonicalize operator aliases before field validation so everything downstream@@ -267,6 +345,8 @@ class FlagPropertySerializer(DropsUnknownKeysMixin, serializers.Serializer):class FlagConditionGroupSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ """A release condition group: who the flag rolls out to, at what percentage."""+unknown_key_level = "group"# allow_null: Rust reads properties as Option<Vec<PropertyFilter>> with #[serde(default)],@@ -303,6 +383,34 @@ class FlagConditionGroupSerializer(DropsUnknownKeysMixin, serializers.Serializerhelp_text="Group type index for this condition set. Null means person-level aggregation; ""absent falls back to the flag-level value.",)+ # Display-only passthrough (#50084 inventory addendum) — see FlagPropertySerializer.+ description = StrictCharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Display-only description for this condition group, shown in the UI.",+ )+ sort_key = serializers.JSONField(+ required=False,+ allow_null=True,+ help_text="Opaque UI ordering key for this condition group (string or number). Preserved as-is.",+ )+ # Experiment freeze-exposure stamps (products/feature_flags/backend/facade/filters.py+ # restriction markers, written via update_flag): load-bearing, not display data —+ # Experiment.is_exposure_frozen and the unfreeze strip read them back from stored+ # filters, so dropping them as unknown keys would silently unfreeze every experiment.+ exposure_frozen = StrictBooleanField(+ required=False,+ allow_null=True,+ help_text="Set when an experiment froze exposure by narrowing this group to a snapshot cohort.",+ )+ exposure_frozen_cohort = StrictIntegerField(+ min_value=I64_MIN,+ max_value=I64_MAX,+ required=False,+ allow_null=True,+ help_text="ID of the snapshot cohort this group was narrowed to when experiment exposure was frozen.",+ )def validate_properties(self, value: list[dict[str, Any]] | None) -> list[dict[str, Any]]:# Null means "no properties" (Rust treats it like absent); normalize so cross-field@@ -311,9 +419,20 @@ class FlagConditionGroupSerializer(DropsUnknownKeysMixin, serializers.Serializerclass FlagMultivariateVariantSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ """A variant of a multivariate feature flag."""+unknown_key_level = "variant"- key = StrictCharField(help_text="Unique key for this variant.")+ # No charset rule, deliberately. The flag editor has restricted variant keys since the+ # multivariate UI shipped, but the API never has, and hundreds of stored flags rely on+ # that: variant keys double as config values (LLM routing keys like "provider/model-1.2")+ # and plenty carry spaces. Enforcing the form's charset here would make those flags+ # uneditable through every path their owners have left. Flag keys keep their charset —+ # that one is genuinely server-enforced.+ key = StrictCharField(+ max_length=400,+ help_text="Unique key for this variant. At most 400 characters.",+ )name = StrictCharField(required=False,allow_null=True,@@ -325,9 +444,18 @@ class FlagMultivariateVariantSerializer(DropsUnknownKeysMixin, serializers.Seriamax_value=100,help_text="Variant rollout percentage, between 0 and 100.",)+ # Display-only passthrough (#50084 inventory addendum) — see FlagPropertySerializer.+ description = StrictCharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Display-only description for this variant, shown in the UI.",+ )class FlagMultivariateSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ """Multivariate configuration for variant-based rollouts."""+unknown_key_level = "multivariate"variants = FlagMultivariateVariantSerializer(@@ -338,6 +466,8 @@ class FlagMultivariateSerializer(DropsUnknownKeysMixin, serializers.Serializer):class FlagHoldoutSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ """Experiment holdout configuration for a feature flag."""+unknown_key_level = "holdout"id = StrictIntegerField(@@ -353,6 +483,8 @@ class FlagHoldoutSerializer(DropsUnknownKeysMixin, serializers.Serializer):class FeatureFlagFiltersSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ """Feature flag targeting configuration: release condition groups, multivariate variants, and payloads."""+unknown_key_level = "filters"groups = FlagConditionGroupSerializer(diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 6304a4460064..5410c12604df 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -1286,6 +1286,14 @@ class OrganizationFeatureFlagView(# references, whose target IDs are project-specific. Both remaps mutate this dict, so# working on a per-target copy keeps one target's IDs from leaking into the next.filters = copy.deepcopy(source_flag.get_filters())+ # A copy replaces the target's filters; the flag serializer merges incoming filters+ # over the target's stored ones, so any top-level key the source omits would be+ # inherited from the flag being overwritten (a boolean source copied onto a+ # multivariate target would keep serving variants). Spell out the omitted keys.+ filters = {+ **dict.fromkeys(("multivariate", "payloads", "holdout", "feature_enrollment", "early_exit")),+ **filters,+ }# reference correct destination cohort ids in the flagfor group in filters.get("groups", []) or []:diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 59e20589edfd..933d4a7abe93 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -54,7 +54,12 @@ from products.cohorts.backend.models.util import CohortErrorCode, get_friendly_efrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, parse_created_by_ids+from products.feature_flags.backend.api.feature_flag import (+ FLAG_FILTERS_VIOLATION_COUNTER,+ FLAG_FILTERS_WRITE_COUNTER,+ FeatureFlagSerializer,+ parse_created_by_ids,+)from products.feature_flags.backend.encrypted_flag_payloads import (REDACTED_PAYLOAD_VALUE,flag_payload_codec,@@ -253,8 +258,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):response.json(),{"type": "validation_error",- "code": "invalid_value",- "detail": f"Invalid value for operator {operator}: ['@posthog.com']",+ "code": "cross_field.operator_requires_string_value",+ "detail": f"groups[0].properties[0].value: Operator {operator} requires a string value.","attr": "filters",},)@@ -323,8 +328,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):response.json(),{"type": "validation_error",- "code": "invalid_operator",- "detail": f"The '{operator}' operator is only valid for cohort properties, not 'person' properties.",+ "code": "cross_field.in_not_in_requires_cohort",+ "detail": f"groups[0].properties[0].operator: Operator {operator} is only supported on cohort properties.","attr": "filters",},)@@ -366,8 +371,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):response.json(),{"type": "validation_error",- "code": "invalid_operator",- "detail": f"Invalid operator: {operator}",+ "code": "structural.groups[].properties[].operator.invalid_choice",+ "detail": f'groups[0].properties[0].operator: "{operator}" is not a valid choice.',"attr": "filters",},)@@ -691,13 +696,13 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):@parameterized.expand([- ("false", False, "bool"),- ("true", True, "bool"),- ("string", "not_an_int", "str"),- ("float", 1.5, "float"),+ ("false", False),+ ("true", True),+ ("string", "not_an_int"),+ ("float", 1.5),])- def test_non_integer_aggregation_group_type_index_rejected(self, _name, bad_value, expected_type):+ def test_non_integer_aggregation_group_type_index_rejected(self, _name, bad_value):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",data={@@ -711,16 +716,16 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn(expected_type, response.json()["detail"])+ self.assertEqual(response.json()["detail"], "aggregation_group_type_index: A valid integer is required.")@parameterized.expand([- ("false", False, "bool"),- ("true", True, "bool"),- ("int", 42, "int"),+ ("false", False),+ ("true", True),+ ("int", 42),])- def test_non_string_group_variant_rejected(self, _name, bad_value, expected_type):+ def test_non_string_group_variant_rejected(self, _name, bad_value):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",data={@@ -733,7 +738,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn(expected_type, response.json()["detail"])+ self.assertEqual(response.json()["detail"], "groups[0].variant: Not a valid string.")def test_string_group_variant_preserved(self):response = self.client.post(@@ -847,13 +852,13 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):@parameterized.expand([- ("int", 1, "int"),- ("string_true", "true", "str"),- ("string_false", "false", "str"),- ("float", 1.5, "float"),+ ("int", 1),+ ("string_true", "true"),+ ("string_false", "false"),+ ("float", 1.5),])- def test_non_boolean_early_exit_rejected(self, _name, bad_value, expected_type):+ def test_non_boolean_early_exit_rejected(self, _name, bad_value):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",data={@@ -867,8 +872,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("early_exit must be a boolean", response.json()["detail"])- self.assertIn(expected_type, response.json()["detail"])+ self.assertIn("early_exit: Must be a valid boolean", response.json()["detail"])@parameterized.expand([@@ -917,7 +921,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("between 0 and 100", response.json()["detail"])+ self.assertIn("groups[0].rollout_percentage: Ensure this value is", response.json()["detail"])@parameterized.expand([@@ -974,13 +978,13 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):@parameterized.expand([- ("false", False, "bool"),- ("true", True, "bool"),- ("string", "not_an_int", "str"),- ("float", 1.5, "float"),+ ("false", False),+ ("true", True),+ ("string", "not_an_int"),+ ("float", 1.5),])- def test_non_integer_property_group_type_index_rejected(self, _name, bad_value, expected_type):+ def test_non_integer_property_group_type_index_rejected(self, _name, bad_value):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",data={@@ -1000,7 +1004,9 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn(expected_type, response.json()["detail"])+ self.assertEqual(+ response.json()["detail"], "groups[0].properties[0].group_type_index: A valid integer is required."+ )@freeze_time("2021-08-25T22:09:14.252Z")@patch("products.feature_flags.backend.api.feature_flag.report_user_action")@@ -1521,7 +1527,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json().get("type"), "validation_error")self.assertEqual(response.json().get("detail"),- "Invalid variant definitions: Variant rollout percentages must sum to 100.",+ f"multivariate.variants: Variant rollout percentages must sum to 100, got {float(75 + third_variant_rollout)}.",)def test_cant_update_multivariate_feature_flag_with_variant_rollout_not_100(self):@@ -1568,7 +1574,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json().get("type"), "validation_error")self.assertEqual(response.json().get("detail"),- "Invalid variant definitions: Variant rollout percentages must sum to 100.",+ "multivariate.variants: Variant rollout percentages must sum to 100, got 90.0.",)# Verify flag wasn't updated@@ -1638,7 +1644,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json().get("type"), "validation_error")self.assertEqual(response.json().get("detail"),- "Filters are not valid (variant override does not exist)",+ "groups[0].variant: Variant override 'unknown-variant' does not match any variant key.",)def test_cant_update_multivariate_feature_flag_with_invalid_variant_overrides(self):@@ -1720,7 +1726,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json().get("type"), "validation_error")self.assertEqual(response.json().get("detail"),- "Filters are not valid (variant override does not exist)",+ "groups[0].variant: Variant override 'unknown-variant' does not match any variant key.",)@patch("products.feature_flags.backend.api.feature_flag.report_user_action")@@ -5190,8 +5196,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertLessEqual({"type": "validation_error",- "code": "invalid_date",- "detail": f"Invalid date value: {invalid_date}",+ "code": "cross_field.date_value_not_parseable",+ "detail": f"groups[0].properties[0].value: Invalid date value: {invalid_date}.","attr": "filters",}.items(),resp.json().items(),@@ -5210,7 +5216,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):[{"key": "age", "type": "person", "value": "test", "operator": operator}],expected_status=status.HTTP_400_BAD_REQUEST,)- self.assertEqual(resp.json()["code"], "unsupported_operator")+ self.assertEqual(resp.json()["code"], "structural.groups[].properties[].operator.invalid_choice")self.assertIn(operator, resp.json()["detail"])@parameterized.expand(@@ -5237,7 +5243,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):format="json",)self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(resp.json()["code"], "unsupported_operator")+ self.assertEqual(resp.json()["code"], "structural.groups[].properties[].operator.invalid_choice")self.assertIn(operator, resp.json()["detail"])@parameterized.expand(@@ -5295,7 +5301,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):[{"key": "app_version", "type": "person", "value": value, "operator": operator}],expected_status=status.HTTP_400_BAD_REQUEST,)- self.assertEqual(resp.json()["code"], "invalid_value")+ self.assertEqual(resp.json()["code"], "cross_field.semver_value_invalid")@parameterized.expand([@@ -5330,7 +5336,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):[{"key": "url", "type": "person", "value": value, "operator": operator}],expected_status=status.HTTP_400_BAD_REQUEST,)- self.assertEqual(resp.json()["code"], "invalid_value")+ self.assertEqual(resp.json()["code"], "cross_field.operator_requires_list_value")self.assertIn("requires a list", resp.json()["detail"])@parameterized.expand(@@ -5508,7 +5514,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):expected_status=status.HTTP_400_BAD_REQUEST,)self.assertEqual(invalid_json_payload.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(invalid_json_payload.json()["detail"], "Payload value is not valid JSON")+ self.assertEqual(invalid_json_payload.json()["detail"], "payloads: Payload for key 'true' is not valid JSON.")non_string_payload = self._create_flag_with_properties("non-string-json-flag",@@ -5559,7 +5565,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):expected_status=status.HTTP_400_BAD_REQUEST,)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["detail"], "Payload value is not valid JSON")+ self.assertEqual(response.json()["detail"], "payloads: Payload for key 'true' is not valid JSON.")def test_creating_feature_flag_with_behavioral_cohort(self):cohort_valid_for_ff = Cohort.objects.create(@@ -6087,8 +6093,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):illegal_groups_request.json(),{"type": "validation_error",- "code": "invalid_input",- "detail": "Filters are not valid (group properties must match the condition set's group type)",+ "code": "cross_field.group_property_type_index_mismatch",+ "detail": "groups[0].properties[0]: Group properties must match the condition set's group type.","attr": "filters",},)@@ -6110,8 +6116,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):person_request.json(),{"type": "validation_error",- "code": "invalid_input",- "detail": "Filters are not valid (group-aggregated conditions can only use group properties)",+ "code": "cross_field.group_aggregation_property_type",+ "detail": "groups[0].properties[0]: Group-aggregated conditions can only use group properties.","attr": "filters",},)@@ -8096,6 +8102,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):"groups": [{"rollout_percentage": 65,+ "aggregation_group_type_index": 0,"properties": [{"key": "email",@@ -8231,7 +8238,9 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):},)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["detail"], "Invalid value for operator regex: 123")+ self.assertEqual(+ response.json()["detail"], "groups[0].properties[0].value: Operator regex requires a string value."+ )def test_can_create_flag_with_valid_regex(self):response = self.client.post(@@ -8573,6 +8582,193 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json()["keys"].get(str(flag.id)), "self-created-flag")+# Wiring guards for #50084 phase 3 enforcement. The validation rule matrix lives in+# test_filters_schema.py and test_filters_validation.py; these prove the endpoint is wired+# to the enforcing serializer and that merged-state PATCH semantics hold end to end.+class TestFeatureFlagFiltersEnforcement(APIBaseTest):+ 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)++ def test_post_with_structurally_invalid_filters_is_rejected(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"key": "bad-filters", "filters": {"groups": [{"rollout_percentage": "50"}]}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ body = response.json()+ self.assertEqual(body["attr"], "filters")+ self.assertEqual(body["code"], "structural.groups[].rollout_percentage.invalid")+ self.assertIn("groups[0].rollout_percentage", body["detail"])++ def test_patch_empty_filters_is_a_validated_noop(self):+ # Deliberately un-normalized: no aggregation_group_type_index at either level. A+ # fixture already carrying those keys cannot fail this assertion, since the only other+ # thing normalization does is coerce the rollout to a float, and 50 == 50.0 in Python.+ original: dict = {+ "groups": [{"properties": [], "rollout_percentage": 50}],+ "payloads": {"true": '"yes"'},+ }+ flag = self._create_flag_via_orm("noop-flag", original)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"filters": {}}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ flag.refresh_from_db()+ self.assertEqual(flag.filters, original)++ def test_patch_without_filters_leaves_them_untouched(self):+ # DRF hands DictField an empty dict rather than "absent" for form-encoded input, so a+ # request that never mentions filters still reaches validate_filters.+ original: dict = {"groups": [{"properties": [], "rollout_percentage": 50}]}+ flag = self._create_flag_via_orm("untouched-flag", original)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ data="name=renamed",+ content_type="application/x-www-form-urlencoded",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ flag.refresh_from_db()+ self.assertEqual(flag.name, "renamed")+ self.assertEqual(flag.filters, original)++ def test_patch_partial_filters_merges_with_stored_state(self):+ flag = self._create_flag_via_orm("merge-flag", {"groups": [{"properties": [], "rollout_percentage": 50}]})++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {"payloads": {"true": '"hello"'}}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ flag.refresh_from_db()+ self.assertEqual(flag.filters["payloads"], {"true": '"hello"'})+ self.assertEqual(flag.filters["groups"][0]["rollout_percentage"], 50)++ def test_patch_groups_absent_preserves_but_empty_list_clears_targeting(self):+ # Pins the locked #50084 merge asymmetry: absent `groups` must merge as "keep stored+ # targeting", while an explicit [] is clear-targeting.+ flag = self._create_flag_via_orm(+ "clear-targeting-flag", {"groups": [{"properties": [], "rollout_percentage": 50}]}+ )++ absent = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {"payloads": {"true": '"kept"'}}},+ format="json",+ )+ self.assertEqual(absent.status_code, status.HTTP_200_OK)+ flag.refresh_from_db()+ self.assertEqual(flag.filters["groups"][0]["rollout_percentage"], 50)++ cleared = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {"groups": []}},+ format="json",+ )+ self.assertEqual(cleared.status_code, status.HTTP_200_OK)+ flag.refresh_from_db()+ self.assertEqual(flag.filters["groups"], [])+ self.assertEqual(flag.filters["payloads"], {"true": '"kept"'})++ def test_stored_violating_flag_blocks_filters_edits_only(self):+ stored = {+ "groups": [+ {+ "properties": [{"key": "email", "type": "person", "operator": "is_contained_within", "value": "x"}],+ "rollout_percentage": None,+ }+ ]+ }+ flag = self._create_flag_via_orm("violating-flag", stored)++ read = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/")+ self.assertEqual(read.status_code, status.HTTP_200_OK)+ self.assertEqual(read.json()["filters"], stored)++ rename = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"name": "renamed"}, format="json"+ )+ self.assertEqual(rename.status_code, status.HTTP_200_OK)++ filters_edit = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {"payloads": {"true": '"x"'}}},+ format="json",+ )+ self.assertEqual(filters_edit.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(filters_edit.json()["attr"], "filters")++ @override_settings(FEATURE_FLAG_FILTERS_ENFORCEMENT=False)+ 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.+ 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}]},+ },+ },+ 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"], "")++ # But the pre-enforcement type/bounds checks stay active: cache-poisoning input is+ # rejected exactly as before enforcement shipped, switch or no switch.+ serde_unsafe = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"key": "poison-flag", "filters": {"groups": [{"properties": [], "rollout_percentage": "50"}]}},+ format="json",+ )+ self.assertEqual(serde_unsafe.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(+ serde_unsafe.json()["detail"], "groups[0].rollout_percentage must be a number or null, got str"+ )++ def test_display_passthrough_fields_round_trip(self):+ filters = {+ "groups": [+ {+ "properties": [+ {+ "key": "email",+ "type": "person",+ "operator": "icontains",+ "value": "@x.com",+ "label": "Email",+ }+ ],+ "rollout_percentage": None,+ "description": "First rollout cohort",+ "sort_key": "g1",+ }+ ],+ }++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"key": "passthrough-flag", "filters": filters},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ stored = FeatureFlag.objects.get(id=response.json()["id"]).filters+ group = stored["groups"][0]+ self.assertEqual(group["description"], "First rollout cohort")+ self.assertEqual(group["sort_key"], "g1")+ self.assertEqual(group["properties"][0]["label"], "Email")++class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):"""Orchestration tests for get_cohort_actors_for_feature_flag with the Rust batch@@ -13887,6 +14083,164 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):self.assertIn("error", response.json())+class TestFeatureFlagFiltersMetrics(APIBaseTest):+ def _write_count(self, operation: str, outcome: str) -> float:+ return FLAG_FILTERS_WRITE_COUNTER.labels(operation=operation, outcome=outcome, source="ui")._value.get()++ def test_write_outcomes_and_violations_are_counted(self) -> None:+ 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"+ )._value.get()++ ok = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"key": "metrics-ok", "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]}},+ format="json",+ )+ self.assertEqual(ok.status_code, status.HTTP_201_CREATED)++ bad = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"key": "metrics-bad", "filters": {"groups": [{"properties": [], "rollout_percentage": 150}]}},+ format="json",+ )+ self.assertEqual(bad.status_code, status.HTTP_400_BAD_REQUEST)++ self.assertEqual(self._write_count("create", "accepted"), accepted_before + 1)+ 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"+ )._value.get(),+ violation_before + 1,+ )++ @override_settings(FEATURE_FLAG_FILTERS_ENFORCEMENT=False)+ def test_bypassed_write_is_not_also_counted_as_accepted(self) -> None:+ accepted_before = self._write_count("create", "accepted")+ bypassed_before = self._write_count("create", "bypassed")++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "metrics-bypassed",+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {"variants": [{"key": "", "rollout_percentage": 100}]},+ },+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ 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()++ 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)++ def test_update_writes_are_counted_under_their_own_operation(self) -> None:+ # update() increments through a different call site than create(); without this the+ # operation="update" series could stop reporting and CI would stay green.+ flag = self._create_flag_via_orm("metrics-update", {"groups": [{"properties": [], "rollout_percentage": 10}]})+ accepted_before = self._write_count("update", "accepted")+ rejected_before = self._write_count("update", "rejected")++ ok = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {"groups": [{"properties": [], "rollout_percentage": 20}]}},+ format="json",+ )+ self.assertEqual(ok.status_code, status.HTTP_200_OK)++ bad = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {"groups": [{"properties": [], "rollout_percentage": 150}]}},+ format="json",+ )+ self.assertEqual(bad.status_code, status.HTTP_400_BAD_REQUEST)++ self.assertEqual(self._write_count("update", "accepted"), accepted_before + 1)+ self.assertEqual(self._write_count("update", "rejected"), rejected_before + 1)++ def test_preexisting_rejections_are_counted_apart_from_enforcement(self) -> None:+ # A missing cohort rejected long before this rollout, so counting it as `rejected`+ # would leave that series unreadable as "what enforcement rejects".+ rejected_before = self._write_count("create", "rejected")+ preexisting_before = self._write_count("create", "rejected_preexisting")++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "metrics-missing-cohort",+ "filters": {+ "groups": [+ {"properties": [{"key": "id", "type": "cohort", "value": 9999999}], "rollout_percentage": 100}+ ]+ },+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(self._write_count("create", "rejected_preexisting"), preexisting_before + 1)+ self.assertEqual(self._write_count("create", "rejected"), rejected_before)++ @override_settings(FEATURE_FLAG_FILTERS_ENFORCEMENT=False)+ def test_cross_field_bypass_is_logged_counted_and_persisted(self) -> None:+ # The branch production runs while the switch is off: structurally valid input with a+ # cross-field violation. It marks the write bypassed, counts the rule, and saves anyway.+ bypassed_before = self._write_count("create", "bypassed")+ rule_before = self._violation_count("cross_field", "cross_field.variant_rollout_sum_not_100", "create")++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "metrics-cross-field-bypass",+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 40}]},+ },+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ self.assertEqual(self._write_count("create", "bypassed"), bypassed_before + 1)+ self.assertEqual(+ self._violation_count("cross_field", "cross_field.variant_rollout_sum_not_100", "create"),+ rule_before + 1,+ )++ @override_settings(FEATURE_FLAG_FILTERS_ENFORCEMENT=False)+ def test_structural_failure_records_cross_field_as_not_evaluated(self) -> None:+ # Cross-field checks need structurally valid input, so they never run for these writes.+ # 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+ # 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/",+ {+ "key": "metrics-not-evaluated",+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {"variants": [{"key": "", "rollout_percentage": 100}]},+ },+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ self.assertEqual(self._violation_count("cross_field", "not_evaluated", "create"), not_evaluated_before + 1)++class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):def _link_flag(self, team: Team, linked_flag: dict[str, Any]) -> None:team.session_recording_linked_flag = linked_flagdiff --git a/products/feature_flags/backend/api/test/test_filters_schema.py b/products/feature_flags/backend/api/test/test_filters_schema.pyindex bfa824be9692..bf779a61982c 100644--- a/products/feature_flags/backend/api/test/test_filters_schema.py+++ b/products/feature_flags/backend/api/test/test_filters_schema.py@@ -7,10 +7,13 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom products.feature_flags.backend.api.filters_schema import (+ PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY,FeatureFlagFiltersSerializer,FlagConditionGroupSerializer,+ FlagMultivariateVariantSerializer,FlagPropertySerializer,)+from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUEVALID_PROPERTY: dict[str, Any] = {"key": "email", "type": "person", "operator": "icontains", "value": "@posthog.com"}@@ -261,6 +264,14 @@ class TestFiltersSchema(SimpleTestCase):assert serializer.is_valid(), serializer.errorsassert serializer.validated_data["payloads"] == {"true": expected}+ def test_redacted_payload_sentinel_passes_payload_validation(self) -> None:+ # Pins the contract merged-state PATCH validation depends on: the sentinel substituted+ # for stored ciphertext must be a JSON-parseable string, or every filters PATCH on+ # every encrypted-payloads flag 400s. See the comment on REDACTED_PAYLOAD_VALUE.+ serializer = FeatureFlagFiltersSerializer(data={"payloads": {"true": REDACTED_PAYLOAD_VALUE}})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["payloads"] == {"true": REDACTED_PAYLOAD_VALUE}+def test_null_group_properties_normalized_to_empty_list(self) -> None:serializer = FlagConditionGroupSerializer(data={"properties": None})assert serializer.is_valid(), serializer.errors@@ -288,15 +299,8 @@ class TestFiltersSchema(SimpleTestCase):@parameterized.expand([("filters", {"groups": [], "junk": 1}, ["junk"]),- (- "group",- {"groups": [{"properties": [], "description": "x", "sort_key": "y"}]},- [- "description",- "sort_key",- ],- ),- ("property", {"groups": [{"properties": [{**VALID_PROPERTY, "cohort_name": "x"}]}]}, ["cohort_name"]),+ ("group", {"groups": [{"properties": [], "junk_g": 1}]}, ["junk_g"]),+ ("property", {"groups": [{"properties": [{**VALID_PROPERTY, "junk_p": 1}]}]}, ["junk_p"]),("multivariate",{"multivariate": {"variants": [{"key": "a", "rollout_percentage": 100}], "junk_m": 1}},@@ -317,9 +321,91 @@ class TestFiltersSchema(SimpleTestCase):serializer = FeatureFlagFiltersSerializer(data=filters, context={"flag_id": 42})assert serializer.is_valid(), serializer.errorsmock_logger.warning.assert_called_once_with(- "feature_flag_filters_unknown_keys_dropped", level=level, keys=expected_keys, flag_id=42+ "feature_flag_filters_unknown_keys_dropped",+ level=level,+ key_count=len(expected_keys),+ keys=expected_keys,+ flag_id=42,)+ def test_log_only_mode_preserves_non_legacy_unknown_keys_at_every_level(self) -> None:+ filters = {+ "groups": [{"properties": [{**VALID_PROPERTY, "property_extra": {"a": 1}}], "group_extra": "g"}],+ "multivariate": {+ "variants": [{"key": "a", "rollout_percentage": 100, "variant_extra": [1]}],+ "multivariate_extra": True,+ },+ "holdout": {"id": 1, "exclusion_percentage": 10, "holdout_extra": "h"},+ "filters_extra": "f",+ "holdout_groups": [],+ }+ serializer = FeatureFlagFiltersSerializer(+ data=filters,+ context={PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY: True},+ )++ assert serializer.is_valid(), serializer.errors+ validated = serializer.validated_data+ assert validated["filters_extra"] == "f"+ assert validated["groups"][0]["group_extra"] == "g"+ assert validated["groups"][0]["properties"][0]["property_extra"] == {"a": 1}+ assert validated["multivariate"]["multivariate_extra"] is True+ assert validated["multivariate"]["variants"][0]["variant_extra"] == [1]+ assert validated["holdout"]["holdout_extra"] == "h"+ assert "holdout_groups" not in validated++ def test_display_passthrough_fields_survive_validation(self) -> None:+ # Guards the #50084 passthrough addendum: if any of these declared fields is removed,+ # enforcement silently deletes live UI display data (condition descriptions, cohort+ # names) from thousands of flags on their next edit.+ filters = {+ "groups": [+ {+ "properties": [+ {+ **VALID_PROPERTY,+ "label": "my label",+ "cohort_name": "my cohort",+ "group_key_names": {"k": "n"},+ }+ ],+ "description": "group description",+ "sort_key": "a1b2",+ }+ ],+ "multivariate": {+ "variants": [{"key": "control", "rollout_percentage": 100, "description": "variant description"}]+ },+ }+ serializer = FeatureFlagFiltersSerializer(data=filters, context={"flag_id": 1})+ assert serializer.is_valid(), serializer.errors+ group = serializer.validated_data["groups"][0]+ assert group["description"] == "group description"+ assert group["sort_key"] == "a1b2"+ prop = group["properties"][0]+ assert prop["label"] == "my label"+ assert prop["cohort_name"] == "my cohort"+ assert prop["group_key_names"] == {"k": "n"}+ assert serializer.validated_data["multivariate"]["variants"][0]["description"] == "variant description"++ @parameterized.expand(+ [+ ("simple", "control", True),+ # The API has never restricted the charset and stored flags depend on that: keys+ # double as config values, and hundreds carry spaces or other characters the flag+ # editor rejects. Only blank and over-length are structural violations.+ ("llm_routing_style", "provider/model-1.2", True),+ ("dots_underscores", "a.b_c-d", True),+ ("space", "foo bar", True),+ ("comma", "foo,bar", True),+ ("blank", "", False),+ ("too_long", "k" * 401, False),+ ]+ )+ def test_variant_key_length_and_blank(self, _name: str, key: str, valid: bool) -> None:+ serializer = FlagMultivariateVariantSerializer(data={"key": key, "rollout_percentage": 100})+ assert serializer.is_valid() is valid, serializer.errors+@patch("products.feature_flags.backend.api.filters_schema.logger")def test_sink_collects_unknown_keys_instead_of_logging(self, mock_logger: Any) -> None:recorded: list[dict[str, Any]] = []diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 09b6b824eec8..4eb3e9e493d5 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -469,10 +469,18 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"groups": [{"rollout_percentage": self.rollout_percentage_to_copy,+ "properties": [],"aggregation_group_type_index": None,}],"aggregation_group_type_index": None,+ # A copy replaces the target's filters, so the keys the source doesn't carry+ # are cleared explicitly instead of being inherited from the overwritten flag.+ "multivariate": None,+ "payloads": None,+ "holdout": None,+ "feature_enrollment": None,+ "early_exit": None,},"active": self.feature_flag_to_copy.active,"ensure_experience_continuity": self.feature_flag_to_copy.ensure_experience_continuity,@@ -595,10 +603,18 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"groups": [{"rollout_percentage": self.rollout_percentage_to_copy,+ "properties": [],"aggregation_group_type_index": None,}],"aggregation_group_type_index": None,+ # A copy replaces the target's filters, so the keys the source doesn't carry+ # are cleared explicitly instead of being inherited from the overwritten flag.+ "multivariate": None,+ "payloads": None,+ "holdout": None,+ "feature_enrollment": None,+ "early_exit": None,},"active": self.feature_flag_to_copy.active,"ensure_experience_continuity": self.feature_flag_to_copy.ensure_experience_continuity,@@ -782,10 +798,18 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"groups": [{"rollout_percentage": self.rollout_percentage_to_copy,+ "properties": [],"aggregation_group_type_index": None,}],"aggregation_group_type_index": None,+ # A copy replaces the target's filters, so the keys the source doesn't carry+ # are cleared explicitly instead of being inherited from the overwritten flag.+ "multivariate": None,+ "payloads": None,+ "holdout": None,+ "feature_enrollment": None,+ "early_exit": None,},"active": self.feature_flag_to_copy.active,"ensure_experience_continuity": self.feature_flag_to_copy.ensure_experience_continuity,diff --git a/products/feature_flags/backend/encrypted_flag_payloads.py b/products/feature_flags/backend/encrypted_flag_payloads.pyindex abced9bcd662..1b5bfb822eec 100644--- a/products/feature_flags/backend/encrypted_flag_payloads.py+++ b/products/feature_flags/backend/encrypted_flag_payloads.py@@ -7,6 +7,9 @@ from cryptography.fernet import Fernet, InvalidToken, MultiFernetfrom posthog.auth import PersonalAPIKeyAuthentication+# Must remain a JSON-parseable string (note the embedded quotes): merged-state filters+# validation substitutes this sentinel for stored ciphertext before structural validation,+# so a non-JSON value here would 400 every filters PATCH on every encrypted-payloads flag.REDACTED_PAYLOAD_VALUE = '"********* (encrypted)"'diff --git a/products/feature_flags/backend/filters_validation.py b/products/feature_flags/backend/filters_validation.pyindex c78d3cefeaa8..2fce61eed895 100644--- a/products/feature_flags/backend/filters_validation.py+++ b/products/feature_flags/backend/filters_validation.py@@ -9,8 +9,8 @@ size limits, feature gates) need DB or request state and stay inEvery check takes a filters dict that already passed `FeatureFlagFiltersSerializer` — typesare trusted, operators are canonical (aliases applied), payload values are JSON-encodedstrings — and returns violations instead of raising, so the `audit_flag_filters` management-command can report all of them per flag. `validate_cross_field_or_raise` is the fail-fast-wrapper for the write path (wired in a later phase).+command can report all of them per flag. The write path collects the same violations, then+reports or raises depending on the enforcement switch."""import re@@ -18,8 +18,6 @@ from collections.abc import Callable, Mappingfrom dataclasses import dataclassfrom typing import Any-from rest_framework import serializers-from rest_framework.exceptions import ErrorDetailfrom rest_framework.settings import api_settingsfrom posthog.hogql.property import parse_semver@@ -300,15 +298,6 @@ def collect_cross_field_violations(filters: Mapping[str, Any]) -> list[Violationreturn [violation for check in CROSS_FIELD_CHECKS for violation in check(filters)]-def validate_cross_field_or_raise(filters: Mapping[str, Any]) -> None:- """Fail-fast wrapper over the same collectors, for the write path."""- violations = collect_cross_field_violations(filters)- if violations:- raise serializers.ValidationError(- [ErrorDetail(f"{violation.path}: {violation.message}", code=violation.rule_id) for violation in violations]- )--_LIST_INDEX_RE = re.compile(r"\[\d+\]")diff --git a/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py b/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.pyindex f854177d3d56..5f3387e56c0b 100644--- a/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py+++ b/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py@@ -85,7 +85,7 @@ class TestAuditFlagFilters(BaseTest):junk = self._create_flag("junk", {"groups": [], "junk": 1})prop_level = self._create_flag("prop-level",- {"groups": [{"properties": [{"key": "k", "type": "person", "value": "x", "cohort_name": "c"}]}]},+ {"groups": [{"properties": [{"key": "k", "type": "person", "value": "x", "junk_p": "c"}]}]},)report = self._run()@@ -96,17 +96,17 @@ class TestAuditFlagFilters(BaseTest):assert unknown_by_key[("filters", "holdout_groups")]["sample_flag_ids"] == [legacy.id]assert unknown_by_key[("filters", "junk")]["legacy"] is Falseassert unknown_by_key[("filters", "junk")]["sample_flag_ids"] == [junk.id]- assert unknown_by_key[("property", "cohort_name")]["sample_flag_ids"] == [prop_level.id]+ assert unknown_by_key[("property", "junk_p")]["sample_flag_ids"] == [prop_level.id]def test_unknown_key_counted_once_per_flag(self) -> None:self._create_flag("two-groups",- {"groups": [{"properties": [], "sort_key": "a"}, {"properties": [], "sort_key": "b"}]},+ {"groups": [{"properties": [], "junk_g": "a"}, {"properties": [], "junk_g": "b"}]},)report = self._run()- entry = next(e for e in report["unknown_keys"] if e["key"] == "sort_key")+ entry = next(e for e in report["unknown_keys"] if e["key"] == "junk_g")assert entry["flags_affected"] == 1@patch("products.feature_flags.backend.api.filters_schema.logger")diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 2e990746d2f1..8eb6f1427963 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -74,11 +74,17 @@ def build_scheduled_change_serializer_data(flag: "FeatureFlag", payload: dict[streturn Nonenew_variants = value.get("variants", [])new_payloads = value.get("payloads", {})- # Deep-copy before mutating: current_filters is flag.filters (a live reference), so assigning- # into its nested multivariate dict would mutate the flag's pre-change state in place and- # defeat the approval gate's old-vs-new comparison.- updated_multivariate = copy.deepcopy(current_filters.get("multivariate", {}))- updated_multivariate["variants"] = new_variants+ if not new_variants:+ # Clearing variants makes the flag boolean; the canonical stored shape for that is+ # multivariate: null. {"variants": []} is an invalid shape (#50084) that migration+ # 0007 cleaned and the filters serializer rejects.+ updated_multivariate = None+ else:+ # Deep-copy before mutating: current_filters is flag.filters (a live reference), so+ # assigning into its nested multivariate dict would mutate the flag's pre-change state+ # in place and defeat the approval gate's old-vs-new comparison.+ updated_multivariate = copy.deepcopy(current_filters.get("multivariate") or {})+ updated_multivariate["variants"] = new_variantsreturn {"filters": {**current_filters,diff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.pyindex 7a90bd5a9d34..1348b850dc41 100644--- a/products/feature_flags/backend/test/test_filters_validation.py+++ b/products/feature_flags/backend/test/test_filters_validation.py@@ -1,5 +1,3 @@-import copy-from types import SimpleNamespacefrom typing import Anyfrom django.test import SimpleTestCase@@ -8,7 +6,8 @@ from parameterized import parameterizedfrom rest_framework import serializersfrom rest_framework.exceptions import ErrorDetail-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.api.feature_flag import _reject_serde_unsafe_filters+from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUEfrom products.feature_flags.backend.filters_validation import (CROSS_FIELD_CHECKS,Violation,@@ -16,7 +15,6 @@ from products.feature_flags.backend.filters_validation import (collect_cross_field_violations,collect_filters_violations,flatten_structural_errors,- validate_cross_field_or_raise,)@@ -269,132 +267,110 @@ class TestFiltersValidation(SimpleTestCase):cross_field = collect_filters_violations({"multivariate": _multivariate(("a", 50))})assert [violation.rule_id for violation in cross_field] == ["cross_field.variant_rollout_sum_not_100"]- def test_validate_cross_field_or_raise(self) -> None:- validate_cross_field_or_raise({"groups": []})+ def test_groups_non_empty_is_a_create_only_rule(self) -> None:+ # The POST/PATCH asymmetry is locked on #50084: stored/patched flags may have empty+ # groups, so the rule must stay out of CROSS_FIELD_CHECKS (and out of the audit).+ assert check_groups_non_empty_for_create not in CROSS_FIELD_CHECKS+ assert collect_cross_field_violations({"groups": []}) == []+ assert [violation.rule_id for violation in check_groups_non_empty_for_create({"groups": []})] == [+ "contextual.groups_empty_on_create"+ ]+ assert check_groups_non_empty_for_create({"groups": [{"properties": []}]}) == []- with self.assertRaises(serializers.ValidationError) as ctx:- validate_cross_field_or_raise({"multivariate": _multivariate(("a", 50))})- detail = ctx.exception.detail- assert isinstance(detail, list) and isinstance(detail[0], ErrorDetail)- assert detail[0].code == "cross_field.variant_rollout_sum_not_100"- # Parity guard for the phases 1-2 window: the cross-field rules mirror logic that still- # lives in validate_filters, and both run independently until the phase 3 swap. This- # corpus exercises the mirrored rules through both paths and asserts the same- # accept/reject verdict, so an edit to either side that changes a shared rule fails here- # instead of silently making the audit measure a different rule set than the write path.- # Scope: only rules that exist on both sides, with structurally valid input, and no- # cohort/flag properties or early_exit (those branches of validate_filters need DB or- # org context). Message text and error codes are documented to differ.+class TestRejectSerdeUnsafeFilters(SimpleTestCase):+ # The only cache-poisoning guard that runs while the enforcement switch is off, and the+ # structural tier shadows it once the switch is on, so it needs its own coverage: nothing+ # else in the suite exercises these rules.@parameterized.expand([- ("variant_sum_100_accepted", {"groups": [{}], "multivariate": _multivariate(("a", 50), ("b", 50))}, True),- ("variant_sum_50_rejected", {"groups": [{}], "multivariate": _multivariate(("a", 50))}, False),- (- "variant_override_valid",- {"groups": [{"variant": "a"}], "multivariate": _multivariate(("a", 100))},- True,- ),- (- "variant_override_dangling",- {"groups": [{"variant": "b"}], "multivariate": _multivariate(("a", 100))},- False,- ),- ("in_on_person_rejected", {"groups": [{"properties": [_person_prop(operator="in", value=[1])]}]}, False),- (- "regex_string_accepted",- {"groups": [{"properties": [_person_prop(operator="regex", value="^a+$")]}]},- True,- ),- ("regex_numeric_rejected", {"groups": [{"properties": [_person_prop(operator="regex", value=5)]}]}, False),- ("gt_string_accepted", {"groups": [{"properties": [_person_prop(operator="gt", value="5")]}]}, True),- ("gt_numeric_rejected", {"groups": [{"properties": [_person_prop(operator="gt", value=5)]}]}, False),- (- "min_alias_string_accepted",- {"groups": [{"properties": [_person_prop(operator="min", value="5")]}]},- True,- ),- (- "date_relative_accepted",- {"groups": [{"properties": [_person_prop(operator="is_date_after", value="-30d")]}]},- True,- ),- (- "date_junk_rejected",- {"groups": [{"properties": [_person_prop(operator="is_date_after", value="not a date")]}]},- False,- ),- (- "semver_valid_accepted",- {"groups": [{"properties": [_person_prop(operator="semver_gt", value="1.2.3")]}]},- True,- ),- (- "semver_junk_rejected",- {"groups": [{"properties": [_person_prop(operator="semver_gt", value="abc")]}]},- False,- ),- (- "multi_contains_list_accepted",- {"groups": [{"properties": [_person_prop(operator="icontains_multi", value=["a"])]}]},- True,- ),- (- "multi_contains_string_rejected",- {"groups": [{"properties": [_person_prop(operator="icontains_multi", value="a")]}]},- False,- ),- (- "person_agg_group_property_rejected",- {"groups": [{"properties": [{"key": "k", "type": "group", "group_type_index": 0, "value": "x"}]}]},- False,- ),- (- "group_agg_matching_index_accepted",+ ("filters_not_dict", "not a dict"),+ ("agg_index_bool", {"aggregation_group_type_index": True}),+ ("agg_index_string", {"aggregation_group_type_index": "0"}),+ ("agg_index_over_i32", {"aggregation_group_type_index": 2**31}),+ ("early_exit_int", {"early_exit": 1}),+ ("feature_enrollment_string", {"feature_enrollment": "true"}),+ ("holdout_not_dict", {"holdout": []}),+ ("holdout_id_missing", {"holdout": {"exclusion_percentage": 10}}),+ ("holdout_id_over_i64", {"holdout": {"id": 2**63, "exclusion_percentage": 10}}),+ ("holdout_exclusion_missing", {"holdout": {"id": 1}}),+ ("holdout_exclusion_string", {"holdout": {"id": 1, "exclusion_percentage": "10"}}),+ ("groups_not_list", {"groups": {}}),+ ("group_not_dict", {"groups": ["x"]}),+ ("group_variant_int", {"groups": [{"variant": 1}]}),+ ("group_rollout_string", {"groups": [{"rollout_percentage": "50"}]}),+ ("group_rollout_bool", {"groups": [{"rollout_percentage": True}]}),+ ("group_rollout_nan", {"groups": [{"rollout_percentage": float("nan")}]}),+ ("group_rollout_over_100", {"groups": [{"rollout_percentage": 150}]}),+ ("group_agg_index_bool", {"groups": [{"aggregation_group_type_index": False}]}),+ ("group_agg_index_under_i32", {"groups": [{"aggregation_group_type_index": -(2**31) - 1}]}),+ ("properties_not_list", {"groups": [{"properties": {}}]}),+ ("property_not_dict", {"groups": [{"properties": ["x"]}]}),+ ("property_group_type_index_string", {"groups": [{"properties": [{"group_type_index": "1"}]}]}),+ ("property_group_type_index_over_i32", {"groups": [{"properties": [{"group_type_index": 2**31}]}]}),+ ("property_negation_string", {"groups": [{"properties": [{"negation": "false"}]}]}),+ ("property_operator_unknown", {"groups": [{"properties": [{"operator": "does not equal"}]}]}),+ ("property_operator_unhashable", {"groups": [{"properties": [{"operator": []}]}]}),+ ("property_type_unknown", {"groups": [{"properties": [{"key": "k", "type": "banana"}]}]}),+ ("property_type_not_string", {"groups": [{"properties": [{"key": "k", "type": 1}]}]}),+ # Rust has no `event` variant, so one of these fails the team's whole cached set.+ ("property_type_event", {"groups": [{"properties": [{"key": "k", "type": "event"}]}]}),+ ("property_type_missing", {"groups": [{"properties": [{"key": "k"}]}]}),+ ("property_empty", {"groups": [{"properties": [{}]}]}),+ ("property_key_missing", {"groups": [{"properties": [{"type": "person"}]}]}),+ ("property_key_null", {"groups": [{"properties": [{"key": None, "type": "person"}]}]}),+ ("property_key_bool", {"groups": [{"properties": [{"key": True, "type": "person"}]}]}),+ ("property_key_list", {"groups": [{"properties": [{"key": [], "type": "person"}]}]}),+ ("multivariate_not_dict", {"multivariate": []}),+ ("multivariate_variants_missing", {"multivariate": {}}),+ ("multivariate_variants_null", {"multivariate": {"variants": None}}),+ ("variants_not_list", {"multivariate": {"variants": {}}}),+ ("variant_not_dict", {"multivariate": {"variants": ["x"]}}),+ ("variant_rollout_null", {"multivariate": {"variants": [{"key": "a", "rollout_percentage": None}]}}),+ ("variant_key_missing", {"multivariate": {"variants": [{"rollout_percentage": 100}]}}),+ ("variant_key_not_string", {"multivariate": {"variants": [{"key": 1, "rollout_percentage": 100}]}}),+ (+ "variant_name_not_string",+ {"multivariate": {"variants": [{"key": "a", "name": 1, "rollout_percentage": 100}]}},+ ),+ ("payloads_not_dict", {"payloads": []}),+ ("payload_string_not_json", {"payloads": {"true": "not json"}}),+ ]+ )+ def test_rejects_what_poisons_the_flag_cache(self, _name: str, filters: Any) -> None:+ with self.assertRaises(serializers.ValidationError):+ _reject_serde_unsafe_filters(filters)++ @parameterized.expand(+ [+ ("empty", {}),+ ("alias_operator", {"groups": [{"properties": [{"key": "k", "type": "person", "operator": "min"}]}]}),+ # Rust deserializes person_metadata; the structural tier narrows to four types,+ # but that is a policy choice rather than something serde rejects.+ ("person_metadata_type", {"groups": [{"properties": [{"key": "k", "type": "person_metadata"}]}]}),+ ("operator_absent", {"groups": [{"properties": [{"key": "x", "type": "person"}]}]}),+ # deserialize_key accepts a JSON number and normalizes it to a string.+ ("numeric_key", {"groups": [{"properties": [{"key": 226357, "type": "flag"}]}]}),+ ("payload_dict_value", {"payloads": {"true": {"a": 1}}}),+ ("payload_nan_token", {"payloads": {"true": "NaN"}}),+ ("redacted_payload_sentinel", {"payloads": {"true": REDACTED_PAYLOAD_VALUE}}),+ ("holdout_exclusion_clamped_by_rust", {"holdout": {"id": 1, "exclusion_percentage": 150}}),+ (+ "well_formed",{"groups": [{- "aggregation_group_type_index": 1,- "properties": [- {"key": "k", "type": "group", "group_type_index": 1, "operator": "exact", "value": "x"}- ],+ "properties": [{"key": "email", "type": "person", "operator": "icontains", "value": "@x"}],+ "rollout_percentage": 50,}- ]+ ],+ "multivariate": {"variants": [{"key": "a", "rollout_percentage": 100}]},+ "payloads": {"a": '"p"'},+ "feature_enrollment": False,+ "holdout": {"id": 1, "exclusion_percentage": 10},},- True,- ),- (- "payload_key_not_variant_rejected",- {"groups": [{}], "multivariate": _multivariate(("a", 100)), "payloads": {"b": "1"}},- False,),- ("boolean_payload_false_key_rejected", {"groups": [{}], "payloads": {"false": "1"}}, False),- ("empty_groups_rejected_on_create", {"groups": []}, False),])- def test_write_path_parity(self, _name: str, filters: dict[str, Any], expected_accept: bool) -> None:- live_serializer = FeatureFlagSerializer(- data={}, context={"request": SimpleNamespace(method="POST"), "project_id": 1}- )- try:- live_serializer.validate_filters(copy.deepcopy(filters))- live_accepts = True- except serializers.ValidationError:- live_accepts = False-- working = copy.deepcopy(filters)- violations = collect_filters_violations(working) or check_groups_non_empty_for_create(working)- new_accepts = not violations-- assert live_accepts == expected_accept- assert new_accepts == expected_accept, violations-- def test_groups_non_empty_is_a_create_only_rule(self) -> None:- # The POST/PATCH asymmetry is locked on #50084: stored/patched flags may have empty- # groups, so the rule must stay out of CROSS_FIELD_CHECKS (and out of the audit).- assert check_groups_non_empty_for_create not in CROSS_FIELD_CHECKS- assert collect_cross_field_violations({"groups": []}) == []- assert [violation.rule_id for violation in check_groups_non_empty_for_create({"groups": []})] == [- "contextual.groups_empty_on_create"- ]- assert check_groups_non_empty_for_create({"groups": [{"properties": []}]}) == []+ def test_accepts_what_master_accepted(self, _name: str, filters: Any) -> None:+ _reject_serde_unsafe_filters(filters)diff --git a/rust/feature-flags/src/properties/property_models.rs b/rust/feature-flags/src/properties/property_models.rsindex 1424e994746c..4d1d0ad40dc7 100644--- a/rust/feature-flags/src/properties/property_models.rs+++ b/rust/feature-flags/src/properties/property_models.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-// Keep in sync with FEATURE_FLAG_SUPPORTED_OPERATORS in-// products/feature_flags/backend/api/feature_flag.py (mirrored by the filters serializer in-// products/feature_flags/backend/api/filters_schema.py — issue #50084). This enum is+// Keep in sync with FEATURE_FLAG_SUPPORTED_OPERATORS, defined in+// products/feature_flags/backend/api/filters_schema.py (used there by the filters serializer+// and by the write-path serde guard in feature_flag.py — issue #50084). This enum is// deliberately a superset: cohort filters don't go through flag-level operator validation,// so operators the cohort UI allows (between/not_between, and the min/max aliases mirroring// FEATURE_FLAG_OPERATOR_ALIASES) must deserialize here even though the flag API rejects them.