: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): resolve group conditions against group properties in test evaluation (#68646)
posthog[bot]c3c3dd75ef6b
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 8f6a25ddfafb..cee49b3874de 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -3838,12 +3838,21 @@ class FeatureFlagViewSet(return Response({"error": "Failed to resolve person"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)if not person or not distinct_ids:- identifier_type = "distinct_id" if distinct_id else "person_id"- identifier_value = distinct_id or person_id- return Response(- {"detail": f"Person not found for {identifier_type}: {identifier_value}"},- status=status.HTTP_404_NOT_FOUND,- )+ # A person may legitimately not exist yet. Server-to-server and webhook+ # automations commonly evaluate with a synthetic distinct_id plus the+ # ``groups`` param and never identify a person, so group-only and+ # rollout-by-distinct_id conditions must still be evaluable. When the caller+ # gave us a distinct_id, fall through with it (empty person properties);+ # only fail when a person_id we couldn't resolve was supplied, since then+ # there is no distinct_id to bucket on.+ if distinct_id:+ person = None+ distinct_ids = [distinct_id]+ else:+ return Response(+ {"detail": f"Person not found for person_id: {person_id}"},+ status=status.HTTP_404_NOT_FOUND,+ )# Prefer the caller-provided distinct_id for evaluation when it resolves to this person,# since rollout/variant assignment can depend on the exact distinct_id used.@@ -3884,8 +3893,8 @@ class FeatureFlagViewSet(status=status.HTTP_500_INTERNAL_SERVER_ERROR,)else:- # Use current person properties- person_properties = person.properties or {}+ # Use current person properties (empty when the identity has no person yet)+ person_properties = (person.properties or {}) if person else {}# If timestamp is provided, reconstruct the flag at that point in time.# ``evaluation_filters`` is what we hand to _filter_person_properties_for_flagdiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 79409e2d7aae..7838b66513ce 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -12961,18 +12961,59 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("Cannot provide both distinct_id and person_id", response.json()["detail"])- def test_test_evaluation_person_not_found(self):- """Test 404 when person doesn't exist."""+ def test_test_evaluation_person_id_not_found(self):+ """A person_id we can't resolve still 404s — there's no distinct_id to bucket on."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")+ missing_person_id = "00000000-0000-0000-0000-000000000000"response = self.client.post(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",- {"distinct_id": "nonexistent-user"},+ {"person_id": missing_person_id},format="json",)self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- self.assertEqual(response.json()["detail"], "Person not found for distinct_id: nonexistent-user")+ self.assertEqual(response.json()["detail"], f"Person not found for person_id: {missing_person_id}")++ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_person_and_distinct_ids_for_identifier")+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")+ def test_test_evaluation_distinct_id_without_person(self, mock_get_person, mock_get_flags):+ """A synthetic distinct_id with no person (server-to-server / webhook automation,+ groups-only) must still evaluate instead of 404ing — bucketing on the given+ distinct_id with empty person properties."""+ flag = FeatureFlag.objects.create(team=self.team, key="org-flag")++ # No person resolves for this distinct_id.+ mock_get_person.return_value = (None, [])++ mock_get_flags.return_value = {+ "flags": {+ "org-flag": {+ "enabled": True,+ "variant": None,+ "reason": {"code": "condition_match", "condition_index": 0},+ "metadata": {"payload": None},+ "conditions": [],+ }+ }+ }++ response = self.client.post(+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",+ {"distinct_id": "webhook-synthetic-id", "groups": {"organization": "org_123"}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["result"], True)+ # Bucketing uses the provided distinct_id and it is echoed back.+ self.assertEqual(mock_get_flags.call_args.kwargs["distinct_id"], "webhook-synthetic-id")+ self.assertEqual(mock_get_flags.call_args.kwargs["groups"], {"organization": "org_123"})+ self.assertEqual(data["evaluation_distinct_id"], "webhook-synthetic-id")+ # No person → empty person properties passed to the evaluation service.+ self.assertEqual(mock_get_flags.call_args.kwargs["person_properties"], {})@patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="")diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rsindex d222439e1232..ffdc12848675 100644--- a/rust/feature-flags/src/api/types.rs+++ b/rust/feature-flags/src/api/types.rs@@ -1,4 +1,5 @@use crate::api::errors::FlagError;+use crate::flags::flag_group_type_mapping::GroupTypeIndex;use crate::flags::flag_match_reason::FeatureFlagMatchReason;use crate::flags::flag_matching::FeatureFlagMatch;use crate::flags::flag_matching_utils::match_flag_value_to_flag_filter;@@ -474,6 +475,7 @@ pub trait FromFeatureAndMatch {flag_match: &FeatureFlagMatch,detailed_analysis: bool,property_values: Option<&HashMap<String, Value>>,+ group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,team_timezone: Tz,) -> Self;@@ -484,7 +486,7 @@ pub trait FromFeatureAndMatch {impl FromFeatureAndMatch for FlagDetails {fn create(flag: &FeatureFlag, flag_match: &FeatureFlagMatch) -> Self {// Timezone is only consulted for detailed analysis, which is off here.- Self::create_with_analysis(flag, flag_match, false, None, None, Tz::UTC)+ Self::create_with_analysis(flag, flag_match, false, None, None, None, Tz::UTC)}fn create_with_analysis(@@ -492,6 +494,7 @@ impl FromFeatureAndMatch for FlagDetails {flag_match: &FeatureFlagMatch,detailed_analysis: bool,property_values: Option<&HashMap<String, Value>>,+ group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,team_timezone: Tz,) -> Self {@@ -517,6 +520,7 @@ impl FromFeatureAndMatch for FlagDetails {flag,flag_match,property_values,+ group_property_values,flag_evaluation_results,team_timezone,))@@ -581,6 +585,7 @@ impl FlagDetails {flag: &FeatureFlag,flag_match: &FeatureFlagMatch,property_values: Option<&HashMap<String, Value>>,+ group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,team_timezone: Tz,) -> Vec<ConditionAnalysis> {@@ -591,6 +596,14 @@ impl FlagDetails {let mut property_analyses = Vec::new();let mut condition_matched = false;+ // Effective aggregation for this condition: the per-condition group type+ // when set, otherwise the flag-level one. Used to resolve legacy group+ // filters that don't carry their own `group_type_index`. Mirrors the+ // aggregation the real matching path uses (flag_matching.rs), so an+ // explicit person aggregation (`Some(None)`) does not fall back to the+ // flag-level group index here.+ let effective_aggregation = group.effective_aggregation(flag.get_group_type_index());+// Determine if this condition matched based on overall flag result and condition index// Only mark as matched if the flag itself matched AND this is the matching conditionif flag_match.matches {@@ -680,7 +693,21 @@ impl FlagDetails {_ => (operator_str.as_str(), "does not match"),};- let (property_matched, actual_value) = if let Some(props) = property_values {+ // Route each filter to the correct property namespace. Group-typed+ // filters (e.g. a group `name` or `$group_key`) must be resolved+ // against the named group's properties, not the person's — otherwise+ // a matching group condition reports `matched: false` with the+ // person's value (or null) as `actual_value`. Mirrors the routing in+ // `PropertyContext::resolve_for_filter` used during actual matching.+ let resolved_props = match property.prop_type {+ crate::properties::property_models::PropertyType::Group => {+ let gti = property.group_type_index.or(effective_aggregation);+ gti.and_then(|idx| group_property_values.and_then(|m| m.get(&idx)))+ }+ _ => property_values,+ };++ let (property_matched, actual_value) = if let Some(props) = resolved_props {let actual = props.get(&property.key).cloned();let matched =match_property(property, props, false, team_timezone).unwrap_or(false);@@ -1286,6 +1313,7 @@ mod tests {&flag_match,Some(&property_values),None,+ None,chrono_tz::Tz::UTC,);@@ -1320,6 +1348,170 @@ mod tests {);}+ #[test]+ fn test_condition_analysis_resolves_group_filters_against_group_properties() {+ use crate::flags::flag_models::FeatureFlag;+ use std::collections::HashMap;++ // A group-aggregated flag whose only condition targets a group property.+ let flag: FeatureFlag = serde_json::from_value(json!(+ {+ "id": 1,+ "team_id": 1,+ "name": "org-flag",+ "key": "org-flag",+ "active": true,+ "filters": {+ "aggregation_group_type_index": 0,+ "groups": [+ {+ "properties": [+ {+ "key": "name",+ "value": "Mjolnir - Test Org",+ "operator": "exact",+ "type": "group",+ "group_type_index": 0+ },+ {+ "key": "$group_key",+ "value": "org_123",+ "operator": "exact",+ "type": "group"+ // No explicit group_type_index: a legacy filter that must fall+ // back to the flag-level aggregation_group_type_index above.+ }+ ],+ "rollout_percentage": 100+ }+ ]+ }+ }+ ))+ .unwrap();++ let flag_match = FeatureFlagMatch {+ matches: true,+ variant: None,+ reason: FeatureFlagMatchReason::ConditionMatch,+ condition_index: Some(0),+ payload: None,+ };++ // The person happens to carry a conflicting `name`; it must not leak into the+ // group-typed condition analysis.+ let mut person_props = HashMap::new();+ person_props.insert("name".to_string(), json!("Hans Grønskag Hammer"));++ // Group properties keyed by group type index, with `$group_key` injected the way+ // request handling does for the `groups` param.+ let mut group_props_for_index = HashMap::new();+ group_props_for_index.insert("name".to_string(), json!("Mjolnir - Test Org"));+ group_props_for_index.insert("$group_key".to_string(), json!("org_123"));+ let group_props: HashMap<GroupTypeIndex, HashMap<String, Value>> =+ HashMap::from([(0, group_props_for_index)]);++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&person_props),+ Some(&group_props),+ None,+ chrono_tz::Tz::UTC,+ );++ assert_eq!(analysis.len(), 1);+ let props = &analysis[0].properties;+ assert_eq!(props.len(), 2);++ // Group `name` resolves against the group, not the person.+ assert_eq!(props[0].key, "name");+ assert!(props[0].matched, "group name should match");+ assert_eq!(props[0].actual_value, Some(json!("Mjolnir - Test Org")));++ // `$group_key` resolves from the injected group override rather than reporting null.+ assert_eq!(props[1].key, "$group_key");+ assert!(props[1].matched, "$group_key should match");+ assert_eq!(props[1].actual_value, Some(json!("org_123")));+ }++ #[test]+ fn test_condition_analysis_respects_explicit_person_aggregation_over_flag_level_group() {+ use crate::flags::flag_models::FeatureFlag;+ use std::collections::HashMap;++ // Flag-level group aggregation, but this condition explicitly overrides to person+ // aggregation (JSON `null`). A legacy group-typed filter with no `group_type_index`+ // must resolve against the (empty) person-aggregation namespace, not fall back to+ // the flag-level group index. Mirrors `FlagPropertyGroup::effective_aggregation`'s+ // `Some(None)` case, which the real matching path already honors.+ let flag: FeatureFlag = serde_json::from_value(json!(+ {+ "id": 1,+ "team_id": 1,+ "name": "org-flag",+ "key": "org-flag",+ "active": true,+ "filters": {+ "aggregation_group_type_index": 0,+ "groups": [+ {+ "aggregation_group_type_index": null,+ "properties": [+ {+ "key": "name",+ "value": "Mjolnir - Test Org",+ "operator": "exact",+ "type": "group"+ }+ ],+ "rollout_percentage": 100+ }+ ]+ }+ }+ ))+ .unwrap();++ // The flag did not match, so a filter that incorrectly falls back to the+ // flag-level group index and finds a real match there would flip `matched`+ // to true and leak the group's value as `actual_value` — the exact bug this+ // fix closes.+ let flag_match = FeatureFlagMatch {+ matches: false,+ variant: None,+ reason: FeatureFlagMatchReason::NoConditionMatch,+ condition_index: None,+ payload: None,+ };++ // Group 0's properties do carry a matching `name`, but the condition's explicit+ // person aggregation must prevent the filter from ever consulting them.+ let mut group_props_for_index = HashMap::new();+ group_props_for_index.insert("name".to_string(), json!("Mjolnir - Test Org"));+ let group_props: HashMap<GroupTypeIndex, HashMap<String, Value>> =+ HashMap::from([(0, group_props_for_index)]);++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ None,+ Some(&group_props),+ None,+ chrono_tz::Tz::UTC,+ );++ assert_eq!(analysis.len(), 1);+ let props = &analysis[0].properties;+ assert_eq!(props.len(), 1);+ assert_eq!(props[0].key, "name");+ assert!(+ !props[0].matched,+ "must fall back to the condition's own (unmatched) outcome, not the flag-level group's properties"+ );+ assert_eq!(props[0].actual_value, None);+ }+#[test]fn test_condition_analysis_resolves_flag_dependencies_against_flag_results() {use crate::flags::flag_models::FeatureFlag;@@ -1367,6 +1559,7 @@ mod tests {&flag,&flag_match,Some(&HashMap::new()),+ None,Some(&flag_results),chrono_tz::Tz::UTC,);@@ -1399,6 +1592,7 @@ mod tests {&flag,&flag_match,Some(&HashMap::new()),+ None,Some(&flag_results),chrono_tz::Tz::UTC,);@@ -1432,6 +1626,7 @@ mod tests {&flag,&flag_match,Some(&HashMap::new()),+ None,None, // empty — dependency flag 42 absentchrono_tz::Tz::UTC,);diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex fc67394332e0..488e7e4a4d9c 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -981,6 +981,7 @@ impl FeatureFlagMatcher {&mut level_evaluated_flags_map,&mut errors_while_computing_flags,person_property_overrides,+ group_property_overrides,);});}@@ -1003,6 +1004,7 @@ impl FeatureFlagMatcher {&mut level_evaluated_flags_map,&mut errors_while_computing_flags,person_property_overrides,+ group_property_overrides,);}}@@ -1031,6 +1033,7 @@ impl FeatureFlagMatcher {level_evaluated_flags_map: &mut HashMap<String, FlagDetails>,errors_while_computing_flags: &mut bool,person_property_overrides: &Option<HashMap<String, Value>>,+ group_property_overrides: &Option<HashMap<String, HashMap<String, Value>>>,) {match result {Ok(flag_match) => {@@ -1041,11 +1044,17 @@ impl FeatureFlagMatcher {let merged_person_props = self.get_person_properties(person_property_overrides.as_ref()).ok();+ // Merged group properties (DB + overrides, including the injected+ // `$group_key`) keyed by group type index, so group-typed condition+ // filters resolve against the group rather than the person.+ let merged_group_props =+ self.merged_group_properties_for_flag(flag, group_property_overrides);FlagDetails::create_with_analysis(flag,flag_match,true,merged_person_props.as_ref(),+ Some(&merged_group_props),Some(&self.flag_evaluation_state.flag_evaluation_results),self.timezone,)@@ -1096,6 +1105,45 @@ impl FeatureFlagMatcher {group_overrides.get(group_type)}+ /// Builds merged group properties (DB + overrides) keyed by group type index for+ /// every group type the flag's conditions reference. Used by detailed condition+ /// analysis so group-typed filters resolve against the group's properties (and the+ /// `$group_key` injected into overrides) rather than the person's. Every referenced+ /// group type index is included, backed by an empty map if no properties were found.+ fn merged_group_properties_for_flag(+ &self,+ flag: &FeatureFlag,+ group_property_overrides: &Option<HashMap<String, HashMap<String, Value>>>,+ ) -> HashMap<GroupTypeIndex, HashMap<String, Value>> {+ let mut referenced_indexes: HashSet<GroupTypeIndex> = HashSet::new();+ for group in &flag.filters.groups {+ // Mirrors the aggregation the real matching path uses (line ~1371 below), so+ // an explicit person aggregation (`Some(None)`) does not fall back to the+ // flag-level group index here.+ let condition_aggregation = group.effective_aggregation(flag.get_group_type_index());+ if let Some(properties) = &group.properties {+ for property in properties {+ if property.prop_type == PropertyType::Group {+ if let Some(gti) = property.group_type_index.or(condition_aggregation) {+ referenced_indexes.insert(gti);+ }+ }+ }+ }+ }++ let mut merged = HashMap::new();+ for gti in referenced_indexes {+ let overrides = self.resolve_group_overrides(gti, group_property_overrides.as_ref());+ merged.insert(+ gti,+ self.get_group_properties(gti, overrides)+ .unwrap_or_default(),+ );+ }+ merged+ }+/// Pushes CPU-bound flag evaluation onto the Rayon pool via [`RayonDispatcher`],/// so the calling Tokio worker thread is free to serve other requests while/// evaluation runs. The dispatcher bounds how many batches can be in-flightdiff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex 30c2fc7c1a53..c91ec747b684 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -495,6 +495,116 @@ mod tests {);}+ /// Regression test: detailed condition analysis must resolve a group-typed filter+ /// against the group's properties, not the person's, through the full+ /// `evaluate_all_feature_flags` -> `process_flag_result` -> `merged_group_properties_for_flag`+ /// wiring (not just `FlagDetails::build_condition_analysis` in isolation).+ #[tokio::test]+ async fn test_detailed_analysis_resolves_group_filters_against_group_properties() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let flag = mock!(FeatureFlag,+ team_id: team.id,+ filters: FlagFilters {+ groups: vec![FlagPropertyGroup {+ properties: Some(vec![+ mock!(PropertyFilter,+ key: "plan".mock_into(),+ value: Some(json!("pro")),+ prop_type: PropertyType::Person+ ),+ mock!(PropertyFilter,+ key: "industry".mock_into(),+ value: Some(json!("tech")),+ prop_type: PropertyType::Group,+ group_type_index: Some(1)+ ),+ ]),+ rollout_percentage: Some(100.0),+ variant: None,+ ..Default::default()+ }],+ multivariate: None,+ aggregation_group_type_index: Some(1),+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: None,+ extra: Default::default(),+ }+ );++ let group_type_cache =+ mock_group_type_cache([("organization".to_string(), 1)].into_iter().collect());++ let groups = HashMap::from([("organization".to_string(), json!("org_123"))]);++ // The person carries a conflicting `industry` value; it must not leak into the+ // group-typed condition's analysis.+ let person_overrides = HashMap::from([+ ("plan".to_string(), json!("pro")),+ ("industry".to_string(), json!("finance")),+ ]);+ let group_overrides = HashMap::from([(+ "organization".to_string(),+ HashMap::from([("industry".to_string(), json!("tech"))]),+ )]);++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None, // device_id+ team.id,+ context.create_postgres_router(),+ cohort_cache.clone(),+ group_type_cache,+ Some(groups),+ )+ .with_detailed_analysis(true);++ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ Some(group_overrides),+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ assert!(!result.errors_while_computing_flags);+ let flag_details = result.flags.get("test_flag").unwrap();+ assert_eq!(flag_details.to_value(), FlagValue::Boolean(true));++ let conditions = flag_details+ .conditions+ .as_ref()+ .expect("detailed_analysis(true) should populate conditions");+ assert_eq!(conditions.len(), 1);+ let properties = &conditions[0].properties;+ assert_eq!(properties.len(), 2);++ let plan_analysis = properties.iter().find(|p| p.key == "plan").unwrap();+ assert!(plan_analysis.matched);+ assert_eq!(plan_analysis.actual_value, Some(json!("pro")));++ let industry_analysis = properties.iter().find(|p| p.key == "industry").unwrap();+ assert!(+ industry_analysis.matched,+ "group-typed filter should resolve against group properties, not the person's"+ );+ assert_eq!(industry_analysis.actual_value, Some(json!("tech")));+ }+/// Helper to create a dependency filter for flag-depends-on-flag patterns.fn dep_filter(flag_id: i32, value: FlagValue) -> PropertyFilter {mock!(crate::properties::property_models::PropertyFilter,