:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(feature-flags): keep whole rollout percentages as integers (#84957)
Patricio05a76906ae9e
diff --git a/products/feature_flags/backend/api/filters_schema.py b/products/feature_flags/backend/api/filters_schema.pyindex 65568d64f68b..cf37d6eab660 100644--- a/products/feature_flags/backend/api/filters_schema.py+++ b/products/feature_flags/backend/api/filters_schema.py@@ -211,20 +211,24 @@ class PropertyKeyField(serializers.CharField):return super().to_internal_value(data)-class FiniteFloatField(serializers.FloatField):- """FloatField that rejects bools, numeric strings, and non-finite values.+class FinitePercentageField(serializers.FloatField):+ """Percentage field that rejects bools, numeric strings, and non-finite values.JSON parsed with stdlib `json.loads` can contain NaN/Infinity tokens, which compareFalse against min_value/max_value and then crash percentage math downstream.++ Whole numbers stay ints. Validated filters are persisted and then served verbatim to+ SDKs, and the .NET and Java clients type rollout percentages as int, so widening 100+ to 100.0 here breaks their local evaluation."""- def to_internal_value(self, data: Any) -> float:+ def to_internal_value(self, data: Any) -> int | 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+ return int(value) if value.is_integer() else valuedef _reject_json_constant(name: str) -> None:@@ -359,7 +363,7 @@ class FlagConditionGroupSerializer(DropsUnknownKeysMixin, serializers.Serializerdefault=list,help_text="Property conditions for this release condition group.",)- rollout_percentage = FiniteFloatField(+ rollout_percentage = FinitePercentageField(min_value=0,max_value=100,required=False,@@ -439,7 +443,7 @@ class FlagMultivariateVariantSerializer(DropsUnknownKeysMixin, serializers.Seriaallow_blank=True,help_text="Human-readable name for this variant.",)- rollout_percentage = FiniteFloatField(+ rollout_percentage = FinitePercentageField(min_value=0,max_value=100,help_text="Variant rollout percentage, between 0 and 100.",@@ -475,7 +479,7 @@ class FlagHoldoutSerializer(DropsUnknownKeysMixin, serializers.Serializer):max_value=I64_MAX,help_text="ID of the experiment holdout this flag belongs to.",)- exclusion_percentage = FiniteFloatField(+ exclusion_percentage = FinitePercentageField(min_value=0,max_value=100,help_text="Percentage of users held out from the flag, between 0 and 100.",diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 933d4a7abe93..abbdff7d74c1 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -1527,7 +1527,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json().get("type"), "validation_error")self.assertEqual(response.json().get("detail"),- f"multivariate.variants: Variant rollout percentages must sum to 100, got {float(75 + third_variant_rollout)}.",+ f"multivariate.variants: Variant rollout percentages must sum to 100, got {75 + third_variant_rollout}.",)def test_cant_update_multivariate_feature_flag_with_variant_rollout_not_100(self):@@ -1574,7 +1574,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json().get("type"), "validation_error")self.assertEqual(response.json().get("detail"),- "multivariate.variants: Variant rollout percentages must sum to 100, got 90.0.",+ "multivariate.variants: Variant rollout percentages must sum to 100, got 90.",)# Verify flag wasn't updateddiff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.pyindex 68436653c5cc..7dc419b814bd 100644--- a/products/feature_flags/backend/test/test_filters_validation.py+++ b/products/feature_flags/backend/test/test_filters_validation.py@@ -7,6 +7,7 @@ from rest_framework import serializersfrom rest_framework.exceptions import ErrorDetailfrom products.feature_flags.backend.api.feature_flag import _reject_serde_unsafe_filters+from products.feature_flags.backend.api.filters_schema import FeatureFlagFiltersSerializerfrom products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUEfrom products.feature_flags.backend.filters_validation import (CROSS_FIELD_CHECKS,@@ -234,6 +235,34 @@ class TestFiltersValidation(SimpleTestCase):violations = collect_cross_field_violations(filters)assert [violation.path for violation in violations] == ["groups[1].properties[1].value"]+ # Validated filters are stored and then served verbatim to SDKs, and the .NET and Java+ # clients type rollout percentages as int, so 100 must not come back as 100.0.+ @parameterized.expand(+ [+ ("int_stays_int", 100, 100, int),+ ("whole_float_narrows_to_int", 100.0, 100, int),+ ("fraction_stays_float", 33.33, 33.33, float),+ ("zero_stays_int", 0, 0, int),+ ]+ )+ def test_rollout_percentage_keeps_whole_numbers_as_ints(+ self, _name: str, stored: float, expected: float, expected_type: type+ ) -> None:+ serializer = FeatureFlagFiltersSerializer(+ data={+ "groups": [{"properties": [], "rollout_percentage": stored, "variant": None}],+ "multivariate": _multivariate(("a", stored)),+ },+ context={},+ )++ assert serializer.is_valid(), serializer.errors+ group_rollout = serializer.validated_data["groups"][0]["rollout_percentage"]+ variant_rollout = serializer.validated_data["multivariate"]["variants"][0]["rollout_percentage"]+ assert group_rollout == expected+ assert type(group_rollout) is expected_type+ assert type(variant_rollout) is expected_type+def test_flatten_structural_errors_strips_indices_in_rule_id(self) -> None:errors = {"groups": [