:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(feature_flags): add flag filters validators and audit command (#72405)
Patricioa03d9af0223b
diff --git a/products/feature_flags/backend/api/filters_schema.py b/products/feature_flags/backend/api/filters_schema.pynew file mode 100644index 000000000000..d0c30efd2c43--- /dev/null+++ b/products/feature_flags/backend/api/filters_schema.py@@ -0,0 +1,405 @@+"""Structural validation for the `FeatureFlag.filters` JSON (issue #50084, structural tier).++This is the runtime Python mirror of the Rust flag structs — the shapes here must stay in+sync with `rust/feature-flags/src/flags/flag_models.rs` (`FlagFilters`, `FlagPropertyGroup`,+`MultivariateFlagVariant`, `Holdout`) and `rust/feature-flags/src/properties/property_models.rs`+(`PropertyFilter`, `OperatorType`, `PropertyType`). A stored filters value that fails serde in+Rust poisons the whole team's flag cache, so these serializers reject exactly what serde would+reject: no DRF type coercion (`"true"` is not a bool, `"42"` is not an int, `NaN` is not a+valid 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.+"""++import json+import math+from collections.abc import Mapping, Sequence+from typing import Any, ClassVar, Protocol, cast++import structlog+from rest_framework import serializers++from products.feature_flags.backend.api.feature_flag import (+ FEATURE_FLAG_OPERATOR_ALIASES,+ FEATURE_FLAG_SUPPORTED_OPERATORS,+)++logger = structlog.get_logger(__name__)++# 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.+FEATURE_FLAG_PROPERTY_TYPES: tuple[str, ...] = ("person", "cohort", "group", "flag")++FEATURE_FLAG_OPERATOR_CHOICES: list[str] = sorted(op for op in FEATURE_FLAG_SUPPORTED_OPERATORS if op is not None)++# Legacy keys that predate `holdout`; stored flags still carry them and read-modify-write+# clients echo them back, so dropping them is expected and not worth a log line.+LEGACY_UNKNOWN_FILTER_KEYS: frozenset[str] = frozenset({"holdout_groups", "super_groups"})++# Rust i32 / i64 bounds. Integers outside these ranges pass Python validation but fail serde+# deserialization — exactly the cache-poisoning class this module exists to stop.+I32_MIN, I32_MAX = -(2**31), 2**31 - 1+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.+UNKNOWN_KEYS_SINK_CONTEXT_KEY = "unknown_keys_sink"+FLAG_ID_CONTEXT_KEY = "flag_id"+++class UnknownKeySink(Protocol):+ def record(self, *, level: str, keys: Sequence[str], flag_id: int | None) -> None: ...+++def is_legacy_unknown_key(level: str, key: str) -> bool:+ return level == "filters" and key in LEGACY_UNKNOWN_FILTER_KEYS+++def _record_dropped_unknown_keys(level: str, keys: Sequence[str], context: Mapping[str, Any]) -> None:+ sink: UnknownKeySink | None = context.get(UNKNOWN_KEYS_SINK_CONTEXT_KEY)+ flag_id: int | None = context.get(FLAG_ID_CONTEXT_KEY)+ if sink is not None:+ sink.record(level=level, keys=keys, flag_id=flag_id)+ return+ non_legacy = [key for key in keys if not is_legacy_unknown_key(level, key)]+ if non_legacy:+ logger.warning(+ "feature_flag_filters_unknown_keys_dropped",+ level=level,+ keys=non_legacy,+ flag_id=flag_id,+ )+++class DropsUnknownKeysMixin:+ """DRF drops keys without a declared field silently; this makes the drop observable.++ During an audit run an `unknown_keys_sink` in the serializer context collects them;+ otherwise non-legacy unknown keys are logged so we learn whether junk keys happen in+ the wild before enforcement flips on.+ """++ unknown_key_level: ClassVar[str]++ def to_internal_value(self, data: Any) -> Any:+ 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]+++class StrictCharField(serializers.CharField):+ """CharField without cross-type coercion: Rust `String` fields reject JSON numbers."""++ def __init__(self, **kwargs: Any) -> None:+ # Validate, don't mutate: stored values must round-trip unchanged.+ kwargs.setdefault("trim_whitespace", False)+ super().__init__(**kwargs)++ def to_internal_value(self, data: Any) -> str:+ if not isinstance(data, str):+ self.fail("invalid")+ return super().to_internal_value(data)+++class StrictBooleanField(serializers.BooleanField):+ """BooleanField without coercion: Rust `Option<bool>` rejects "true", 1, etc."""++ def to_internal_value(self, data: Any) -> bool:+ if not isinstance(data, bool):+ self.fail("invalid", input=data)+ return data+++class StrictIntegerField(serializers.IntegerField):+ """IntegerField without coercion: Rust `i32`/`i64` reject "42", 42.0, and bools.++ min_value/max_value are enforced by DRF's validators, which run after this method.+ """++ def to_internal_value(self, data: Any) -> int:+ if isinstance(data, bool) or not isinstance(data, int):+ self.fail("invalid")+ return data+++class PropertyKeyField(serializers.CharField):+ """Property keys are strings, but JSON numbers are accepted and normalized to strings.++ Mirrors Rust's `deserialize_key` on `PropertyFilter.key`: flag-dependency keys are flag+ IDs and the API has persisted them as raw JSON numbers, so serde accepts both forms and+ normalizes to a string. Rejecting numbers here would flag stored data that evaluates fine+ and would 400 read-modify-write PATCHes that echo it back.+ """++ def __init__(self, **kwargs: Any) -> None:+ kwargs.setdefault("trim_whitespace", False)+ super().__init__(**kwargs)++ def to_internal_value(self, data: Any) -> str:+ if isinstance(data, bool):+ self.fail("invalid")+ if isinstance(data, int) or (isinstance(data, float) and math.isfinite(data)):+ data = str(data)+ if not isinstance(data, str):+ self.fail("invalid")+ return super().to_internal_value(data)+++class FiniteFloatField(serializers.FloatField):+ """FloatField that rejects bools, numeric strings, and non-finite values.++ JSON parsed with stdlib `json.loads` can contain NaN/Infinity tokens, which compare+ False against min_value/max_value and then crash percentage math downstream.+ """++ def to_internal_value(self, data: Any) -> float:+ if isinstance(data, bool) or not isinstance(data, (int, float)):+ self.fail("invalid")+ value = float(data)+ if not math.isfinite(value):+ self.fail("invalid")+ return value+++def _reject_json_constant(name: str) -> None:+ raise ValueError(f"non-RFC JSON constant {name}")+++class FlagPayloadsField(serializers.DictField):+ """Payloads stay lenient at the edge: any JSON value is accepted and normalized to a+ JSON-encoded string, so everything past this boundary (cross-field validators, storage,+ the Rust service) only ever sees JSON-encoded strings. Mirrors the normalization in+ `FeatureFlagSerializer.validate_filters`; tightening the public contract to+ strings-only would be a breaking change and is out of scope for #50084.++ One deliberate divergence from the live normalization: NaN/Infinity are rejected. stdlib+ json accepts them, but they produce non-RFC payload strings that strict parsers+ (serde_json, SDK JSON.parse) fail on.+ """++ def to_internal_value(self, data: Any) -> dict[str, str]:+ if not isinstance(data, dict):+ self.fail("not_a_dict", input_type=type(data).__name__)+ normalized: dict[str, str] = {}+ errors: list[str] = []+ for key, value in data.items():+ try:+ if isinstance(value, str):+ # An incoming string is already the canonical stored form; just check it parses.+ json.loads(value, parse_constant=_reject_json_constant)+ normalized[key] = value+ else:+ normalized[key] = json.dumps(value, allow_nan=False)+ except json.JSONDecodeError:+ errors.append(f"Payload for key '{key}' is not valid JSON.")+ except (TypeError, ValueError):+ errors.append(f"Payload for key '{key}' is not valid strict JSON (NaN/Infinity not allowed).")+ if errors:+ # Flat (not keyed by payload key) so the audit's rule id stays stable instead of+ # exploding per variant key.+ raise serializers.ValidationError(errors, code="invalid_payload_json")+ return normalized+++class FlagPropertySerializer(DropsUnknownKeysMixin, serializers.Serializer):+ unknown_key_level = "property"++ key = PropertyKeyField(+ help_text="Property key used in this feature flag condition. Numbers are normalized to strings."+ )+ value = serializers.JSONField(+ required=False,+ allow_null=True,+ # Deliberately any JSON value: which shapes are valid depends on `operator`, and that+ # dependency is enforced in the cross-field tier (filters_validation.py), not here.+ help_text="Comparison value for the property filter. Valid shapes depend on the operator.",+ )+ type = serializers.ChoiceField(+ choices=FEATURE_FLAG_PROPERTY_TYPES,+ help_text="Property filter type. One of 'person', 'cohort', 'group', or 'flag'.",+ )+ operator = serializers.ChoiceField(+ choices=FEATURE_FLAG_OPERATOR_CHOICES,+ required=False,+ allow_null=True,+ help_text="Operator used to compare the property value. Null means exact match.",+ )+ group_type_index = StrictIntegerField(+ min_value=I32_MIN,+ max_value=I32_MAX,+ required=False,+ allow_null=True,+ help_text="Group type index when using group-based filters.",+ )+ negation = StrictBooleanField(+ required=False,+ allow_null=True,+ help_text="Whether the property condition is negated.",+ )++ def to_internal_value(self, data: Any) -> dict[str, Any]:+ # Canonicalize operator aliases before field validation so everything downstream+ # (the operator ChoiceField, cross-field validators, storage) only ever sees+ # canonical operators. The isinstance guard matters: an unhashable operator (list/dict+ # in stored junk) would raise TypeError on the dict lookup instead of failing cleanly+ # in the ChoiceField.+ operator = data.get("operator") if isinstance(data, dict) else None+ if isinstance(operator, str) and operator in FEATURE_FLAG_OPERATOR_ALIASES:+ data = {**data, "operator": FEATURE_FLAG_OPERATOR_ALIASES[operator]}+ return super().to_internal_value(data)+++class FlagConditionGroupSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ unknown_key_level = "group"++ # allow_null: Rust reads properties as Option<Vec<PropertyFilter>> with #[serde(default)],+ # so an explicit JSON null deserializes fine (treated like absent) and must not audit as+ # a violation.+ properties = FlagPropertySerializer(+ many=True,+ required=False,+ allow_null=True,+ default=list,+ help_text="Property conditions for this release condition group.",+ )+ rollout_percentage = FiniteFloatField(+ min_value=0,+ max_value=100,+ required=False,+ allow_null=True,+ help_text="Rollout percentage for this release condition group, between 0 and 100.",+ )+ variant = StrictCharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Variant key override for multivariate flags.",+ )+ # No default here: an absent key falls back to the flag-level aggregation while an explicit+ # null means person aggregation (Rust models this as Option<Option<i32>>). Injecting a+ # default would erase that distinction.+ aggregation_group_type_index = StrictIntegerField(+ min_value=I32_MIN,+ max_value=I32_MAX,+ required=False,+ allow_null=True,+ help_text="Group type index for this condition set. Null means person-level aggregation; "+ "absent falls back to the flag-level value.",+ )++ 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+ # checks can iterate without a None guard.+ return value if value is not None else []+++class FlagMultivariateVariantSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ unknown_key_level = "variant"++ key = StrictCharField(help_text="Unique key for this variant.")+ name = StrictCharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Human-readable name for this variant.",+ )+ rollout_percentage = FiniteFloatField(+ min_value=0,+ max_value=100,+ help_text="Variant rollout percentage, between 0 and 100.",+ )+++class FlagMultivariateSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ unknown_key_level = "multivariate"++ variants = FlagMultivariateVariantSerializer(+ many=True,+ allow_empty=False,+ help_text="Variant definitions for multivariate feature flags.",+ )+++class FlagHoldoutSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ unknown_key_level = "holdout"++ id = StrictIntegerField(+ min_value=I64_MIN,+ max_value=I64_MAX,+ help_text="ID of the experiment holdout this flag belongs to.",+ )+ exclusion_percentage = FiniteFloatField(+ min_value=0,+ max_value=100,+ help_text="Percentage of users held out from the flag, between 0 and 100.",+ )+++class FeatureFlagFiltersSerializer(DropsUnknownKeysMixin, serializers.Serializer):+ unknown_key_level = "filters"++ groups = FlagConditionGroupSerializer(+ many=True,+ required=False,+ default=list,+ help_text="Release condition groups for the feature flag.",+ )+ multivariate = FlagMultivariateSerializer(+ required=False,+ allow_null=True,+ help_text="Multivariate configuration for variant-based rollouts.",+ )+ aggregation_group_type_index = StrictIntegerField(+ min_value=I32_MIN,+ max_value=I32_MAX,+ required=False,+ allow_null=True,+ help_text="Group type index for group-based feature flags. Null means person-level aggregation.",+ )+ # allow_null: Rust reads payloads as Option<serde_json::Value>, so stored `payloads: null`+ # evaluates fine and must not audit as a violation (the live write path rejects null, but+ # that is contextual strictness, not serde fidelity).+ payloads = FlagPayloadsField(+ required=False,+ allow_null=True,+ help_text="Payloads keyed by variant key (multivariate flags) or 'true' (boolean flags). "+ "Values are stored as JSON-encoded strings; non-string JSON values are normalized on write.",+ )+ feature_enrollment = StrictBooleanField(+ required=False,+ allow_null=True,+ help_text="Whether this flag has early access feature enrollment enabled. When true, the flag "+ "is evaluated against the person property $feature_enrollment/{flag_key}.",+ )+ holdout = FlagHoldoutSerializer(+ required=False,+ allow_null=True,+ help_text="Experiment holdout configuration for this flag.",+ )+ # Addendum to the locked #50084 inventory: `early_exit` exists in the Rust FlagFilters struct+ # and is already type-checked in validate_filters, so it must be a declared field here or+ # enforcement would silently drop it. Shape only — the org-level gating on enabling it is+ # contextual tier and stays in FeatureFlagSerializer.+ early_exit = StrictBooleanField(+ required=False,+ allow_null=True,+ help_text="When true, condition evaluation stops at the first matching condition set rather "+ "than continuing to evaluate subsequent groups.",+ )diff --git a/products/feature_flags/backend/api/test/test_filters_schema.py b/products/feature_flags/backend/api/test/test_filters_schema.pynew file mode 100644index 000000000000..bfa824be9692--- /dev/null+++ b/products/feature_flags/backend/api/test/test_filters_schema.py@@ -0,0 +1,337 @@+from typing import Any++from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from products.feature_flags.backend.api.filters_schema import (+ FeatureFlagFiltersSerializer,+ FlagConditionGroupSerializer,+ FlagPropertySerializer,+)++VALID_PROPERTY: dict[str, Any] = {"key": "email", "type": "person", "operator": "icontains", "value": "@posthog.com"}++KITCHEN_SINK_FILTERS: dict[str, Any] = {+ "groups": [+ {+ "properties": [{**VALID_PROPERTY, "negation": False, "group_type_index": None}],+ "rollout_percentage": 50.0,+ "variant": "control",+ "aggregation_group_type_index": None,+ },+ {"properties": [], "rollout_percentage": None},+ ],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ "aggregation_group_type_index": None,+ "payloads": {"control": '{"plan": "pro"}'},+ "feature_enrollment": True,+ "holdout": {"id": 5, "exclusion_percentage": 10.0},+ "early_exit": False,+}+++def _codes_under(node: Any) -> set[str]:+ if isinstance(node, dict):+ return {code for child in node.values() for code in _codes_under(child)}+ if isinstance(node, list):+ return {code for child in node for code in _codes_under(child)}+ return {getattr(node, "code", None) or "invalid"}+++class TestFiltersSchema(SimpleTestCase):+ @parameterized.expand(+ [+ ("empty", {}),+ ("empty_groups", {"groups": []}),+ ("kitchen_sink", KITCHEN_SINK_FILTERS),+ ("null_optionals", {"groups": [], "multivariate": None, "holdout": None, "early_exit": None}),+ ("null_payloads", {"payloads": None}),+ ("null_group_properties", {"groups": [{"properties": None, "rollout_percentage": 50}]}),+ ]+ )+ def test_valid_filters_pass(self, _name: str, filters: dict[str, Any]) -> None:+ serializer = FeatureFlagFiltersSerializer(data=filters)+ assert serializer.is_valid(), serializer.errors++ @parameterized.expand(+ [+ ("groups_not_a_list", {"groups": "all"}, ["groups"], "not_a_list"),+ ("group_not_a_dict", {"groups": ["x"]}, ["groups", 0], "invalid"),+ ("property_key_missing", {"groups": [{"properties": [{"type": "person"}]}]}, ["groups"], "required"),+ (+ "property_key_blank",+ {"groups": [{"properties": [{"key": "", "type": "person"}]}]},+ ["groups"],+ "blank",+ ),+ (+ "property_key_bool",+ {"groups": [{"properties": [{"key": True, "type": "person"}]}]},+ ["groups"],+ "invalid",+ ),+ (+ "property_key_list",+ {"groups": [{"properties": [{"key": ["a"], "type": "person"}]}]},+ ["groups"],+ "invalid",+ ),+ ("property_type_missing", {"groups": [{"properties": [{"key": "k"}]}]}, ["groups"], "required"),+ (+ "property_type_unknown",+ {"groups": [{"properties": [{"key": "k", "type": "event"}]}]},+ ["groups"],+ "invalid_choice",+ ),+ (+ "property_type_person_metadata",+ {"groups": [{"properties": [{"key": "k", "type": "person_metadata"}]}]},+ ["groups"],+ "invalid_choice",+ ),+ (+ "property_operator_unknown",+ {"groups": [{"properties": [{**VALID_PROPERTY, "operator": "bogus"}]}]},+ ["groups"],+ "invalid_choice",+ ),+ (+ "property_operator_unhashable_list",+ {"groups": [{"properties": [{**VALID_PROPERTY, "operator": []}]}]},+ ["groups"],+ "invalid_choice",+ ),+ (+ "property_operator_unhashable_dict",+ {"groups": [{"properties": [{**VALID_PROPERTY, "operator": {}}]}]},+ ["groups"],+ "invalid_choice",+ ),+ (+ "property_group_type_index_string",+ {"groups": [{"properties": [{**VALID_PROPERTY, "group_type_index": "0"}]}]},+ ["groups"],+ "invalid",+ ),+ (+ "property_group_type_index_float",+ {"groups": [{"properties": [{**VALID_PROPERTY, "group_type_index": 1.5}]}]},+ ["groups"],+ "invalid",+ ),+ (+ "property_group_type_index_bool",+ {"groups": [{"properties": [{**VALID_PROPERTY, "group_type_index": True}]}]},+ ["groups"],+ "invalid",+ ),+ (+ "property_negation_int",+ {"groups": [{"properties": [{**VALID_PROPERTY, "negation": 1}]}]},+ ["groups"],+ "invalid",+ ),+ ("group_rollout_negative", {"groups": [{"rollout_percentage": -1}]}, ["groups"], "min_value"),+ ("group_rollout_over_100", {"groups": [{"rollout_percentage": 101}]}, ["groups"], "max_value"),+ ("group_rollout_string", {"groups": [{"rollout_percentage": "50"}]}, ["groups"], "invalid"),+ ("group_rollout_bool", {"groups": [{"rollout_percentage": True}]}, ["groups"], "invalid"),+ ("group_rollout_nan", {"groups": [{"rollout_percentage": float("nan")}]}, ["groups"], "invalid"),+ ("group_variant_numeric", {"groups": [{"variant": 123}]}, ["groups"], "invalid"),+ ("group_aggregation_string", {"groups": [{"aggregation_group_type_index": "0"}]}, ["groups"], "invalid"),+ (+ "group_aggregation_i32_overflow",+ {"groups": [{"aggregation_group_type_index": 2**31}]},+ ["groups"],+ "max_value",+ ),+ (+ "property_group_type_index_i32_underflow",+ {"groups": [{"properties": [{**VALID_PROPERTY, "group_type_index": -(2**31) - 1}]}]},+ ["groups"],+ "min_value",+ ),+ ("multivariate_missing_variants", {"multivariate": {}}, ["multivariate"], "required"),+ ("multivariate_empty_variants", {"multivariate": {"variants": []}}, ["multivariate"], "empty"),+ (+ "variant_key_blank",+ {"multivariate": {"variants": [{"key": "", "rollout_percentage": 100}]}},+ ["multivariate"],+ "blank",+ ),+ (+ "variant_key_numeric",+ {"multivariate": {"variants": [{"key": 5, "rollout_percentage": 100}]}},+ ["multivariate"],+ "invalid",+ ),+ ("variant_rollout_missing", {"multivariate": {"variants": [{"key": "a"}]}}, ["multivariate"], "required"),+ (+ "variant_rollout_null",+ {"multivariate": {"variants": [{"key": "a", "rollout_percentage": None}]}},+ ["multivariate"],+ "null",+ ),+ (+ "variant_rollout_string",+ {"multivariate": {"variants": [{"key": "a", "rollout_percentage": "100"}]}},+ ["multivariate"],+ "invalid",+ ),+ ("holdout_missing_id", {"holdout": {"exclusion_percentage": 10}}, ["holdout"], "required"),+ ("holdout_id_string", {"holdout": {"id": "5", "exclusion_percentage": 10}}, ["holdout"], "invalid"),+ (+ "holdout_id_i64_overflow",+ {"holdout": {"id": 2**63, "exclusion_percentage": 10}},+ ["holdout"],+ "max_value",+ ),+ (+ "holdout_exclusion_over_100",+ {"holdout": {"id": 5, "exclusion_percentage": 150}},+ ["holdout"],+ "max_value",+ ),+ ("feature_enrollment_string", {"feature_enrollment": "true"}, ["feature_enrollment"], "invalid"),+ ("early_exit_int", {"early_exit": 1}, ["early_exit"], "invalid"),+ (+ "aggregation_group_type_index_float",+ {"aggregation_group_type_index": 1.5},+ ["aggregation_group_type_index"],+ "invalid",+ ),+ (+ "aggregation_group_type_index_i32_overflow",+ {"aggregation_group_type_index": 2**31},+ ["aggregation_group_type_index"],+ "max_value",+ ),+ ("payloads_not_a_dict", {"payloads": []}, ["payloads"], "not_a_dict"),+ ("payload_invalid_json_string", {"payloads": {"true": "not json"}}, ["payloads"], "invalid_payload_json"),+ ("payload_blank_string", {"payloads": {"true": ""}}, ["payloads"], "invalid_payload_json"),+ ("payload_nan_float", {"payloads": {"true": float("nan")}}, ["payloads"], "invalid_payload_json"),+ ("payload_nan_string", {"payloads": {"true": "NaN"}}, ["payloads"], "invalid_payload_json"),+ ("payload_infinity_string", {"payloads": {"true": "Infinity"}}, ["payloads"], "invalid_payload_json"),+ ]+ )+ def test_invalid_filters_rejected(+ self, _name: str, filters: dict[str, Any], error_path: list[Any], expected_code: str+ ) -> None:+ serializer = FeatureFlagFiltersSerializer(data=filters)+ assert not serializer.is_valid()+ node: Any = serializer.errors+ for step in error_path:+ assert step in node if isinstance(node, dict) else step < len(node), serializer.errors+ node = node[step]+ assert expected_code in _codes_under(node), serializer.errors++ @parameterized.expand([("min", "gte"), ("max", "lte")])+ def test_operator_aliases_are_canonicalized(self, alias: str, canonical: str) -> None:+ serializer = FlagPropertySerializer(data={**VALID_PROPERTY, "operator": alias, "value": "5"})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["operator"] == canonical++ @parameterized.expand([("int", 123, "123"), ("float", 1.5, "1.5")])+ def test_numeric_property_keys_normalized_to_strings(self, _name: str, key: Any, expected: str) -> None:+ # Mirrors Rust deserialize_key: stored numeric keys evaluate fine and must not be+ # rejected (nor 400 a read-modify-write PATCH echoing them back).+ serializer = FlagPropertySerializer(data={**VALID_PROPERTY, "key": key})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["key"] == expected++ @parameterized.expand(+ [+ ("dict", {"a": 1}, '{"a": 1}'),+ ("list", [1, 2], "[1, 2]"),+ ("number", 5, "5"),+ ("bool", True, "true"),+ ("null", None, "null"),+ ("string_passthrough", '{"a": 1}', '{"a": 1}'),+ ]+ )+ def test_payload_values_normalized_to_json_strings(self, _name: str, value: Any, expected: str) -> None:+ serializer = FeatureFlagFiltersSerializer(data={"payloads": {"true": value}})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["payloads"] == {"true": expected}++ def test_null_group_properties_normalized_to_empty_list(self) -> None:+ serializer = FlagConditionGroupSerializer(data={"properties": None})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["properties"] == []++ def test_group_aggregation_absent_vs_null_is_preserved(self) -> None:+ absent = FlagConditionGroupSerializer(data={"properties": []})+ assert absent.is_valid(), absent.errors+ assert "aggregation_group_type_index" not in absent.validated_data++ explicit_null = FlagConditionGroupSerializer(data={"properties": [], "aggregation_group_type_index": None})+ assert explicit_null.is_valid(), explicit_null.errors+ assert explicit_null.validated_data["aggregation_group_type_index"] is None++ @patch("products.feature_flags.backend.api.filters_schema.logger")+ def test_legacy_unknown_filter_keys_dropped_without_logging(self, mock_logger: Any) -> None:+ serializer = FeatureFlagFiltersSerializer(+ data={"groups": [], "holdout_groups": [], "super_groups": []}, context={"flag_id": 1}+ )+ assert serializer.is_valid(), serializer.errors+ assert "holdout_groups" not in serializer.validated_data+ assert "super_groups" not in serializer.validated_data+ mock_logger.warning.assert_not_called()++ @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"]),+ (+ "multivariate",+ {"multivariate": {"variants": [{"key": "a", "rollout_percentage": 100}], "junk_m": 1}},+ ["junk_m"],+ ),+ (+ "variant",+ {"multivariate": {"variants": [{"key": "a", "rollout_percentage": 100, "junk_v": 1}]}},+ ["junk_v"],+ ),+ ("holdout", {"holdout": {"id": 1, "exclusion_percentage": 0, "junk_h": 1}}, ["junk_h"]),+ ]+ )+ @patch("products.feature_flags.backend.api.filters_schema.logger")+ def test_non_legacy_unknown_keys_logged_per_level(+ self, level: str, filters: dict[str, Any], expected_keys: list[str], mock_logger: Any+ ) -> None:+ serializer = FeatureFlagFiltersSerializer(data=filters, context={"flag_id": 42})+ assert serializer.is_valid(), serializer.errors+ mock_logger.warning.assert_called_once_with(+ "feature_flag_filters_unknown_keys_dropped", level=level, keys=expected_keys, flag_id=42+ )++ @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]] = []++ class Sink:+ def record(self, *, level: str, keys: Any, flag_id: int | None) -> None:+ recorded.append({"level": level, "keys": list(keys), "flag_id": flag_id})++ serializer = FeatureFlagFiltersSerializer(+ data={"groups": [], "junk": 1, "holdout_groups": []},+ context={"unknown_keys_sink": Sink(), "flag_id": 7},+ )+ assert serializer.is_valid(), serializer.errors+ assert recorded == [{"level": "filters", "keys": ["holdout_groups", "junk"], "flag_id": 7}]+ mock_logger.warning.assert_not_called()diff --git a/products/feature_flags/backend/filters_validation.py b/products/feature_flags/backend/filters_validation.pynew file mode 100644index 000000000000..13bc57305eeb--- /dev/null+++ b/products/feature_flags/backend/filters_validation.py@@ -0,0 +1,359 @@+"""Cross-field validation for the `FeatureFlag.filters` JSON (issue #50084, cross-field tier).++The structural tier (`api/filters_schema.py`) checks shape and types; this module checks+invariants between fields: variant sums, key uniqueness, payload/variant agreement, and+operator/value compatibility. Contextual checks (cohort existence, circular dependencies,+size limits, feature gates) need DB or request state and stay in+`FeatureFlagSerializer.validate_filters`.++Every check takes a filters dict that already passed `FeatureFlagFiltersSerializer` — types+are trusted, operators are canonical (aliases applied), payload values are JSON-encoded+strings — 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).+"""++import re+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from typing import Any++from rest_framework import serializers+from rest_framework.exceptions import ErrorDetail+from rest_framework.settings import api_settings++from posthog.hogql.property import parse_semver++from posthog.queries.base import determine_parsed_date_for_property_matching++from products.feature_flags.backend.api.filters_schema import FeatureFlagFiltersSerializer++DATE_OPERATORS: frozenset[str] = frozenset({"is_date_exact", "is_date_after", "is_date_before"})+STRING_VALUE_OPERATORS: frozenset[str] = frozenset(+ {"regex", "not_regex", "icontains", "not_icontains", "gt", "gte", "lt", "lte"}+)+LIST_VALUE_OPERATORS: frozenset[str] = frozenset({"icontains_multi", "not_icontains_multi"})+SEMVER_OPERATORS: frozenset[str] = frozenset(+ {+ "semver_gt",+ "semver_gte",+ "semver_lt",+ "semver_lte",+ "semver_eq",+ "semver_neq",+ "semver_tilde",+ "semver_caret",+ "semver_wildcard",+ }+)+PERSON_AGGREGATED_PROPERTY_TYPES: tuple[str, ...] = ("person", "cohort", "flag")+++@dataclass(frozen=True)+class Violation:+ rule_id: str # stable grouping key, index-free (e.g. "cross_field.variant_rollout_sum_not_100")+ path: str # concrete location, indices preserved (e.g. "groups[2].properties[0].value")+ message: str+++def _variant_keys(filters: Mapping[str, Any]) -> set[str]:+ return {variant["key"] for variant in (filters.get("multivariate") or {}).get("variants", [])}+++def check_variant_rollout_sum(filters: Mapping[str, Any]) -> list[Violation]:+ variant_list = (filters.get("multivariate") or {}).get("variants", [])+ if not variant_list:+ return []+ # Exact equality is deliberate parity with the live write path, which enforces+ # `sum != 100`. Float summation is deterministic, so any flag that passed that check at+ # write time still sums to exactly 100 here; near-100 drift only exists on rows that+ # predate the check, and those genuinely need cleanup before enforcement because the+ # write path would reject them on their next update anyway.+ rollout_sum = sum(variant.get("rollout_percentage", 0) for variant in variant_list)+ if rollout_sum != 100:+ return [+ Violation(+ rule_id="cross_field.variant_rollout_sum_not_100",+ path="multivariate.variants",+ message=f"Variant rollout percentages must sum to 100, got {rollout_sum}.",+ )+ ]+ return []+++def check_variant_keys_unique(filters: Mapping[str, Any]) -> list[Violation]:+ variant_list = (filters.get("multivariate") or {}).get("variants", [])+ seen: set[str] = set()+ duplicates: set[str] = set()+ for variant in variant_list:+ key = variant["key"]+ if key in seen:+ duplicates.add(key)+ seen.add(key)+ if duplicates:+ return [+ Violation(+ rule_id="cross_field.variant_keys_not_unique",+ path="multivariate.variants",+ message=f"Variant keys must be unique, duplicated: {', '.join(sorted(duplicates))}.",+ )+ ]+ return []+++def check_payload_keys(filters: Mapping[str, Any]) -> list[Violation]:+ payloads = filters.get("payloads") or {}+ if not payloads:+ return []+ if filters.get("multivariate"):+ variant_keys = _variant_keys(filters)+ return [+ Violation(+ rule_id="cross_field.payload_key_not_a_variant",+ path=f"payloads.{key}",+ message=f"Payload key '{key}' does not match any variant key.",+ )+ for key in payloads+ if key not in variant_keys+ ]+ return [+ Violation(+ rule_id="cross_field.payload_key_not_true",+ path=f"payloads.{key}",+ message=f"Payload key '{key}' is invalid: boolean flags only support the 'true' key.",+ )+ for key in payloads+ if key != "true"+ ]+++def check_group_variant_references(filters: Mapping[str, Any]) -> list[Violation]:+ variant_keys = _variant_keys(filters)+ violations = []+ for group_index, group in enumerate(filters.get("groups", [])):+ variant = group.get("variant")+ if variant and variant not in variant_keys:+ violations.append(+ Violation(+ rule_id="cross_field.group_variant_not_a_variant",+ path=f"groups[{group_index}].variant",+ message=f"Variant override '{variant}' does not match any variant key.",+ )+ )+ return violations+++def check_property_types_match_aggregation(filters: Mapping[str, Any]) -> list[Violation]:+ violations = []+ flag_level_aggregation = filters.get("aggregation_group_type_index")+ for group_index, group in enumerate(filters.get("groups", [])):+ # An absent key falls back to the flag-level aggregation; an explicit null means person+ # aggregation. Stored legacy flags predate per-group aggregation, so skipping the+ # fallback would misfire on every one of them.+ aggregation = (+ group["aggregation_group_type_index"] if "aggregation_group_type_index" in group else flag_level_aggregation+ )+ for prop_index, prop in enumerate(group.get("properties", [])):+ path = f"groups[{group_index}].properties[{prop_index}]"+ if aggregation is None:+ if prop.get("type") not in PERSON_AGGREGATED_PROPERTY_TYPES:+ violations.append(+ Violation(+ rule_id="cross_field.person_aggregation_property_type",+ path=path,+ message="Person-aggregated conditions can only use person, cohort, and flag properties.",+ )+ )+ elif prop.get("type") != "group":+ violations.append(+ Violation(+ rule_id="cross_field.group_aggregation_property_type",+ path=path,+ message="Group-aggregated conditions can only use group properties.",+ )+ )+ elif prop.get("group_type_index") != aggregation:+ violations.append(+ Violation(+ rule_id="cross_field.group_property_type_index_mismatch",+ path=path,+ message="Group properties must match the condition set's group type.",+ )+ )+ return violations+++def _check_semver_value(value: Any, operator: str, path: str) -> Violation | None:+ if not isinstance(value, str):+ return Violation(+ rule_id="cross_field.semver_value_invalid",+ path=path,+ message=f"Invalid value for operator {operator}: expected a semver string.",+ )+ semver_value = value+ if operator == "semver_wildcard":+ semver_value = semver_value.rstrip(".*")+ try:+ parse_semver(semver_value)+ except (ValueError, IndexError):+ return Violation(+ rule_id="cross_field.semver_value_invalid",+ path=path,+ message=f"Invalid semver value for operator {operator}: {value}.",+ )+ return None+++def check_operator_value_compatibility(filters: Mapping[str, Any]) -> list[Violation]:+ violations = []+ for group_index, group in enumerate(filters.get("groups", [])):+ for prop_index, prop in enumerate(group.get("properties", [])):+ path = f"groups[{group_index}].properties[{prop_index}].value"+ operator = prop.get("operator")+ value = prop.get("value")+ if prop.get("type") == "flag" and operator != "flag_evaluates_to":+ violations.append(+ Violation(+ rule_id="cross_field.flag_property_requires_flag_evaluates_to",+ path=f"groups[{group_index}].properties[{prop_index}].operator",+ message="Flag properties must use the 'flag_evaluates_to' operator.",+ )+ )+ if operator in ("in", "not_in") and prop.get("type") != "cohort":+ violations.append(+ Violation(+ rule_id="cross_field.in_not_in_requires_cohort",+ path=f"groups[{group_index}].properties[{prop_index}].operator",+ message=f"Operator {operator} is only supported on cohort properties.",+ )+ )+ if operator in DATE_OPERATORS and determine_parsed_date_for_property_matching(value) is None:+ violations.append(+ Violation(+ rule_id="cross_field.date_value_not_parseable",+ path=path,+ message=f"Invalid date value: {value}.",+ )+ )+ if operator in STRING_VALUE_OPERATORS and not isinstance(value, str):+ violations.append(+ Violation(+ rule_id="cross_field.operator_requires_string_value",+ path=path,+ message=f"Operator {operator} requires a string value.",+ )+ )+ if operator in LIST_VALUE_OPERATORS and not isinstance(value, list):+ violations.append(+ Violation(+ rule_id="cross_field.operator_requires_list_value",+ path=path,+ message=f"Operator {operator} requires a list of values.",+ )+ )+ if operator in SEMVER_OPERATORS:+ semver_violation = _check_semver_value(value, operator, path)+ if semver_violation is not None:+ violations.append(semver_violation)+ return violations+++CROSS_FIELD_CHECKS: tuple[Callable[[Mapping[str, Any]], list[Violation]], ...] = (+ check_variant_rollout_sum,+ check_variant_keys_unique,+ check_payload_keys,+ check_group_variant_references,+ check_property_types_match_aggregation,+ check_operator_value_compatibility,+)+++def check_groups_non_empty_for_create(filters: Mapping[str, Any]) -> list[Violation]:+ # Deliberately NOT in CROSS_FIELD_CHECKS. The POST/PATCH asymmetry is a locked decision+ # on #50084: POST requires at least one condition group, but+ # PATCH {"filters": {"groups": []}} is a legitimate "clear targeting" under merged-state+ # validation, and stored flags with empty groups are valid state the audit must never+ # flag. Do not "unify" these in either direction.+ if not filters.get("groups"):+ return [+ Violation(+ rule_id="contextual.groups_empty_on_create",+ path="groups",+ message="Feature flags must have at least one condition set (group).",+ )+ ]+ return []+++def collect_cross_field_violations(filters: Mapping[str, Any]) -> list[Violation]:+ return [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+\]")+++def flatten_structural_errors(errors: Any, path: str = "") -> list[Violation]:+ """Flatten DRF's nested error structure into Violations with stable rule ids.++ The rule id is the index-stripped path plus the ErrorDetail code (e.g.+ "structural.groups[].properties[].key.invalid"); concrete indices survive in the path.+ """+ violations: list[Violation] = []+ if isinstance(errors, dict):+ for key, child in errors.items():+ if isinstance(key, int):+ # ListField reports per-item errors as {index: errors}+ child_path = f"{path}[{key}]"+ elif key == api_settings.NON_FIELD_ERRORS_KEY:+ child_path = path+ else:+ child_path = f"{path}.{key}" if path else str(key)+ violations.extend(flatten_structural_errors(child, child_path))+ elif isinstance(errors, list):+ for index, item in enumerate(errors):+ if isinstance(item, (dict, list)):+ # many=True serializers report a list aligned by item index; empty dicts mark+ # valid items+ if item:+ violations.extend(flatten_structural_errors(item, f"{path}[{index}]"))+ elif item:+ code = getattr(item, "code", None) or "invalid"+ rule_path = _LIST_INDEX_RE.sub("[]", path) or "filters"+ violations.append(+ Violation(+ rule_id=f"structural.{rule_path}.{code}",+ path=path or "filters",+ message=str(item),+ )+ )+ return violations+++def collect_filters_violations(filters: Any, *, context: dict[str, Any] | None = None) -> list[Violation]:+ """Run the full structural + cross-field rule set against one filters value.++ Cross-field checks only run once the structure is valid — the same ordering the write+ path has (field validation raises before object-level validation), and it lets the+ cross-field rules trust types instead of re-checking them.+ """+ if not isinstance(filters, dict):+ return [+ Violation(+ rule_id="structural.filters.not_a_dict",+ path="filters",+ message=f"Filters must be a dict, got {type(filters).__name__}.",+ )+ ]+ serializer = FeatureFlagFiltersSerializer(data=filters, context=context or {})+ if not serializer.is_valid():+ return flatten_structural_errors(serializer.errors)+ return collect_cross_field_violations(serializer.validated_data)diff --git a/products/feature_flags/backend/management/commands/audit_flag_filters.py b/products/feature_flags/backend/management/commands/audit_flag_filters.pynew file mode 100644index 000000000000..8a9ab70299c5--- /dev/null+++ b/products/feature_flags/backend/management/commands/audit_flag_filters.py@@ -0,0 +1,260 @@+"""Read-only audit of `FeatureFlag.filters` against the #50084 structural + cross-field rules.++Reports violations grouped by rule, plus a frequency table of unknown keys that enforcement+would drop. A clean run (zero violations) is the gate for flipping enforcement on; unknown+keys are informational (they get dropped silently by design). Contextual rules (cohort+existence, circular dependencies, size limits, feature gates) are already enforced at write+time in FeatureFlagSerializer and are not audited.++Each flag costs a DRF serializer instantiation, so a full prod scan takes minutes, not+seconds — it's an offline command.+"""++import re+import json+from collections.abc import Iterator, Sequence+from dataclasses import dataclass, field+from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser++from posthog.models import Team++from products.feature_flags.backend.api.filters_schema import (+ FLAG_ID_CONTEXT_KEY,+ UNKNOWN_KEYS_SINK_CONTEXT_KEY,+ is_legacy_unknown_key,+)+from products.feature_flags.backend.filters_validation import Violation, collect_filters_violations+from products.feature_flags.backend.models.feature_flag import FeatureFlag++# Unknown keys come from user-controlled JSON, so the distinct-key space is unbounded; cap it+# to keep a pathological prod scan from growing the aggregator without limit.+MAX_TRACKED_UNKNOWN_KEYS = 1000++# C0/C1 control characters (incl. tab, newline, ESC, OSC): stored filter junk is+# user-controlled and the console report prints keys and values verbatim, so strip anything+# a terminal could interpret — a newline in a key could forge a fake report line.+_CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]")+++def _sanitize_for_console(text: str) -> str:+ return _CONTROL_CHARS_RE.sub("�", text)+++def _iter_flag_rows(queryset: Any, *, limit: int, chunk_size: int = 500) -> Iterator[tuple[int, int, Any]]:+ # Keyset pagination instead of .iterator(): prod runs behind PgBouncer with server-side+ # cursors disabled, so .iterator() buffers the entire result set client-side on execute+ # and a full scan would hold every flag's filters JSON in memory at once. Repeated+ # id-bounded LIMIT queries keep memory bounded on any connection.+ base = queryset.order_by("id").values_list("id", "team_id", "filters")+ last_id, yielded = 0, 0+ while True:+ page = chunk_size if not limit else min(chunk_size, limit - yielded)+ if page <= 0:+ return+ chunk = list(base.filter(id__gt=last_id)[:page])+ if not chunk:+ return+ yield from chunk+ yielded += len(chunk)+ last_id = chunk[-1][0]+++@dataclass+class RuleReport:+ rule_id: str+ flags_affected: int = 0+ total_violations: int = 0+ sample_flag_ids: list[int] = field(default_factory=list)+ sample_details: list[str] = field(default_factory=list)+++class UnknownKeyAggregator:+ """Implements the UnknownKeySink protocol; counts flags affected per (level, key)."""++ def __init__(self, max_samples: int) -> None:+ self.max_samples = max_samples+ self.flag_counts: dict[tuple[str, str], int] = {}+ self.sample_flag_ids: dict[tuple[str, str], list[int]] = {}+ self.untracked_keys = 0+ self._current_flag_id: int | None = None+ self._seen_for_current_flag: set[tuple[str, str]] = set()++ def record(self, *, level: str, keys: Sequence[str], flag_id: int | None) -> None:+ # Flags are scanned sequentially, so dedupe per (level, key) within the current flag —+ # the same unknown key across several groups of one flag counts that flag once.+ if flag_id != self._current_flag_id:+ self._current_flag_id = flag_id+ self._seen_for_current_flag = set()+ for key in keys:+ pair = (level, key)+ if pair in self._seen_for_current_flag:+ continue+ self._seen_for_current_flag.add(pair)+ if pair not in self.flag_counts and len(self.flag_counts) >= MAX_TRACKED_UNKNOWN_KEYS:+ self.untracked_keys += 1+ continue+ self.flag_counts[pair] = self.flag_counts.get(pair, 0) + 1+ samples = self.sample_flag_ids.setdefault(pair, [])+ if flag_id is not None and len(samples) < self.max_samples:+ samples.append(flag_id)+++class Command(BaseCommand):+ help = (+ "Read-only audit of FeatureFlag.filters (all flags, soft-deleted included) against the "+ "#50084 structural + cross-field rules. Reports violations grouped by rule; a clean run "+ "gates flipping enforcement on."+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--json", action="store_true", help="Emit a machine-readable JSON report instead")+ parser.add_argument("--limit", type=int, default=0, help="Max flags to scan (0 = all)")+ parser.add_argument("--samples", type=int, default=5, help="Sample flag ids to record per rule / unknown key")+ parser.add_argument("--team-id", type=int, default=None, help="Restrict the scan to one team (debugging)")++ def handle(self, *args: Any, **options: Any) -> None:+ limit: int = options["limit"]+ samples: int = options["samples"]+ team_id: int | None = options["team_id"]++ # A negative limit would silently slice away the newest flags (rows[:-N]) and a+ # negative samples cap would drop every diagnostic — both would make a bad scan look+ # authoritative, so fail loudly instead.+ if limit < 0:+ raise CommandError("--limit must be >= 0 (0 scans all flags)")+ if samples < 0:+ raise CommandError("--samples must be >= 0")+ # A mistyped --team-id would scan zero rows and report a false "clean".+ if team_id is not None and not Team.objects.filter(id=team_id).exists():+ raise CommandError(f"Team {team_id} does not exist")++ sink = UnknownKeyAggregator(max_samples=samples)+ rule_reports: dict[str, RuleReport] = {}+ scanned = 0+ flags_with_violations = 0++ # objects_including_soft_deleted: the default manager excludes soft-deleted flags, and+ # a restored flag must not resurrect a violation. It is also a RootTeamManager, so+ # --team-id with an environment's team id maps to the project root team instead of+ # silently scanning zero flags.+ queryset = FeatureFlag.objects_including_soft_deleted.all()+ if team_id is not None:+ queryset = queryset.filter(team_id=team_id)++ # collect_filters_violations runs CROSS_FIELD_CHECKS, which deliberately excludes+ # check_groups_non_empty_for_create: non-empty groups is a POST-only rule (#50084) —+ # stored flags with empty groups are valid state and must never show up in this report.+ for flag_id, flag_team_id, filters in _iter_flag_rows(queryset, limit=limit):+ scanned += 1+ try:+ violations = collect_filters_violations(+ filters, context={UNKNOWN_KEYS_SINK_CONTEXT_KEY: sink, FLAG_ID_CONTEXT_KEY: flag_id}+ )+ except Exception as exc:+ # The whole point of this command is surviving wild-west data: one flag whose+ # junk crashes a validator must become a reported violation, not a dead scan.+ violations = [+ Violation(+ rule_id="structural.filters.internal_error",+ path="filters",+ message=f"{type(exc).__name__}: {exc}",+ )+ ]+ if not violations:+ continue+ flags_with_violations += 1+ counted_rules: set[str] = set()+ for violation in violations:+ report = rule_reports.setdefault(violation.rule_id, RuleReport(rule_id=violation.rule_id))+ report.total_violations += 1+ if violation.rule_id in counted_rules:+ continue+ counted_rules.add(violation.rule_id)+ report.flags_affected += 1+ if len(report.sample_flag_ids) < samples:+ report.sample_flag_ids.append(flag_id)+ report.sample_details.append(+ f"flag={flag_id} team={flag_team_id} {violation.path}: {violation.message}"+ )++ reports = sorted(rule_reports.values(), key=lambda r: (-r.flags_affected, r.rule_id))+ if options["json"]:+ self._emit_json(scanned, flags_with_violations, reports, sink)+ else:+ self._emit_console(scanned, flags_with_violations, reports, sink)++ def _emit_json(+ self, scanned: int, flags_with_violations: int, reports: list[RuleReport], sink: UnknownKeyAggregator+ ) -> None:+ payload = {+ "scanned": scanned,+ "flags_with_violations": flags_with_violations,+ "clean": flags_with_violations == 0,+ # Enumerate fields explicitly: report.__dict__ would leak any future internal+ # attribute into the machine-readable contract.+ "rules": [+ {+ "rule_id": report.rule_id,+ "flags_affected": report.flags_affected,+ "total_violations": report.total_violations,+ "sample_flag_ids": report.sample_flag_ids,+ "sample_details": report.sample_details,+ }+ for report in reports+ ],+ "unknown_keys": [+ {+ "level": level,+ "key": key,+ "legacy": is_legacy_unknown_key(level, key),+ "flags_affected": count,+ "sample_flag_ids": sink.sample_flag_ids.get((level, key), []),+ }+ for (level, key), count in sorted(sink.flag_counts.items())+ ],+ "untracked_unknown_keys": sink.untracked_keys,+ }+ self.stdout.write(json.dumps(payload, indent=2))++ def _emit_console(+ self, scanned: int, flags_with_violations: int, reports: list[RuleReport], sink: UnknownKeyAggregator+ ) -> None:+ clean = scanned - flags_with_violations+ self.stdout.write(+ f"Scanned {scanned} flags (soft-deleted included); {clean} clean, {flags_with_violations} with violations."+ )++ if reports:+ self.stdout.write("")+ self.stdout.write("Violations by rule:")+ for report in reports:+ ids = ", ".join(str(flag_id) for flag_id in report.sample_flag_ids)+ self.stdout.write(+ self.style.ERROR(+ f" {report.rule_id} — {report.flags_affected} flags "+ f"({report.total_violations} violations) sample ids: {ids}"+ )+ )+ for detail in report.sample_details:+ self.stdout.write(f" {_sanitize_for_console(detail)}")+ else:+ self.stdout.write(self.style.SUCCESS("No violations found."))++ if sink.flag_counts:+ self.stdout.write("")+ self.stdout.write("Unknown keys dropped by enforcement (frequency):")+ for (level, key), count in sorted(sink.flag_counts.items(), key=lambda item: (-item[1], item[0])):+ legacy_marker = " [legacy]" if is_legacy_unknown_key(level, key) else ""+ ids = ", ".join(str(flag_id) for flag_id in sink.sample_flag_ids.get((level, key), []))+ self.stdout.write(+ f" {level:<9} {_sanitize_for_console(key):<40} {count} flags sample ids: {ids}{legacy_marker}"+ )+ if sink.untracked_keys:+ self.stdout.write(+ self.style.WARNING(+ f" ... plus {sink.untracked_keys} occurrence(s) of keys beyond the "+ f"{MAX_TRACKED_UNKNOWN_KEYS} distinct-key tracking cap"+ )+ )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.pynew file mode 100644index 000000000000..f854177d3d56--- /dev/null+++ b/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py@@ -0,0 +1,263 @@+import json+from io import StringIO+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command+from django.core.management.base import CommandError++from parameterized import parameterized++from posthog.models import Team++from products.feature_flags.backend.filters_validation import collect_filters_violations+from products.feature_flags.backend.models.feature_flag import FeatureFlag++INVALID_MULTIVARIATE_FILTERS: dict[str, Any] = {+ "groups": [],+ "multivariate": {"variants": [{"key": "a", "rollout_percentage": 50}]},+}+++class TestAuditFlagFilters(BaseTest):+ def _create_flag(self, key: str, filters: dict[str, Any], **kwargs: Any) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=kwargs.pop("team", self.team), created_by=self.user, key=key, filters=filters, **kwargs+ )++ def _run(self, *args: str) -> dict[str, Any]:+ # Always scope to this test's team: the local test DB is reused across suites and can+ # carry leftover flags from other tests.+ out = StringIO()+ call_command("audit_flag_filters", "--json", "--team-id", str(self.team.id), *args, stdout=out)+ return json.loads(out.getvalue())++ def _rule(self, report: dict[str, Any], rule_id: str) -> dict[str, Any] | None:+ return next((rule for rule in report["rules"] if rule["rule_id"] == rule_id), None)++ def test_clean_flags_report_no_violations(self) -> None:+ self._create_flag("clean", {"groups": [{"properties": [], "rollout_percentage": 50}]})+ self._create_flag("empty_filters", {})+ self._create_flag("empty_groups", {"groups": []})++ report = self._run()++ assert report["clean"] is True+ assert report["scanned"] == 3+ assert report["flags_with_violations"] == 0+ assert report["rules"] == []++ def test_violations_grouped_by_rule_with_samples(self) -> None:+ structural = self._create_flag("structural", {"groups": [{"properties": [{"type": "person"}]}]})+ cross_field = self._create_flag("cross-field", INVALID_MULTIVARIATE_FILTERS)+ self._create_flag("clean", {"groups": []})++ report = self._run()++ assert report["clean"] is False+ assert report["flags_with_violations"] == 2++ structural_rule = self._rule(report, "structural.groups[].properties[].key.required")+ assert structural_rule is not None+ assert structural_rule["flags_affected"] == 1+ assert structural_rule["sample_flag_ids"] == [structural.id]++ cross_field_rule = self._rule(report, "cross_field.variant_rollout_sum_not_100")+ assert cross_field_rule is not None+ assert cross_field_rule["sample_flag_ids"] == [cross_field.id]+ assert f"team={self.team.id}" in cross_field_rule["sample_details"][0]++ def test_soft_deleted_flags_are_audited(self) -> None:+ flag = self._create_flag("soft-deleted", INVALID_MULTIVARIATE_FILTERS)+ flag.deleted = True+ flag.save()++ report = self._run()++ rule = self._rule(report, "cross_field.variant_rollout_sum_not_100")+ assert rule is not None+ assert rule["sample_flag_ids"] == [flag.id]++ def test_unknown_keys_reported_with_legacy_marker(self) -> None:+ legacy = self._create_flag("legacy", {"groups": [], "holdout_groups": []})+ 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"}]}]},+ )++ report = self._run()++ assert report["clean"] is True+ unknown_by_key = {(entry["level"], entry["key"]): entry for entry in report["unknown_keys"]}+ assert unknown_by_key[("filters", "holdout_groups")]["legacy"] is True+ assert unknown_by_key[("filters", "holdout_groups")]["sample_flag_ids"] == [legacy.id]+ assert unknown_by_key[("filters", "junk")]["legacy"] is False+ assert unknown_by_key[("filters", "junk")]["sample_flag_ids"] == [junk.id]+ assert unknown_by_key[("property", "cohort_name")]["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"}]},+ )++ report = self._run()++ entry = next(e for e in report["unknown_keys"] if e["key"] == "sort_key")+ assert entry["flags_affected"] == 1++ @patch("products.feature_flags.backend.api.filters_schema.logger")+ def test_audit_does_not_log_unknown_keys(self, mock_logger: Any) -> None:+ self._create_flag("junk", {"groups": [], "junk": 1})++ self._run()++ mock_logger.warning.assert_not_called()++ def test_limit_and_samples_options(self) -> None:+ self._create_flag("first", INVALID_MULTIVARIATE_FILTERS)+ self._create_flag("second", INVALID_MULTIVARIATE_FILTERS)++ limited = self._run("--limit", "1")+ assert limited["scanned"] == 1++ sampled = self._run("--samples", "1")+ rule = self._rule(sampled, "cross_field.variant_rollout_sum_not_100")+ assert rule is not None+ assert rule["flags_affected"] == 2+ assert len(rule["sample_flag_ids"]) == 1++ def test_team_id_restricts_scan(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="other")+ self._create_flag("other-team", INVALID_MULTIVARIATE_FILTERS, team=other_team)+ self._create_flag("this-team", {"groups": []})++ report = self._run()++ assert report["scanned"] == 1+ assert report["clean"] is True++ def test_team_id_maps_environment_to_root_team(self) -> None:+ env_team = Team.objects.create(+ organization=self.organization, project=self.team.project, parent_team=self.team, name="env"+ )+ self._create_flag("root-team-flag", INVALID_MULTIVARIATE_FILTERS)++ out = StringIO()+ call_command("audit_flag_filters", "--json", "--team-id", str(env_team.id), stdout=out)+ report = json.loads(out.getvalue())++ # A false "0 flags scanned, clean" here means the manager stopped resolving+ # environment team ids to the project root.+ assert report["scanned"] == 1+ assert report["clean"] is False++ def test_validator_crash_becomes_violation_not_dead_scan(self) -> None:+ crashing = self._create_flag("crashing", {"groups": []})+ self._create_flag("clean", {"groups": []})++ real = collect_filters_violations++ def crash_on_first(filters: Any, **kwargs: Any) -> Any:+ if kwargs.get("context", {}).get("flag_id") == crashing.id:+ raise TypeError("unhashable type: 'list'")+ return real(filters, **kwargs)++ with patch(+ "products.feature_flags.backend.management.commands.audit_flag_filters.collect_filters_violations",+ side_effect=crash_on_first,+ ):+ report = self._run()++ assert report["scanned"] == 2+ rule = self._rule(report, "structural.filters.internal_error")+ assert rule is not None+ assert rule["sample_flag_ids"] == [crashing.id]++ def test_console_output_summarizes(self) -> None:+ self._create_flag("cross-field", INVALID_MULTIVARIATE_FILTERS)+ out = StringIO()++ call_command("audit_flag_filters", "--team-id", str(self.team.id), stdout=out)++ output = out.getvalue()+ assert "1 with violations" in output+ assert "cross_field.variant_rollout_sum_not_100" in output++ def test_console_output_reports_clean_scan(self) -> None:+ self._create_flag("clean", {"groups": []})+ out = StringIO()++ call_command("audit_flag_filters", "--team-id", str(self.team.id), stdout=out)++ assert "No violations found." in out.getvalue()++ def test_repeated_rule_counts_flag_once_but_all_violations(self) -> None:+ self._create_flag(+ "double",+ {+ "groups": [+ {+ "properties": [+ {"key": "a", "type": "person", "operator": "in", "value": [1]},+ {"key": "b", "type": "person", "operator": "in", "value": [2]},+ ]+ }+ ]+ },+ )++ report = self._run()++ rule = self._rule(report, "cross_field.in_not_in_requires_cohort")+ assert rule is not None+ assert rule["flags_affected"] == 1+ assert rule["total_violations"] == 2++ @patch("products.feature_flags.backend.management.commands.audit_flag_filters.MAX_TRACKED_UNKNOWN_KEYS", 1)+ def test_console_output_reports_untracked_keys(self) -> None:+ self._create_flag("many-junk-keys", {"groups": [], "junk_a": 1, "junk_b": 2})+ out = StringIO()++ call_command("audit_flag_filters", "--team-id", str(self.team.id), stdout=out)++ assert "tracking cap" in out.getvalue()++ @parameterized.expand(+ [+ ("negative_limit", ["--limit", "-1"]),+ ("negative_samples", ["--samples", "-1"]),+ ("nonexistent_team", ["--team-id", "999999999"]),+ ]+ )+ def test_invalid_options_rejected(self, _name: str, args: list[str]) -> None:+ self._create_flag("clean", {"groups": []})++ with self.assertRaises(CommandError):+ call_command("audit_flag_filters", *args, stdout=StringIO())++ def test_console_output_escapes_control_sequences(self) -> None:+ self._create_flag(+ "escape-junk",+ {"groups": [], "payloads": {"\x1b]0;evil\x07": "1"}, "junk\x1b[31mkey": 1},+ )+ out = StringIO()++ call_command("audit_flag_filters", "--team-id", str(self.team.id), stdout=out)++ output = out.getvalue()+ assert "\x1b" not in output+ assert "\x07" not in output+ assert "�" in output++ @patch("products.feature_flags.backend.management.commands.audit_flag_filters.MAX_TRACKED_UNKNOWN_KEYS", 1)+ def test_unknown_key_tracking_is_capped(self) -> None:+ self._create_flag("many-junk-keys", {"groups": [], "junk_a": 1, "junk_b": 2})++ report = self._run()++ assert len(report["unknown_keys"]) == 1+ assert report["untracked_unknown_keys"] == 1diff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.pynew file mode 100644index 000000000000..326189787346--- /dev/null+++ b/products/feature_flags/backend/test/test_filters_validation.py@@ -0,0 +1,375 @@+import copy+from types import SimpleNamespace+from typing import Any++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import serializers+from rest_framework.exceptions import ErrorDetail++from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.filters_validation import (+ CROSS_FIELD_CHECKS,+ Violation,+ check_groups_non_empty_for_create,+ collect_cross_field_violations,+ collect_filters_violations,+ flatten_structural_errors,+ validate_cross_field_or_raise,+)+++def _multivariate(*variants: tuple[str, float]) -> dict[str, Any]:+ return {"variants": [{"key": key, "rollout_percentage": rollout} for key, rollout in variants]}+++def _person_prop(**overrides: Any) -> dict[str, Any]:+ return {"key": "email", "type": "person", "operator": "icontains", "value": "@posthog.com", **overrides}+++class TestFiltersValidation(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "variant_sum_under_100",+ {"multivariate": _multivariate(("a", 50), ("b", 49.9))},+ ["cross_field.variant_rollout_sum_not_100"],+ ),+ ("variant_sum_exactly_100", {"multivariate": _multivariate(("a", 50), ("b", 50))}, []),+ (+ "variant_keys_duplicated",+ {"multivariate": _multivariate(("a", 50), ("a", 50))},+ ["cross_field.variant_keys_not_unique"],+ ),+ (+ "payload_key_not_a_variant",+ {"multivariate": _multivariate(("a", 100)), "payloads": {"b": "1"}},+ ["cross_field.payload_key_not_a_variant"],+ ),+ (+ "boolean_payload_key_not_true",+ {"payloads": {"false": "1"}},+ ["cross_field.payload_key_not_true"],+ ),+ ("boolean_payload_key_true", {"payloads": {"true": "1"}}, []),+ (+ "group_variant_not_a_variant",+ {"multivariate": _multivariate(("a", 100)), "groups": [{"variant": "b"}]},+ ["cross_field.group_variant_not_a_variant"],+ ),+ ("group_variant_empty_string_ignored", {"groups": [{"variant": ""}]}, []),+ (+ "person_aggregation_with_group_property",+ {"groups": [{"properties": [{"key": "k", "type": "group", "group_type_index": 0}]}]},+ ["cross_field.person_aggregation_property_type"],+ ),+ (+ "flag_level_aggregation_fallback_applies",+ {"aggregation_group_type_index": 0, "groups": [{"properties": [_person_prop()]}]},+ ["cross_field.group_aggregation_property_type"],+ ),+ (+ "explicit_null_aggregation_overrides_flag_level",+ {+ "aggregation_group_type_index": 0,+ "groups": [{"aggregation_group_type_index": None, "properties": [_person_prop()]}],+ },+ [],+ ),+ (+ "group_property_type_index_mismatch",+ {+ "groups": [+ {+ "aggregation_group_type_index": 1,+ "properties": [{"key": "k", "type": "group", "group_type_index": 0, "value": "x"}],+ }+ ]+ },+ ["cross_field.group_property_type_index_mismatch"],+ ),+ (+ "group_property_type_index_match",+ {+ "groups": [+ {+ "aggregation_group_type_index": 1,+ "properties": [+ {"key": "k", "type": "group", "group_type_index": 1, "operator": "exact", "value": "x"}+ ],+ }+ ]+ },+ [],+ ),+ (+ "flag_property_wrong_operator",+ {"groups": [{"properties": [{"key": "1", "type": "flag", "operator": "exact", "value": True}]}]},+ ["cross_field.flag_property_requires_flag_evaluates_to"],+ ),+ (+ "flag_property_correct_operator",+ {+ "groups": [+ {"properties": [{"key": "1", "type": "flag", "operator": "flag_evaluates_to", "value": True}]}+ ]+ },+ [],+ ),+ (+ "in_operator_on_person_property",+ {"groups": [{"properties": [_person_prop(operator="in", value=[1])]}]},+ ["cross_field.in_not_in_requires_cohort"],+ ),+ (+ "in_operator_on_cohort_property",+ {"groups": [{"properties": [{"key": "id", "type": "cohort", "operator": "in", "value": 5}]}]},+ [],+ ),+ (+ "date_operator_unparseable_value",+ {"groups": [{"properties": [_person_prop(operator="is_date_after", value="not a date")]}]},+ ["cross_field.date_value_not_parseable"],+ ),+ (+ "date_operator_relative_value",+ {"groups": [{"properties": [_person_prop(operator="is_date_after", value="-30d")]}]},+ [],+ ),+ (+ "date_operator_iso_value",+ {"groups": [{"properties": [_person_prop(operator="is_date_exact", value="2024-01-01")]}]},+ [],+ ),+ (+ "regex_operator_numeric_value",+ {"groups": [{"properties": [_person_prop(operator="regex", value=5)]}]},+ ["cross_field.operator_requires_string_value"],+ ),+ (+ "gt_operator_numeric_value",+ {"groups": [{"properties": [_person_prop(operator="gt", value=5)]}]},+ ["cross_field.operator_requires_string_value"],+ ),+ (+ "multi_contains_string_value",+ {"groups": [{"properties": [_person_prop(operator="icontains_multi", value="a")]}]},+ ["cross_field.operator_requires_list_value"],+ ),+ (+ "multi_contains_list_value",+ {"groups": [{"properties": [_person_prop(operator="icontains_multi", value=["a"])]}]},+ [],+ ),+ (+ "semver_invalid_value",+ {"groups": [{"properties": [_person_prop(operator="semver_gt", value="abc")]}]},+ ["cross_field.semver_value_invalid"],+ ),+ (+ "semver_valid_value",+ {"groups": [{"properties": [_person_prop(operator="semver_gt", value="1.2.3")]}]},+ [],+ ),+ (+ "semver_wildcard_value",+ {"groups": [{"properties": [_person_prop(operator="semver_wildcard", value="1.2.*")]}]},+ [],+ ),+ (+ "semver_non_string_value",+ {"groups": [{"properties": [_person_prop(operator="semver_eq", value=123)]}]},+ ["cross_field.semver_value_invalid"],+ ),+ ]+ )+ def test_cross_field_rules(self, _name: str, filters: dict[str, Any], expected_rule_ids: list[str]) -> None:+ violations = collect_cross_field_violations(filters)+ assert sorted(violation.rule_id for violation in violations) == sorted(expected_rule_ids), violations++ def test_violation_paths_preserve_indices(self) -> None:+ filters = {+ "groups": [+ {"properties": []},+ {"properties": [_person_prop(), _person_prop(operator="regex", value=5)]},+ ]+ }+ violations = collect_cross_field_violations(filters)+ assert [violation.path for violation in violations] == ["groups[1].properties[1].value"]++ def test_flatten_structural_errors_strips_indices_in_rule_id(self) -> None:+ errors = {+ "groups": [+ {},+ {"properties": [{}, {"key": [ErrorDetail("This field is required.", code="required")]}]},+ ]+ }+ violations = flatten_structural_errors(errors)+ assert violations == [+ Violation(+ rule_id="structural.groups[].properties[].key.required",+ path="groups[1].properties[1].key",+ message="This field is required.",+ )+ ]++ def test_flatten_structural_errors_handles_non_field_errors_and_int_keys(self) -> None:+ errors = {+ "groups": {+ "non_field_errors": [ErrorDetail('Expected a list of items but got type "str".', code="not_a_list")]+ },+ "payloads": {0: [ErrorDetail("bad", code="invalid")]},+ }+ rule_ids = {violation.rule_id for violation in flatten_structural_errors(errors)}+ assert rule_ids == {"structural.groups.not_a_list", "structural.payloads[].invalid"}++ @parameterized.expand([("none", None), ("list", []), ("string", "x")])+ def test_non_dict_filters_reported(self, _name: str, filters: Any) -> None:+ violations = collect_filters_violations(filters)+ assert [violation.rule_id for violation in violations] == ["structural.filters.not_a_dict"]++ def test_structural_failure_short_circuits_cross_field(self) -> None:+ filters = {+ "multivariate": _multivariate(("a", 50)),+ "payloads": {"b": "not json"},+ }+ rule_ids = [violation.rule_id for violation in collect_filters_violations(filters)]+ assert rule_ids == ["structural.payloads.invalid_payload_json"]++ def test_collect_filters_violations_end_to_end(self) -> None:+ structural = collect_filters_violations({"groups": [{"properties": [{"type": "person"}]}]})+ assert [violation.rule_id for violation in structural] == ["structural.groups[].properties[].key.required"]++ 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": []})++ 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.+ @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",+ {+ "groups": [+ {+ "aggregation_group_type_index": 1,+ "properties": [+ {"key": "k", "type": "group", "group_type_index": 1, "operator": "exact", "value": "x"}+ ],+ }+ ]+ },+ 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": []}]}) == []diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rsindex a281a7b7b743..cfa37c22e2f1 100644--- a/rust/feature-flags/src/flags/flag_models.rs+++ b/rust/feature-flags/src/flags/flag_models.rs@@ -185,6 +185,8 @@ pub struct MultivariateFlagOptions {pub variants: Vec<MultivariateFlagVariant>,}+// Runtime Python mirror: products/feature_flags/backend/api/filters_schema.py validates+// filters against these shapes at write time — keep field shapes in sync (issue #50084).#[derive(Debug, Clone, Deserialize, Serialize, Default)]pub struct FlagFilters {#[serde(default)]diff --git a/rust/feature-flags/src/properties/property_models.rs b/rust/feature-flags/src/properties/property_models.rsindex 43c0c4d29c5f..52d0a994a22f 100644--- a/rust/feature-flags/src/properties/property_models.rs+++ b/rust/feature-flags/src/properties/property_models.rs@@ -1,6 +1,8 @@use serde::{Deserialize, Serialize};-// Keep in sync with FEATURE_FLAG_SUPPORTED_OPERATORS in posthog/api/feature_flag.py+// 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)#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]#[serde(rename_all = "snake_case")]pub enum OperatorType {@@ -99,6 +101,8 @@ where})}+// Runtime Python mirror: products/feature_flags/backend/api/filters_schema.py validates flag+// filter properties against this shape at write time — keep field shapes in sync (issue #50084).#[derive(Debug, Clone, Default, Deserialize, Serialize)]pub struct PropertyFilter {#[serde(deserialize_with = "deserialize_key")]