:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): estimate release conditions that depend on another flag (#105503)
Gustavo H. Strassburger6b6f81943759
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.mdindex 5922ca645d7d..941bbc3acfbb 100644--- a/docs/internal/feature-flags/django-api-endpoints.md+++ b/docs/internal/feature-flags/django-api-endpoints.md@@ -146,13 +146,14 @@ Key things to know:### Supporting modules-| File | Purpose |-| -------------------------------------------------- | -------------------------------------------------------------------------- |-| `posthog/models/feature_flag/flag_matching.py` | **Legacy** Python evaluation engine (only used for static cohort creation) |-| `posthog/models/feature_flag/flags_cache.py` | HyperCache for the Rust flags service with signal-based invalidation |-| `posthog/models/feature_flag/local_evaluation.py` | Prepares flag data for SDK local evaluation with HyperCache |-| `posthog/models/feature_flag/user_blast_radius.py` | Estimates user/group match counts for conditions |-| `posthog/api/services/flags_service.py` | HTTP proxy to the Rust flags service |+| File | Purpose |+| ---------------------------------------------------------- | --------------------------------------------------------------------------------- |+| `posthog/models/feature_flag/flag_matching.py` | **Legacy** Python evaluation engine (only used for static cohort creation) |+| `products/feature_flags/backend/flags_cache.py` | HyperCache for the Rust flags service with signal-based invalidation |+| `products/feature_flags/backend/local_evaluation.py` | Prepares flag data for SDK local evaluation with HyperCache |+| `products/feature_flags/backend/user_blast_radius.py` | Estimates user/group match counts for conditions |+| `products/feature_flags/backend/blast_radius_flag_deps.py` | Sizes flag-dependency filters for that estimate as per-person match probabilities |+| `posthog/api/services/flags_service.py` | HTTP proxy to the Rust flags service |## Remote config endpointsdiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 734865e0477b..19ef55036e3a 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -67,6 +67,7 @@ from products.feature_flags.backend.api.feature_flag import (_flag_write_source,parse_created_by_ids,)+from products.feature_flags.backend.blast_radius_flag_deps import MAX_DEPENDENCY_DEPTHfrom products.feature_flags.backend.encrypted_flag_payloads import (REDACTED_PAYLOAD_VALUE,flag_payload_codec,@@ -9901,7 +9902,202 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["type"], "validation_error")- def test_user_blast_radius_with_flag_dependency(self):+ @parameterized.expand(+ [+ (+ "false_when_the_flag_is_on_for_everyone",+ {"groups": [{"properties": [], "rollout_percentage": 100}]},+ False,+ 0,+ ),+ (+ "true_when_the_flag_is_on_for_everyone",+ {"groups": [{"properties": [], "rollout_percentage": 100}]},+ True,+ 10,+ ),+ ("string_true_is_a_variant_name", {"groups": [{"properties": [], "rollout_percentage": 100}]}, "true", 0),+ ("true_scales_by_rollout", {"groups": [{"properties": [], "rollout_percentage": 10}]}, True, 1),+ ("null_rollout_means_everyone", {"groups": [{"properties": [], "rollout_percentage": None}]}, True, 10),+ (+ "true_follows_targeting",+ {+ "groups": [+ {+ "properties": [+ {"key": "group", "type": "person", "value": ["0", "1", "2", "3"], "operator": "exact"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ True,+ 4,+ ),+ (+ "false_is_the_complement_of_targeting",+ {+ "groups": [+ {+ "properties": [+ {"key": "group", "type": "person", "value": ["0", "1", "2", "3"], "operator": "exact"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ False,+ 6,+ ),+ (+ # Max over the sets gives 6; a sum would give 7 and the first set alone 4.+ "shared_rollout_hash_takes_the_widest_admitting_set",+ {+ "groups": [+ {+ "properties": [+ {+ "key": "group",+ "type": "person",+ "value": ["0", "1", "2", "3", "4"],+ "operator": "exact",+ }+ ],+ "rollout_percentage": 20,+ },+ {"properties": [], "rollout_percentage": 60},+ ]+ },+ True,+ 6,+ ),+ (+ "variant_splits_by_variant_rollout",+ {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 30},+ {"key": "test", "rollout_percentage": 70},+ ]+ },+ },+ "control",+ 3,+ ),+ (+ "pinned_variant_wins_for_its_set",+ {+ "groups": [+ {+ "properties": [+ {"key": "group", "type": "person", "value": ["0", "1"], "operator": "exact"}+ ],+ "rollout_percentage": 100,+ "variant": "control",+ },+ {"properties": [], "rollout_percentage": 100},+ ],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ },+ "control",+ 6,+ ),+ (+ "unknown_variant_is_never_served",+ {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ },+ "missing-variant",+ 0,+ ),+ (+ # Set 1 pins control and admits 60%; set 2 wins only the 60% to 80% slice, split 50/50.+ "variant_slices_follow_partial_rollouts",+ {+ "groups": [+ {"properties": [], "rollout_percentage": 60, "variant": "control"},+ {"properties": [], "rollout_percentage": 80},+ ],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ },+ "test",+ 1,+ ),+ (+ "group_aggregated_dependency_stays_neutral",+ {"groups": [{"properties": [], "rollout_percentage": 100}], "aggregation_group_type_index": 0},+ False,+ 10,+ ),+ (+ # Saved flags carry the index on each set and None at the flag level.+ "group_aggregated_set_stays_neutral",+ {+ "groups": [{"properties": [], "rollout_percentage": 30, "aggregation_group_type_index": 0}],+ "aggregation_group_type_index": None,+ },+ True,+ 10,+ ),+ (+ "holdout_groups_stay_neutral",+ {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "holdout_groups": [{"properties": [], "rollout_percentage": 10}],+ },+ False,+ 10,+ ),+ (+ "feature_enrollment_stays_neutral",+ {"groups": [{"properties": [], "rollout_percentage": 0}], "feature_enrollment": True},+ True,+ 10,+ ),+ (+ "holdout_stays_neutral",+ {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "holdout": {"id": 1, "exclusion_percentage": 10},+ },+ False,+ 10,+ ),+ (+ "super_groups_stay_neutral",+ {+ "groups": [{"properties": [], "rollout_percentage": 0}],+ "super_groups": [{"properties": [], "rollout_percentage": 100}],+ },+ True,+ 10,+ ),+ (+ "early_exit_stays_neutral",+ {"groups": [{"properties": [], "rollout_percentage": 10}], "early_exit": True},+ True,+ 10,+ ),+ ]+ )+ def test_user_blast_radius_with_flag_dependency(self, _name, filters, value, expected_affected):for i in range(10):_create_person(team_id=self.team.pk,@@ -9913,10 +10109,9 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):team=self.team,key="dependency-flag",created_by=self.user,- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ filters=filters,)- # Flag dependencies can't be evaluated in HogQL, so they are neutral for the estimateresponse = self.client.post(f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",{@@ -9925,7 +10120,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):{"key": str(dependency_flag.pk),"type": "flag",- "value": False,+ "value": value,"operator": "flag_evaluates_to",}],@@ -9935,7 +10130,433 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertLessEqual({"affected": 10, "total": 10}.items(), response.json().items())+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ @parameterized.expand(+ [+ # A disabled dependency is pre-seeded false, so `false` still matches everyone. A missing,+ # deleted or non-v1 dependency makes the dependent flag false whatever the condition asks.+ ("inactive_flag", {"active": False}, "id", True, 0),+ ("inactive_flag_negated", {"active": False}, "id", False, 10),+ ("deleted_flag", {"deleted": True}, "id", True, 0),+ ("deleted_flag_negated", {"deleted": True}, "id", False, 0),+ ("missing_flag", {}, "missing", True, 0),+ ("missing_flag_negated", {}, "missing", False, 0),+ ("v2_config_flag_negated", {"filters": {"version": 2, "rules": []}}, "id", False, 0),+ ("key_reference_never_resolves", {}, "key", True, 0),+ ]+ )+ def test_user_blast_radius_with_unresolvable_flag_dependency(+ self, _name, flag_kwargs, reference, value, expected_affected+ ):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})++ dependency_flag = FeatureFlag.objects.create(+ **{+ "team": self.team,+ "key": "dependency-flag",+ "created_by": self.user,+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},+ **flag_kwargs,+ }+ )+ key = {"id": str(dependency_flag.pk), "key": dependency_flag.key, "missing": "999999999"}[reference]++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [{"key": key, "type": "flag", "value": value, "operator": "flag_evaluates_to"}],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ @parameterized.expand(+ [+ ("live_cohort", False, 3),+ # The dependency's broken targeting is not the caller's input, so it sizes neutrally.+ ("hard_deleted_cohort", True, 10),+ ]+ )+ def test_user_blast_radius_with_cohort_targeted_flag_dependency(self, _name, delete_cohort, expected_affected):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})+ cohort = Cohort.objects.create(+ team=self.team,+ groups=[+ {"properties": [{"key": "group", "type": "person", "value": ["0", "1", "2"], "operator": "exact"}]}+ ],+ )+ cohort.calculate_people_ch(pending_version=0)++ dependency_flag = FeatureFlag.objects.create(+ team=self.team,+ key="dependency-flag",+ created_by=self.user,+ filters={+ "groups": [+ {"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}], "rollout_percentage": 100}+ ]+ },+ )+ if delete_cohort:+ Cohort.objects.filter(pk=cohort.pk).delete()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [+ {"key": str(dependency_flag.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ def test_user_blast_radius_with_a_cycle_through_a_variant(self):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})+ # A needs B, B needs A=control at 50%, and the condition asks for A=true. The enclosing+ # `true` does not settle a variant, so the cycle guard is what stops the recursion.+ flag_a = FeatureFlag.objects.create(+ team=self.team,+ key="flag-a",+ created_by=self.user,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ },+ )+ flag_b = FeatureFlag.objects.create(+ team=self.team,+ key="flag-b",+ created_by=self.user,+ filters={+ "groups": [+ {+ "properties": [+ {"key": str(flag_a.pk), "type": "flag", "value": "control", "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 50,+ }+ ]+ },+ )+ flag_a.filters["groups"][0]["properties"].append(+ {"key": str(flag_b.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ )+ flag_a.save()+ expected_affected = 5++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [+ {"key": str(flag_a.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ def test_user_blast_radius_falls_back_when_the_dependency_budget_runs_out(self):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})+ half = FeatureFlag.objects.create(+ team=self.team,+ key="half",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},+ )+ two_fifths = FeatureFlag.objects.create(+ team=self.team,+ key="two-fifths",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 40}]},+ )+ # A partially expanded weight would size one dependency and ignore the other.+ expected_affected = 10++ with patch("products.feature_flags.backend.blast_radius_flag_deps.MAX_DEPENDENCY_NODES", 1):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [+ {"key": str(half.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"},+ {"key": str(two_fifths.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"},+ ],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ def test_user_blast_radius_falls_back_past_the_dependency_depth(self):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})+ # A chain one longer than the cap, ending in a flag that targets four persons. Sizing part+ # of it would report 4; the whole weight is neutral instead.+ head = FeatureFlag.objects.create(+ team=self.team,+ key="leaf",+ created_by=self.user,+ filters={+ "groups": [+ {+ "properties": [+ {"key": "group", "type": "person", "value": ["0", "1", "2", "3"], "operator": "exact"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ )+ for level in range(MAX_DEPENDENCY_DEPTH + 1):+ head = FeatureFlag.objects.create(+ team=self.team,+ key=f"level-{level}",+ created_by=self.user,+ filters={+ "groups": [+ {+ "properties": [+ {"key": str(head.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ )+ expected_affected = 10++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [+ {"key": str(head.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ def test_user_blast_radius_with_a_dependency_of_many_condition_sets(self):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})+ # One running max per set as nested calls would exceed the recursion limit and return a 500.+ dependency_flag = FeatureFlag.objects.create(+ team=self.team,+ key="dependency-flag",+ created_by=self.user,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 1}] * 399+ + [{"properties": [], "rollout_percentage": 100}]+ },+ )+ expected_affected = 10++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [+ {"key": str(dependency_flag.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ @parameterized.expand(+ [+ ("nested_dependency", False, 2),+ # The enclosing `true` settles the repeated flag, so a cycle stops there instead of recursing until a 500.+ ("cyclic_dependency", True, 2),+ ]+ )+ def test_user_blast_radius_with_nested_flag_dependency(self, _name, cyclic, expected_affected):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})++ root_flag = FeatureFlag.objects.create(+ team=self.team,+ key="root-flag",+ created_by=self.user,+ filters={+ "groups": [+ {+ "properties": [+ {"key": "group", "type": "person", "value": ["0", "1", "2", "3"], "operator": "exact"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ )+ middle_flag = FeatureFlag.objects.create(+ team=self.team,+ key="middle-flag",+ created_by=self.user,+ filters={+ "groups": [+ {+ "properties": [+ {"key": str(root_flag.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 50,+ }+ ]+ },+ )+ if cyclic:+ root_flag.filters["groups"][0]["properties"].append(+ {"key": str(middle_flag.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ )+ root_flag.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [+ {"key": str(middle_flag.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ @parameterized.expand(+ [+ # The flags service evaluates a flag once, so repeats do not compound and contradictions never match.+ ("repeated_dependency_counts_once", [("half", True), ("half", True)], 5),+ ("contradictory_values_never_match", [("half", True), ("half", False)], 0),+ ("independent_dependencies_multiply", [("half", True), ("two_fifths", True)], 2),+ # needs_half depends on half, so requesting both is one draw of half, not two.+ ("transitive_dependency_counts_once", [("half", True), ("needs_half", True)], 5),+ ("transitive_contradiction_never_matches", [("half", False), ("needs_half", True)], 0),+ # With split fixed to true, its control variant is conditional on that draw: 0.5 * 0.4.+ ("variant_given_true_is_conditional", [("split", True), ("needs_split_control", True)], 2),+ # split=control stays the narrower value down the chain, so the deeper split=test contradicts it.+ (+ "deeper_variant_contradiction_never_matches",+ [("split", "control"), ("needs_split_true_and_test", True)],+ 0,+ ),+ ]+ )+ def test_user_blast_radius_with_several_flag_dependencies(self, _name, dependencies, expected_affected):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})+ flags: dict[str, FeatureFlag] = {}++ def create(key: str, properties: list[dict], rollout: int, multivariate: Optional[dict] = None) -> None:+ flags[key] = FeatureFlag.objects.create(+ team=self.team,+ key=key,+ created_by=self.user,+ filters={+ "groups": [{"properties": properties, "rollout_percentage": rollout}],+ "multivariate": multivariate,+ },+ )++ def depends_on(key: str, value: Any) -> dict:+ return {"key": str(flags[key].pk), "type": "flag", "value": value, "operator": "flag_evaluates_to"}++ create("half", [], 50)+ create("two_fifths", [], 40)+ create("needs_half", [depends_on("half", True)], 100)+ create(+ "split",+ [],+ 50,+ {"variants": [{"key": "control", "rollout_percentage": 40}, {"key": "test", "rollout_percentage": 60}]},+ )+ create("needs_split_control", [depends_on("split", "control")], 100)+ create("needs_split_test", [depends_on("split", "test")], 100)+ create("needs_split_true_and_test", [depends_on("split", True), depends_on("needs_split_test", True)], 100)++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": [depends_on(key, value) for key, value in dependencies],+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())++ def test_user_blast_radius_with_flag_dependency_in_an_or_group_stays_neutral(self):+ for i in range(10):+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"], properties={"group": f"{i}"})+ dependency_flag = FeatureFlag.objects.create(+ team=self.team,+ key="dependency-flag",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 0}]},+ )+ expected_affected = 10++ # The flags service cannot evaluate an OR condition, so the weight does not apply and the+ # flag's 0% must not zero out the persons the other branch matches.+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",+ {+ "condition": {+ "properties": {+ "type": "OR",+ "values": [+ {+ "key": str(dependency_flag.pk),+ "type": "flag",+ "value": True,+ "operator": "flag_evaluates_to",+ },+ {"key": "group", "type": "person", "value": ["0", "1", "2"], "operator": "exact"},+ ],+ },+ "rollout_percentage": 100,+ }+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertLessEqual({"affected": expected_affected, "total": 10}.items(), response.json().items())def test_user_blast_radius_with_flag_dependency_and_person_property(self):for i in range(10):@@ -9949,10 +10570,10 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):team=self.team,key="dependency-flag",created_by=self.user,- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},)- # The flag dependency is ignored, but the person property filter still applies+ # The person property filter keeps 4 persons and the 50% dependency halves themresponse = self.client.post(f"/api/projects/{self.team.id}/feature_flags/user_blast_radius",{@@ -9977,7 +10598,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertLessEqual({"affected": 4, "total": 10}.items(), response.json().items())+ self.assertLessEqual({"affected": 2, "total": 10}.items(), response.json().items())def test_user_blast_radius_with_groups_and_flag_dependency(self):create_group_type_mapping_without_created_at(diff --git a/products/feature_flags/backend/blast_radius_flag_deps.py b/products/feature_flags/backend/blast_radius_flag_deps.pynew file mode 100644index 000000000000..9deddab314d4--- /dev/null+++ b/products/feature_flags/backend/blast_radius_flag_deps.py@@ -0,0 +1,370 @@+from collections.abc import Callable+from typing import Any, Optional++from django.core.exceptions import ObjectDoesNotExist++from rest_framework.exceptions import ValidationError++from posthog.hogql import ast+from posthog.hogql.errors import (+ ExposedHogQLError,+ NotImplementedError as HogQLNotImplementedError,+)+from posthog.hogql.property import property_to_expr+from posthog.hogql.visitor import TraversingVisitor, clone_expr++from posthog.models.filters import Filter+from posthog.models.property import Property, PropertyGroup, PropertyOperatorType, PropertyValidationError+from posthog.models.team.team import Team+from posthog.utils import safe_int++from products.feature_flags.backend.facade.config import detect_config_format+from products.feature_flags.backend.facade.filters import EVALUATED_BEFORE_RELEASE_CONDITIONS+from products.feature_flags.backend.models.feature_flag import FeatureFlag++# Neither the flags service nor the save path limits how deep a dependency chain goes, so the+# cap only guards against a pathological chain. Past it the whole weight is neutral.+MAX_DEPENDENCY_DEPTH = 5++# Dependencies are deduplicated per condition, so a real configuration expands a handful of+# flags. The budget bounds the Postgres lookups when a chain fans out anyway.+MAX_DEPENDENCY_NODES = 50++# The variant model re-embeds every earlier set's expression for each later set, so the emitted+# expression can outgrow the dependency budget. The budget is charged while the expression is+# built, so an oversized one is abandoned before it is cloned any further.+MAX_WEIGHT_AST_NODES = 10_000++# Probability used when a dependency cannot be sized per person: every person counts, which is+# what property_to_expr's neutral filter for flag properties already does.+NEUTRAL = 1.0++# Flag-level settings the flags service evaluates before, or instead of, the condition sets.+# The rollout model below does not apply to them. Feature enrollment reads a person property+# the configuration does not carry, so it joins the shared list here.+_UNMODELED_FILTER_KEYS = EVALUATED_BEFORE_RELEASE_CONDITIONS | {"feature_enrollment"}++# Errors that mean the dependency's stored targeting cannot be compiled. They describe that+# flag's configuration, not the caller's condition, so they must not surface as a 400. This+# mirrors the build-time errors unevaluable_filters_as_validation_errors converts.+_TARGETING_BUILD_ERRORS = (+ ValidationError,+ ExposedHogQLError,+ HogQLNotImplementedError,+ PropertyValidationError,+ ObjectDoesNotExist,+)+++class _DependencyBudgetExceeded(Exception):+ pass+++class _DependencyMissing(Exception):+ pass+++class FlagDependencyEstimator:+ """+ Translates the flag-dependency filters of a condition (`type: "flag"`, `flag_evaluates_to`)+ into a HogQL expression for the probability that the condition's dependencies hold for a+ person the plain filters already matched.++ Flag matching hashes the distinct_id, so a person-grained query cannot say whether one+ person is in a rollout. It can say how likely they are, which is what a sizing estimate+ needs: summing the probability over persons gives the expected number of matches.++ The model follows the flags service. Condition sets are checked in stored order and the+ first one whose targeting matches and whose rollout admits the person wins. Every set of a+ flag compares the same hash against its rollout, so a person targeted by several sets is+ admitted with probability max(rollout) rather than the sum. The winning set's pinned+ variant applies when it has one; otherwise the variant is a second, independent hash split+ by the variant rollouts. A dependency is resolved by flag id only and a string value is a+ variant name, as the flags service does. The max over sets is exact when every non-rollout+ factor of a set is 0 or 1; a nested dependency inside a set makes it an approximation.++ A dependency the flags service cannot resolve, because the flag is missing, deleted or not+ stored in config version 1, makes the dependent flag false for everyone, whatever value the+ condition asks for.++ Not modeled: holdouts, super conditions, feature enrollment, early exit and group-aggregated+ dependency flags, a dependency whose stored targeting cannot be compiled, a chain past the+ depth or node budgets, and a condition that is not an AND list, the only shape the flag+ editor sends. Those fall back to the neutral estimate, which is the pre-existing behavior of+ counting every person.+ """++ def __init__(self, team: Team, clean_condition: Callable[[Team, dict], Filter]):+ self.team = team+ # Injected rather than imported: user_blast_radius imports this module, and its cleaner+ # must normalize the dependency's stored filters the same way as the condition being sized.+ self.clean_condition = clean_condition+ self._flags: dict[int, Optional[FeatureFlag]] = {}+ self._dependency_nodes = 0+ self._ast_nodes = 0++ def weight_expr(self, group: PropertyGroup) -> ast.Expr:+ """Probability that the condition's flag dependencies hold for a person its plain filters match."""+ properties = _conjunction_properties(group)+ if properties is None:+ return ast.Constant(value=NEUTRAL)+ references = [(str(prop.key), prop.value) for prop in properties if prop.type == "flag"]+ try:+ return self._conjunction_expr(references, depth=0, seen=frozenset(), assumed={})+ except _DependencyBudgetExceeded:+ # A partially expanded chain would give a misleading number, so the whole weight is neutral.+ return ast.Constant(value=NEUTRAL)+ except _DependencyMissing:+ return ast.Constant(value=0.0)++ def _conjunction_expr(+ self, references: list[tuple[str, Any]], depth: int, seen: frozenset[int], assumed: dict[str, bool | str]+ ) -> ast.Expr:+ """+ Probability that every referenced flag evaluates to its requested value. `assumed` holds the+ values the enclosing conjunctions already fixed. The flags service evaluates a flag once, so+ a reference to one of those is settled by that value rather than drawn again, and a variant+ of a flag fixed to `true` is conditional on that draw.+ """+ requested_by_flag = _merge_requested_values(references)+ child_assumed = _merge_requested_values([*assumed.items(), *references])+ if requested_by_flag is None or child_assumed is None:+ return ast.Constant(value=0.0)++ factors: list[ast.Expr] = []+ for reference, requested in requested_by_flag.items():+ settled = _settled_by(assumed.get(reference), requested)+ if settled is None:+ return ast.Constant(value=0.0)+ if settled:+ continue+ given_true = assumed.get(reference) is True+ factors.append(self._probability_expr(reference, requested, depth, seen, child_assumed, given_true))+ return _product(factors) if factors else ast.Constant(value=1.0)++ def _probability_expr(+ self,+ reference: str,+ requested: bool | str,+ depth: int,+ seen: frozenset[int],+ assumed: dict[str, bool | str],+ given_true: bool = False,+ ) -> ast.Expr:+ self._dependency_nodes += 1+ if self._dependency_nodes > MAX_DEPENDENCY_NODES or depth >= MAX_DEPENDENCY_DEPTH:+ raise _DependencyBudgetExceeded()++ flag = self._find_flag(reference)+ if flag is None or detect_config_format(flag.get_filters()).kind != "v1":+ raise _DependencyMissing()+ if not flag.active:+ # A disabled dependency is pre-seeded as false, so the flags service still evaluates the+ # dependent flag against it.+ return ast.Constant(value=1.0 if requested is False else 0.0)+ if flag.pk in seen or _has_unmodeled_evaluation(flag):+ return ast.Constant(value=NEUTRAL)++ admitted_by_set = self._admitted_probabilities(flag, depth, seen | {flag.pk}, assumed)+ if admitted_by_set is None:+ return ast.Constant(value=NEUTRAL)++ if isinstance(requested, bool):+ return _from_true_probability(requested, _running_max(admitted_by_set))+ variant = self._variant_probability(flag, admitted_by_set, requested)+ if not given_true:+ return variant+ # The enclosing conjunction already drew `true`, so only the variant's share of it is new.+ served = _running_max([self._clone(admitted) for admitted in admitted_by_set])+ return ast.Call(+ name="if",+ args=[+ ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=served, right=ast.Constant(value=0.0)),+ ast.ArithmeticOperation(op=ast.ArithmeticOperationOp.Div, left=variant, right=self._clone(served)),+ ast.Constant(value=0.0),+ ],+ )++ def _find_flag(self, reference: str) -> Optional[FeatureFlag]:+ # The flags service resolves a dependency by id only, so a key reference never matches.+ flag_id = safe_int(reference)+ if flag_id is None:+ return None+ if flag_id not in self._flags:+ self._flags[flag_id] = FeatureFlag.objects.filter(+ team__project_id=self.team.project_id, deleted=False, pk=flag_id+ ).first()+ return self._flags[flag_id]++ def _admitted_probabilities(+ self, flag: FeatureFlag, depth: int, seen: frozenset[int], assumed: dict[str, bool | str]+ ) -> Optional[list[ast.Expr]]:+ """+ One expression per condition set, in stored order: the probability that the set's targeting+ matches the person and its rollout admits them. None when a set cannot be sized per person.+ """+ admitted: list[ast.Expr] = []+ for condition in flag.conditions:+ if _is_group_aggregated(flag, condition):+ return None+ rollout_percentage = condition.get("rollout_percentage")+ rollout = 1.0 if rollout_percentage is None else float(rollout_percentage) / 100+ factors: list[ast.Expr] = [ast.Constant(value=rollout)]++ properties = condition.get("properties") or []+ plain_properties = [prop for prop in properties if prop.get("type") != "flag"]+ if plain_properties:+ try:+ cleaned = self.clean_condition(self.team, {"properties": plain_properties})+ targeting = property_to_expr(cleaned.property_groups, self.team, scope="person")+ except _TARGETING_BUILD_ERRORS:+ return None+ factors.append(self._indicator(targeting))+ nested = [(str(prop.get("key")), prop.get("value")) for prop in properties if prop.get("type") == "flag"]+ if nested:+ factors.append(self._conjunction_expr(nested, depth + 1, seen, assumed))++ admitted.append(_product(factors))+ return admitted++ def _variant_probability(self, flag: FeatureFlag, admitted_by_set: list[ast.Expr], variant: str) -> ast.Expr:+ variant_keys = {v.get("key") for v in flag.variants}+ hashed_variant_share = next(+ (float(v.get("rollout_percentage") or 0) / 100 for v in flag.variants if v.get("key") == variant), 0.0+ )++ terms: list[ast.Expr] = []+ for index, condition in enumerate(flag.conditions):+ pinned = condition.get("variant")+ if pinned in variant_keys:+ share = 1.0 if pinned == variant else 0.0+ else:+ share = hashed_variant_share+ if share == 0:+ continue+ # The set wins only for the slice of the hash range above every earlier admitted set.+ # Each running max is a flat array, so the depth stays constant however many sets.+ up_to_here = _running_max([self._clone(admitted) for admitted in admitted_by_set[: index + 1]])+ before = _running_max([self._clone(admitted) for admitted in admitted_by_set[:index]])+ won = ast.ArithmeticOperation(op=ast.ArithmeticOperationOp.Sub, left=up_to_here, right=before)+ terms.append(_product([won, ast.Constant(value=share)]))+ if not terms:+ return ast.Constant(value=0.0)+ return ast.Call(name="arraySum", args=[ast.Array(exprs=terms)])++ def _indicator(self, predicate: ast.Expr) -> ast.Expr:+ self._charge(predicate)+ return ast.Call(name="if", args=[predicate, ast.Constant(value=1.0), ast.Constant(value=0.0)])++ def _clone(self, expr: ast.Expr) -> ast.Expr:+ self._charge(expr)+ return clone_expr(expr)++ def _charge(self, expr: ast.Expr) -> None:+ self._ast_nodes += _count_nodes(expr)+ if self._ast_nodes > MAX_WEIGHT_AST_NODES:+ raise _DependencyBudgetExceeded()+++def _conjunction_properties(group: PropertyGroup) -> Optional[list[Property]]:+ """The properties an AND tree requires together, or None when the tree holds an OR group."""+ if group.type == PropertyOperatorType.OR and len(group.values) > 1:+ return None+ properties: list[Property] = []+ for value in group.values:+ if isinstance(value, Property):+ properties.append(value)+ continue+ nested = _conjunction_properties(value)+ if nested is None:+ return None+ properties.extend(nested)+ return properties+++def _merge_requested_values(references: list[tuple[str, Any]]) -> Optional[dict[str, bool | str]]:+ """+ The one value each dependency flag must evaluate to, keyed by reference. None when two+ filters on the same flag contradict each other. `true` matches any served variant, so it+ narrows to a variant requested alongside it.+ """+ merged: dict[str, bool | str] = {}+ for reference, value in references:+ requested = _requested_value(value)+ previous = merged.get(reference)+ if previous is None or previous == requested or (previous is True and requested is not False):+ merged[reference] = requested+ elif requested is True and previous is not False:+ continue+ else:+ return None+ return merged+++def _settled_by(assumed: bool | str | None, requested: bool | str) -> Optional[bool]:+ """+ Whether a value an enclosing conjunction already fixed decides this request: True when it+ implies it, None when it contradicts it, False when the request needs its own probability.+ """+ if assumed is None:+ return False+ if _merge_requested_values([("flag", assumed), ("flag", requested)]) is None:+ return None+ # A variant implies `true`; `true` does not imply a variant, which keeps its own share.+ return assumed == requested or (requested is True and isinstance(assumed, str))+++class _NodeCounter(TraversingVisitor):+ def __init__(self) -> None:+ super().__init__()+ self.count = 0++ def visit(self, node: ast.AST | None) -> None:+ self.count += 1+ return super().visit(node)+++def _count_nodes(expr: ast.Expr) -> int:+ counter = _NodeCounter()+ counter.visit(expr)+ return counter.count+++def _from_true_probability(requested: bool, true_probability: ast.Expr) -> ast.Expr:+ if requested:+ return true_probability+ return ast.ArithmeticOperation(+ op=ast.ArithmeticOperationOp.Sub, left=ast.Constant(value=1.0), right=true_probability+ )+++def _requested_value(value: Any) -> bool | str:+ # The flags service compares a string value against the served variant name only, so a+ # string "true" is a variant name, not the boolean.+ if isinstance(value, bool):+ return value+ return str(value)+++def _has_unmodeled_evaluation(flag: FeatureFlag) -> bool:+ filters = flag.get_filters()+ return any(filters.get(key) for key in _UNMODELED_FILTER_KEYS)+++def _is_group_aggregated(flag: FeatureFlag, condition: dict[str, Any]) -> bool:+ if "aggregation_group_type_index" in condition:+ return condition["aggregation_group_type_index"] is not None+ return flag.aggregation_group_type_index is not None+++def _running_max(exprs: list[ast.Expr]) -> ast.Expr:+ # A flat array rather than nested greatest() calls, so a flag with hundreds of sets does not+ # exhaust the recursion limit in the visitors and the printer.+ return ast.Call(name="arrayMax", args=[ast.Array(exprs=[ast.Constant(value=0.0), *exprs])])+++def _product(factors: list[ast.Expr]) -> ast.Expr:+ result = factors[0]+ for factor in factors[1:]:+ result = ast.ArithmeticOperation(op=ast.ArithmeticOperationOp.Mult, left=result, right=factor)+ return resultdiff --git a/products/feature_flags/backend/facade/filters.py b/products/feature_flags/backend/facade/filters.pyindex 9b01caec19ef..150b7390baa6 100644--- a/products/feature_flags/backend/facade/filters.py+++ b/products/feature_flags/backend/facade/filters.py@@ -16,6 +16,13 @@ from typing import LiteralCohortRestrictionBlocker = Literal["group_aggregation", "holdout", "super_groups", "no_groups"]+# Flag-level settings the flags service evaluates before, or instead of, the release conditions.+# A holdout returns `holdout-<id>` to its share, legacy super groups short-circuit the same way,+# and `early_exit` returns false on a failed rollout instead of falling through to a later set.+EVALUATED_BEFORE_RELEASE_CONDITIONS: frozenset[str] = frozenset(+ {"holdout", "holdout_groups", "super_groups", "early_exit"}+)+def restrict_groups_to_cohort(current_filters: dict,diff --git a/products/feature_flags/backend/person_sampling.py b/products/feature_flags/backend/person_sampling.pyindex 2676bf8c98d7..e9a22e2d54f7 100644--- a/products/feature_flags/backend/person_sampling.py+++ b/products/feature_flags/backend/person_sampling.py@@ -65,6 +65,22 @@ def count_settings(sample_modulus: Optional[int]) -> HogQLGlobalSettings:return bounded_memory_settings()+def sampled_or_exact_estimate(run: Callable[[Optional[int]], tuple[int, float]]) -> int:+ """+ Estimate from a 1-in-SAMPLE_MODULUS sample and extrapolate, or exactly when the sample holds+ too few matches for a stable extrapolation.++ `run` takes the sample modulus, or None for an exact run, and returns the number of matched+ persons with the estimate to extrapolate. The threshold reads the match count and not the+ estimate, because the noise of the extrapolation depends on how many persons the sample+ holds, not on how much each of them weighs.+ """+ matched, estimate = run(SAMPLE_MODULUS)+ if matched >= MIN_SAMPLED_MATCHES:+ return int(round(estimate * SAMPLE_MODULUS))+ return int(round(run(None)[1]))++def sampled_or_exact_count(run_count: Callable[[Optional[int]], int]) -> int:"""Count from a 1-in-SAMPLE_MODULUS sample and extrapolate, or exactly when the sample holds@@ -72,23 +88,37 @@ def sampled_or_exact_count(run_count: Callable[[Optional[int]], int]) -> int:`run_count` takes the sample modulus, or None for an exact run."""- sampled = run_count(SAMPLE_MODULUS)- if sampled >= MIN_SAMPLED_MATCHES:- return sampled * SAMPLE_MODULUS- return run_count(None)+ def run(sample_modulus: Optional[int]) -> tuple[int, float]:+ count = run_count(sample_modulus)+ return count, count++ return sampled_or_exact_estimate(run)+++def count_matching_persons(+ team: Team, filter: Optional[Filter], database: Database, query_type: str, weight: Optional[ast.Expr] = None+) -> int:+ """+ Count the persons a filter matches, or every person on the team when filter is None.-def count_matching_persons(team: Team, filter: Optional[Filter], database: Database, query_type: str) -> int:- """Count the persons a filter matches, or every person on the team when filter is None."""- return sampled_or_exact_count(- lambda sample_modulus: _run_person_count(team, filter, database, query_type, sample_modulus)+ `weight` is a per-person probability expression. With it, the result is the sum of the+ weights over the matched persons instead of their number.+ """+ return sampled_or_exact_estimate(+ lambda sample_modulus: _run_person_count(team, filter, database, query_type, sample_modulus, weight))def _run_person_count(- team: Team, filter: Optional[Filter], database: Database, query_type: str, sample_modulus: Optional[int]-) -> int:- query = build_person_count_query(team, filter, sample_modulus=sample_modulus)+ team: Team,+ filter: Optional[Filter],+ database: Database,+ query_type: str,+ sample_modulus: Optional[int],+ weight: Optional[ast.Expr] = None,+) -> tuple[int, float]:+ query = build_person_count_query(team, filter, sample_modulus=sample_modulus, weight=weight)response = execute_hogql_query(query=query,team=team,@@ -104,10 +134,24 @@ def _run_person_count(context=HogQLContext(team_id=team.pk, database=database),settings=count_settings(sample_modulus),)- return response.results[0][0] if response.results else 0+ return read_person_count(response.results, weighted=weight is not None)++def read_person_count(results: list, weighted: bool) -> tuple[int, float]:+ """The matched persons and the estimate from a `build_person_count_query` result row."""+ if not results:+ return 0, 0.0+ matched = results[0][0]+ return matched, ((results[0][1] or 0.0) if weighted else matched)-def build_person_count_query(team: Team, filter: Optional[Filter], sample_modulus: Optional[int]) -> ast.SelectQuery:++def build_person_count_query(+ team: Team, filter: Optional[Filter], sample_modulus: Optional[int], weight: Optional[ast.Expr] = None+) -> ast.SelectQuery:+ """+ Count the persons a filter matches. With `weight`, the query returns the number of matched+ persons and the sum of one weight per person.+ """where_exprs: list[ast.Expr] = [ast.CompareOperation(op=ast.CompareOperationOp.Eq,@@ -120,19 +164,35 @@ def build_person_count_query(team: Team, filter: Optional[Filter], sample_moduluif filter is not None:where_exprs.append(property_to_expr(filter.property_groups, team, scope="person"))- # A filter can add a one-to-many join: a `distinct_id` person property resolves through- # persons.pdi, which gives a person one row per distinct id. So a filtered count dedups on- # the person id. The unfiltered total joins nothing, so it keeps the plain count() and- # avoids a uniqExact state over every person on the team.- if filter is None:- count_expr: ast.Expr = ast.Call(name="count", args=[])- else:- count_expr = ast.Call(name="count", distinct=True, args=[ast.Field(chain=["persons", "id"])])+ if weight is None:+ # A filter can add a one-to-many join: a `distinct_id` person property resolves through+ # persons.pdi, which gives a person one row per distinct id. So a filtered count dedups on+ # the person id. The unfiltered total joins nothing, so it keeps the plain count() and+ # avoids a uniqExact state over every person on the team.+ if filter is None:+ count_expr: ast.Expr = ast.Call(name="count", args=[])+ else:+ count_expr = ast.Call(name="count", distinct=True, args=[ast.Field(chain=["persons", "id"])])+ return ast.SelectQuery(+ select=[count_expr],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ where=ast.And(exprs=where_exprs),+ )- return ast.SelectQuery(- select=[count_expr],+ # One weight per person, deduped with a GROUP BY rather than a DISTINCT: the GROUP BY can+ # stream in id order and spill to disk under count_settings, which a DISTINCT cannot.+ per_person = ast.SelectQuery(+ select=[+ ast.Field(chain=["persons", "id"]),+ ast.Alias(alias="weight", expr=ast.Call(name="max", args=[weight])),+ ],select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),where=ast.And(exprs=where_exprs),+ group_by=[ast.Field(chain=["persons", "id"])],+ )+ return ast.SelectQuery(+ select=[ast.Call(name="count", args=[]), ast.Call(name="sum", args=[ast.Field(chain=["weight"])])],+ select_from=ast.JoinExpr(table=per_person),)diff --git a/products/feature_flags/backend/temporal/health_checks/stale_flags.py b/products/feature_flags/backend/temporal/health_checks/stale_flags.pyindex 92470cedffcd..e52f387b5ed8 100644--- a/products/feature_flags/backend/temporal/health_checks/stale_flags.py+++ b/products/feature_flags/backend/temporal/health_checks/stale_flags.py@@ -17,6 +17,7 @@ from posthog.temporal.health_checks.models import HealthCheckResultfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.facade.config import detect_config_format+from products.feature_flags.backend.facade.filters import EVALUATED_BEFORE_RELEASE_CONDITIONSfrom products.feature_flags.backend.flag_status import (ROLLOUT_FULLY_ROLLED_OUT,ROLLOUT_NOT_ROLLED_OUT,@@ -239,15 +240,12 @@ def _serves_more_than_one_result(flag: FeatureFlag) -> bool:which none of this contradicts."""filters = flag.filters or {}- # A holdout is resolved before the release conditions and returns `holdout-<id>` to its share,- # legacy super groups short-circuit the same way, and `early_exit` returns false on a failed- # rollout check instead of falling through to a later blanket condition.# Two siblings encode part of the same evaluation order. `group_cohort_restriction_blocker` in# `products/feature_flags/backend/facade/filters.py` reads `holdout`, `holdout_groups` and# `super_groups`. `is_unconditionally_fully_rolled_out` in# `products/feature_flags/backend/persisted_flags.py` reads `holdout` and `super_groups`.- # Neither reads `early_exit`, so the three lists have never been in parity.- if any(filters.get(key) for key in ("holdout", "holdout_groups", "super_groups", "early_exit")):+ # Neither reads `early_exit`, so those two have never been in parity with this list.+ if any(filters.get(key) for key in EVALUATED_BEFORE_RELEASE_CONDITIONS):return True# These three decide the result from evaluation context the configuration does not carry, so a# blanket condition does not reach everyone. A group-aggregated condition is skipped for adiff --git a/products/feature_flags/backend/test/test_blast_radius_v2.py b/products/feature_flags/backend/test/test_blast_radius_v2.pyindex a80826197ce6..7a5c9dbf0e03 100644--- a/products/feature_flags/backend/test/test_blast_radius_v2.py+++ b/products/feature_flags/backend/test/test_blast_radius_v2.py@@ -7,6 +7,7 @@ from parameterized import parameterizedfrom posthog.models.team.team import Team+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.user_blast_radius import (BlastRadiusResult,get_person_blast_radius_v2,@@ -46,6 +47,31 @@ class TestBlastRadiusQueryV2(ClickhouseTestMixin, APIBaseTest):assert (result.affected, result.total) == (affected, total)assert (result.affected, result.total) == (v1_result.affected, v1_result.total)+ def test_flag_dependency_is_weighted_on_both_paths(self):+ self._create_persons([True, True, True, False])+ dependency_flag = FeatureFlag.objects.create(+ team=self.team,+ key="dependency-flag",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},+ )+ filters = {+ "properties": [+ {"key": str(dependency_flag.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ]+ }++ # Both paths must weight the dependency: a v2 count that neutralizes it returns every person.+ v1_result = get_user_blast_radius(self.team, filters)+ assert (v1_result.affected, v1_result.total) == (2, 4)+ assert get_person_blast_radius_v2(self.team, filters) == v1_result++ with (+ patch("products.feature_flags.backend.person_sampling.SAMPLE_MODULUS", 1),+ patch("products.feature_flags.backend.person_sampling.MIN_SAMPLED_MATCHES", 0),+ ):+ assert get_person_blast_radius_v2(self.team, filters) == v1_result+def test_sampled_path_extrapolates_by_modulus(self):self._create_persons([True, True, False])diff --git a/products/feature_flags/backend/test/test_person_sampling.py b/products/feature_flags/backend/test/test_person_sampling.pyindex cd2a6a3e74cb..6bec32b78a77 100644--- a/products/feature_flags/backend/test/test_person_sampling.py+++ b/products/feature_flags/backend/test/test_person_sampling.py@@ -11,6 +11,7 @@ from products.feature_flags.backend.person_sampling import (bounded_memory_settings,count_settings,sampled_or_exact_count,+ sampled_or_exact_estimate,)@@ -62,3 +63,15 @@ class TestSampledOrExactCount(SimpleTestCase):assert sampled_or_exact_count(run_count) == self.EXACT_COUNT# The probe still runs and is paid for before the exact count replaces it.assert moduli == [SAMPLE_MODULUS, None]++ def test_the_threshold_reads_the_matched_count_and_not_the_estimate(self):+ moduli: list[Optional[int]] = []++ def run(sample_modulus: Optional[int]) -> tuple[int, float]:+ moduli.append(sample_modulus)+ # A large audience behind a low-rollout dependency: many matches, a small weight sum.+ return (MIN_SAMPLED_MATCHES, 3.0) if sample_modulus is not None else (self.EXACT_COUNT, 5.0)++ assert sampled_or_exact_estimate(run) == round(3.0 * SAMPLE_MODULUS)+ # Comparing the estimate against the threshold would rerun the exact query here.+ assert moduli == [SAMPLE_MODULUS]diff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.pyindex fc1682af861a..de498803b37f 100644--- a/products/feature_flags/backend/user_blast_radius.py+++ b/products/feature_flags/backend/user_blast_radius.py@@ -29,7 +29,13 @@ from posthog.models.team.team import Teamfrom posthog.ph_client import feature_enabled_or_falsefrom products.cohorts.backend.models.cohort import Cohort-from products.feature_flags.backend.person_sampling import count_matching_persons+from products.feature_flags.backend.blast_radius_flag_deps import FlagDependencyEstimator+from products.feature_flags.backend.person_sampling import (+ build_person_count_query,+ count_matching_persons,+ count_settings,+ read_person_count,+)@frozen@@ -77,7 +83,15 @@ def sampled_person_blast_radius(team: Team, filter: Filter, query_type: str) ->if len(filter.property_groups.flat) == 0:return BlastRadiusResult(affected=total, total=total)- affected = count_matching_persons(team, filter, database, query_type=query_type)+ weight = _flag_dependency_weight(team, filter)+ try:+ affected = count_matching_persons(team, filter, database, query_type=query_type, weight=weight)+ except InternalCHQueryError as e:+ if weight is None or e.code not in _VALUE_PARSE_CH_ERROR_CODES:+ raise+ # A dependency's stored targeting failed a cast in ClickHouse. Its configuration is not+ # the caller's input, so the dependency sizes neutrally instead of failing the request.+ affected = count_matching_persons(team, filter, database, query_type=query_type)return BlastRadiusResult(affected=min(affected, total), total=total)@@ -216,43 +230,63 @@ def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:total_users = team.persons_seen_so_farreturn BlastRadiusResult(affected=total_users, total=total_users)- # Build the SELECT query - property_to_expr handles all properties including cohorts- select_query = _build_person_query(team, filter, return_count=True)-- # Execute the querytag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY)# Build the team's HogQL database once and share it between the two counts below.# Each execute_hogql_query call would otherwise build its own, and the build cost# scales with the team's warehouse size.database = Database.create_for(team=team)+ weight = _flag_dependency_weight(team, filter)+ try:+ estimate = _run_exact_person_count(team, filter, database, weight)+ except InternalCHQueryError as e:+ if weight is None or e.code not in _VALUE_PARSE_CH_ERROR_CODES:+ raise+ # A dependency's stored targeting failed a cast in ClickHouse. Its configuration is not+ # the caller's input, so the dependency sizes neutrally instead of failing the request.+ estimate = _run_exact_person_count(team, filter, database, weight=None)+ # A condition with a flag dependency sums per-person match probabilities, so the count is a float.+ total_count = int(round(estimate))+ total_users = team.count_persons_seen_so_far(database=database)+ blast_radius = min(total_count, total_users)++ return BlastRadiusResult(affected=blast_radius, total=total_users)+++def _run_exact_person_count(team: Team, filter: Filter, database: Database, weight: Optional[ast.Expr]) -> float:+ # property_to_expr handles all properties including cohorts+ select_query = build_person_count_query(team, filter, sample_modulus=None, weight=weight)response = execute_hogql_query(query=select_query,team=team,context=HogQLContext(team_id=team.pk, database=database),+ # The weighted count groups by person, so it takes the settings that let that aggregation+ # stream in id order and spill to disk. The plain count keeps its historical defaults.+ settings=count_settings(None) if weight is not None else None,)+ return read_person_count(response.results, weighted=weight is not None)[1]- total_count = response.results[0][0] if response.results else 0- total_users = team.count_persons_seen_so_far(database=database)- blast_radius = min(total_count, total_users)- return BlastRadiusResult(affected=blast_radius, total=total_users)+def _flag_dependency_weight(team: Team, filter: Filter) -> Optional[ast.Expr]:+ """+ Per-person probability that the condition's flag dependencies evaluate to their requested+ values, or None when the condition has none. property_to_expr neutralizes flag properties, so+ the count paths weight each person by this instead. The persons listing stays unweighted and+ lists everyone the plain filters match.+ """+ group = filter.property_groups+ if not any(prop.type == "flag" for prop in group.flat):+ return None+ return FlagDependencyEstimator(team, clean_condition=replace_proxy_properties).weight_expr(group)-def _build_person_query(team: Team, filter: Filter, return_count: bool = True, cursor: Optional[str] = None):- """Build HogQL AST query to count or select distinct persons matching filters."""+def _build_person_query(team: Team, filter: Filter, cursor: Optional[str] = None) -> ast.SelectQuery:+ """Build HogQL AST query to select distinct persons matching filters, paginated by id."""- # Build the main SELECT with either count(DISTINCT persons.id) or DISTINCT persons.id- if return_count:- select_query = ast.SelectQuery(- select=[ast.Call(name="count", distinct=True, args=[ast.Field(chain=["persons", "id"])])],- select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),- )- else:- select_query = ast.SelectQuery(- select=[ast.Field(chain=["persons", "id"])],- select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),- distinct=True,- )+ select_query = ast.SelectQuery(+ select=[ast.Field(chain=["persons", "id"])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ distinct=True,+ )# Build WHERE clause with team_id and property filters# property_to_expr handles all property types including cohorts@@ -268,8 +302,8 @@ def _build_person_query(team: Team, filter: Filter, return_count: bool = True, cproperty_expr = property_to_expr(filter.property_groups, team, scope="person")where_exprs.append(property_expr)- # Add cursor-based pagination when returning IDs- if not return_count and cursor is not None:+ # Add cursor-based pagination+ if cursor is not None:where_exprs.append(ast.CompareOperation(op=ast.CompareOperationOp.Gt,@@ -281,10 +315,8 @@ def _build_person_query(team: Team, filter: Filter, return_count: bool = True, c# Combine all WHERE expressions with ANDselect_query.where = ast.And(exprs=where_exprs)- # Add ORDER BY and LIMIT for pagination when returning IDs- if not return_count:- select_query.order_by = [ast.OrderExpr(expr=ast.Field(chain=["persons", "id"]), order="ASC")]- select_query.limit = ast.Constant(value=500)+ select_query.order_by = [ast.OrderExpr(expr=ast.Field(chain=["persons", "id"]), order="ASC")]+ select_query.limit = ast.Constant(value=500)return select_query@@ -572,7 +604,7 @@ def _get_person_blast_radius_persons(team: Team, filter: Filter, cursor: Optiona"""Get distinct person IDs matching person-based feature flag filters."""# Build the SELECT query to get person IDs- select_query = _build_person_query(team, filter, return_count=False, cursor=cursor)+ select_query = _build_person_query(team, filter, cursor=cursor)tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY)response = execute_hogql_query(