Skip to content

: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.

fix(flags): resolve cohort conditions against membership in flag tester (#90646)

Ben Lea931c261efc82
diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rs
index b14cfc887dae..e5ef0b7b3f26 100644
--- a/rust/feature-flags/src/api/types.rs
+++ b/rust/feature-flags/src/api/types.rs
@@ -1,4 +1,6 @@
use crate::api::errors::FlagError;
+use crate::cohorts::cohort_models::{CohortId, CohortMembership};
+use crate::cohorts::cohort_operations::apply_cohort_membership_logic;
use crate::flags::evaluate_v2::EvaluationDetail;
use crate::flags::flag_group_type_mapping::GroupTypeIndex;
use crate::flags::flag_match_reason::FeatureFlagMatchReason;
@@ -629,6 +631,7 @@ pub struct FlagEvaluationReason {
pub trait FromFeatureAndMatch {
fn create(flag: &FeatureFlag, flag_match: &FeatureFlagMatch) -> Self;
+ #[allow(clippy::too_many_arguments)]
fn create_with_analysis(
flag: &FeatureFlag,
flag_match: &FeatureFlagMatch,
@@ -636,6 +639,7 @@ pub trait FromFeatureAndMatch {
property_values: Option<&HashMap<String, Value>>,
group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,
flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,
+ cohort_matches: Option<&HashMap<CohortId, CohortMembership>>,
matching_context: PropertyMatchingContext,
) -> Self;
fn create_error(flag: &FeatureFlag, error: &FlagError, condition_index: Option<i32>) -> Self;
@@ -652,6 +656,7 @@ impl FromFeatureAndMatch for FlagDetails {
None,
None,
None,
+ None,
PropertyMatchingContext::new(Tz::UTC, false),
)
}
@@ -663,6 +668,7 @@ impl FromFeatureAndMatch for FlagDetails {
property_values: Option<&HashMap<String, Value>>,
group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,
flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,
+ cohort_matches: Option<&HashMap<CohortId, CohortMembership>>,
matching_context: PropertyMatchingContext,
) -> Self {
FlagDetails {
@@ -693,6 +699,7 @@ impl FromFeatureAndMatch for FlagDetails {
property_values,
group_property_values,
flag_evaluation_results,
+ cohort_matches,
matching_context,
)
} else {
@@ -764,6 +771,7 @@ impl FlagDetails {
property_values: Option<&HashMap<String, Value>>,
group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,
flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,
+ cohort_matches: Option<&HashMap<CohortId, CohortMembership>>,
matching_context: PropertyMatchingContext,
) -> Vec<ConditionAnalysis> {
let mut analyses = Vec::new();
@@ -848,6 +856,65 @@ impl FlagDetails {
continue;
}
+ // match_property() cannot evaluate a cohort filter, so it reports every one
+ // as unmatched and contradicts the condition outcome. Resolve against
+ // membership through the same helper the matcher uses.
+ if property.is_cohort() {
+ let empty = HashMap::new();
+ let matches = cohort_matches.unwrap_or(&empty);
+ let cohort_id = property.get_cohort_id();
+ let cohort_label = match cohort_id {
+ Some(id) => format!("cohort {id}"),
+ None => "the targeted cohort".to_string(),
+ };
+ // A missing entry means membership was never resolved, not that the person
+ // is outside the cohort. `apply_cohort_membership_logic` reads it as a
+ // non-match, so a `not in` filter would claim a match the matcher never made.
+ let membership = cohort_id.and_then(|id| matches.get(&id).copied());
+ let (property_matched, explanation) = match membership {
+ Some(membership) => {
+ let memberships: HashMap<CohortId, bool> = matches
+ .iter()
+ .map(|(id, membership)| (*id, membership.is_member()))
+ .collect();
+ let matched = apply_cohort_membership_logic(
+ std::slice::from_ref(property),
+ &memberships,
+ )
+ .unwrap_or(false);
+ // State membership, not the verdict: the frontend renders this line
+ // with no pass or fail marker. `matched` still follows the boolean,
+ // because that is what the matcher applied the operator to.
+ let line = match membership {
+ CohortMembership::Member => {
+ format!("Person is in {cohort_label}")
+ }
+ CohortMembership::NonMember => {
+ format!("Person is not in {cohort_label}")
+ }
+ CohortMembership::UnverifiedNonMember => format!(
+ "Could not fully check if person is in {cohort_label}, because it targets behavior over time"
+ ),
+ };
+ (matched, line)
+ }
+ None => (
+ false,
+ format!("Could not check if person is in {cohort_label}"),
+ ),
+ };
+ property_analyses.push(PropertyAnalysis {
+ key: property.key.clone(),
+ operator: operator_str,
+ value: property.value.clone().unwrap_or(Value::Null),
+ r#type: type_str,
+ actual_value: None,
+ matched: property_matched,
+ explanation,
+ });
+ continue;
+ }
+
// Generate explanation placeholder - will be updated after we know if property matched
let explanation_placeholder = match property.operator {
Some(OperatorType::IsSet) => ("is set", "is not set"),
@@ -1633,6 +1700,7 @@ mod tests {
Some(&property_values),
None,
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -1737,6 +1805,7 @@ mod tests {
Some(&person_props),
Some(&group_props),
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -1819,6 +1888,7 @@ mod tests {
None,
Some(&group_props),
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -1883,6 +1953,7 @@ mod tests {
Some(&HashMap::new()),
None,
Some(&flag_results),
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -1917,6 +1988,7 @@ mod tests {
Some(&HashMap::new()),
None,
Some(&flag_results),
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -1952,6 +2024,7 @@ mod tests {
Some(&HashMap::new()),
None,
None, // empty — dependency flag 42 absent
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -1963,6 +2036,154 @@ mod tests {
assert_eq!(analysis[0].properties[0].actual_value, None);
}
+ fn cohort_flag(operator: &str) -> crate::flags::flag_models::FeatureFlag {
+ serde_json::from_value(json!(
+ {
+ "id": 1,
+ "team_id": 1,
+ "name": "cohort-flag",
+ "key": "cohort-flag",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": "id",
+ "value": 12345,
+ "type": "cohort",
+ "operator": operator
+ }
+ ],
+ "rollout_percentage": 100
+ }
+ ]
+ }
+ }
+ ))
+ .unwrap()
+ }
+
+ #[rstest]
+ #[case::is_in("in")]
+ #[case::is_not_in("not_in")]
+ fn test_condition_analysis_fails_cohort_filters_closed_when_membership_is_unresolved(
+ #[case] operator: &str,
+ ) {
+ use std::collections::HashMap;
+
+ // An evaluation at a past timestamp skips the DB preparation that loads cohorts, so the
+ // membership map arrives empty and the matcher fails the condition closed.
+ let flag = cohort_flag(operator);
+
+ let flag_match = FeatureFlagMatch {
+ matches: false,
+ variant: None,
+ reason: FeatureFlagMatchReason::NoConditionMatch,
+ condition_index: None,
+ payload: None,
+ evaluation_v2: None,
+ };
+
+ let analysis = FlagDetails::build_condition_analysis(
+ &flag,
+ &flag_match,
+ Some(&HashMap::new()),
+ None,
+ None,
+ None, // membership never resolved
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
+ );
+
+ assert_eq!(analysis.len(), 1);
+ assert!(
+ !analysis[0].properties[0].matched,
+ "Unresolved cohort membership must report matched=false for both operators"
+ );
+ assert!(
+ !analysis[0].properties_matched,
+ "Condition must agree with the matcher, which fails closed without cohorts"
+ );
+ assert_eq!(
+ analysis[0].properties[0].explanation, "Could not check if person is in cohort 12345",
+ "The line must not assert a membership that was never resolved"
+ );
+ assert_eq!(
+ analysis[0].explanation,
+ "Condition 1 did not match properties"
+ );
+ }
+
+ #[rstest]
+ #[case::in_member("in", CohortMembership::Member, true, "Person is in cohort 12345")]
+ #[case::in_non_member(
+ "in",
+ CohortMembership::NonMember,
+ false,
+ "Person is not in cohort 12345"
+ )]
+ #[case::not_in_member("not_in", CohortMembership::Member, false, "Person is in cohort 12345")]
+ #[case::not_in_non_member(
+ "not_in",
+ CohortMembership::NonMember,
+ true,
+ "Person is not in cohort 12345"
+ )]
+ // A behavioral or lifecycle cohort scores every leaf as a non-match, so the operator still
+ // applies but the line cannot claim the person is outside the cohort.
+ #[case::in_behavioral(
+ "in",
+ CohortMembership::UnverifiedNonMember,
+ false,
+ "Could not fully check if person is in cohort 12345, because it targets behavior over time"
+ )]
+ #[case::not_in_behavioral(
+ "not_in",
+ CohortMembership::UnverifiedNonMember,
+ true,
+ "Could not fully check if person is in cohort 12345, because it targets behavior over time"
+ )]
+ fn test_condition_analysis_applies_cohort_operator_to_known_membership(
+ #[case] operator: &str,
+ #[case] membership: CohortMembership,
+ #[case] expected_matched: bool,
+ #[case] expected_explanation: &str,
+ ) {
+ use std::collections::HashMap;
+
+ let flag = cohort_flag(operator);
+
+ let flag_match = FeatureFlagMatch {
+ matches: expected_matched,
+ variant: None,
+ reason: if expected_matched {
+ FeatureFlagMatchReason::ConditionMatch
+ } else {
+ FeatureFlagMatchReason::NoConditionMatch
+ },
+ condition_index: expected_matched.then_some(0),
+ payload: None,
+ evaluation_v2: None,
+ };
+
+ let analysis = FlagDetails::build_condition_analysis(
+ &flag,
+ &flag_match,
+ Some(&HashMap::new()),
+ None,
+ None,
+ Some(&HashMap::from([(12345, membership)])),
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
+ );
+
+ assert_eq!(analysis.len(), 1);
+ assert_eq!(
+ analysis[0].properties[0].matched, expected_matched,
+ "the operator must be applied to the resolved membership"
+ );
+ assert_eq!(analysis[0].properties[0].explanation, expected_explanation);
+ }
+
#[rstest]
#[case::opted_in(Some("true"), SuperConditionValue, true, true, true, "Enrolled", false)]
#[case::opted_out(
@@ -2022,6 +2243,7 @@ mod tests {
Some(&property_values),
None,
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -2098,6 +2320,7 @@ mod tests {
Some(&property_values),
None,
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -2142,6 +2365,7 @@ mod tests {
Some(&property_values),
None,
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -2189,6 +2413,7 @@ mod tests {
Some(&property_values),
None,
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
@@ -2247,6 +2472,7 @@ mod tests {
Some(&property_values),
None,
None,
+ None,
PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
diff --git a/rust/feature-flags/src/cohorts/cohort_models.rs b/rust/feature-flags/src/cohorts/cohort_models.rs
index 67751359fa95..7c460d1c4dd3 100644
--- a/rust/feature-flags/src/cohorts/cohort_models.rs
+++ b/rust/feature-flags/src/cohorts/cohort_models.rs
@@ -168,6 +168,27 @@ impl StampPolicyDivergence {
}
}
+/// A cohort membership resolved for condition analysis, and whether it can be stated as fact.
+///
+/// The dynamic path scores a behavioral or lifecycle leaf as a non-match whatever the cohort's
+/// member list holds, so the matcher refuses to trust a non-match on such a cohort. Condition
+/// analysis keeps the same distinction, so its explanation never asserts a membership that
+/// nothing resolved.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum CohortMembership {
+ Member,
+ NonMember,
+ /// Resolved as a non-member, on a cohort whose behavioral or lifecycle leaf the dynamic path
+ /// cannot evaluate.
+ UnverifiedNonMember,
+}
+
+impl CohortMembership {
+ pub fn is_member(self) -> bool {
+ matches!(self, Self::Member)
+ }
+}
+
impl Cohort {
/// Returns true if `condition_type` flags a `behavioral` or `lifecycle` leaf condition.
/// Missing or malformed `condition_type` (e.g. a hypercache entry written before this
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index e035c5eac6da..039fe25191e4 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -1,7 +1,7 @@
use crate::api::errors::FlagError;
use crate::api::types::{FlagDetails, FlagValue, FlagsResponse, FromFeatureAndMatch};
use crate::cohorts::cohort_cache_manager::CohortCacheManager;
-use crate::cohorts::cohort_models::{Cohort, CohortId, MembershipStampPolicy};
+use crate::cohorts::cohort_models::{Cohort, CohortId, CohortMembership, MembershipStampPolicy};
use crate::cohorts::cohort_operations::{
apply_cohort_membership_logic, evaluate_dynamic_cohorts, record_stamp_policy_divergence,
};
@@ -833,35 +833,142 @@ impl FeatureFlagMatcher {
// Track cohort evaluations in canonical log
with_canonical_log(|log| log.eval.cohorts_evaluated += cohort_property_filters.len());
+ let (cohort_matches, errors) =
+ self.resolve_cohort_matches(cohort_property_filters, target_properties, &cohorts);
+
+ if let Some(error) = errors.into_iter().next() {
+ return Err(error);
+ }
+
+ // Apply cohort membership logic (IN|NOT_IN) to the cohort match results
+ apply_cohort_membership_logic(cohort_property_filters, &cohort_matches)
+ }
+
+ /// Resolves every cohort the given filters reference to a membership boolean, starting from
+ /// the memberships cached during `prepare_flag_evaluation_state` (static and realtime).
+ fn resolve_cohort_matches(
+ &self,
+ cohort_property_filters: &[&PropertyFilter],
+ target_properties: &HashMap<String, Value>,
+ cohorts: &[Cohort],
+ ) -> (HashMap<CohortId, bool>, Vec<FlagError>) {
// Get cached cohort results (static + realtime, merged during prepare_flag_evaluation_state)
let cached_matches = match self.flag_evaluation_state.get_cohort_matches() {
Some(matches) => matches.clone(),
None => HashMap::new(), // Happens when targeting an anonymous user with no person record
};
+ Self::resolve_cohort_matches_from_cache(
+ cohort_property_filters,
+ target_properties,
+ cohorts,
+ cached_matches,
+ PropertyMatchingContext::new(self.timezone, self.use_explicit_exact_matching),
+ )
+ }
+
+ /// Evaluates any dynamic cohort the filters reference that the cache does not already cover.
+ ///
+ /// Resolution continues past a cohort that fails, and the failures come back alongside the
+ /// memberships that did resolve. A caller that must agree with the whole filter set fails on
+ /// the first error; condition analysis keeps what resolved, because a cohort left out of the
+ /// map reads as unknown rather than as a non-match. Both paths share this loop so a change to
+ /// cohort resolution cannot reach one and miss the other.
+ fn resolve_cohort_matches_from_cache(
+ cohort_property_filters: &[&PropertyFilter],
+ target_properties: &HashMap<String, Value>,
+ cohorts: &[Cohort],
+ cached_matches: HashMap<CohortId, bool>,
+ matching_context: PropertyMatchingContext,
+ ) -> (HashMap<CohortId, bool>, Vec<FlagError>) {
let mut cohort_matches = cached_matches;
+ let mut errors = Vec::new();
// For any cohorts not yet evaluated (i.e., dynamic ones), evaluate them
for filter in cohort_property_filters {
- let cohort_id = filter
- .get_cohort_id()
- .ok_or(FlagError::CohortFiltersParsingError)?;
+ let Some(cohort_id) = filter.get_cohort_id() else {
+ errors.push(FlagError::CohortFiltersParsingError);
+ continue;
+ };
if !cohort_matches.contains_key(&cohort_id) {
let current_matches = cohort_matches.clone();
- let match_result = evaluate_dynamic_cohorts(
+ match evaluate_dynamic_cohorts(
cohort_id,
target_properties,
- &cohorts,
+ cohorts,
&current_matches,
- PropertyMatchingContext::new(self.timezone, self.use_explicit_exact_matching),
- )?;
- cohort_matches.insert(cohort_id, match_result);
+ matching_context,
+ ) {
+ Ok(match_result) => {
+ cohort_matches.insert(cohort_id, match_result);
+ }
+ Err(error) => errors.push(error),
+ }
}
}
- // Apply cohort membership logic (IN|NOT_IN) to the cohort match results
- apply_cohort_membership_logic(cohort_property_filters, &cohort_matches)
+ (cohort_matches, errors)
+ }
+
+ /// Resolves cohort memberships for every cohort filter on the flag, for detailed condition
+ /// analysis.
+ ///
+ /// The evaluation state caches static and realtime memberships only, because
+ /// `evaluate_cohort_filters` discards the dynamic ones it resolves. Reading that cache alone
+ /// would report every dynamic cohort as a non-match.
+ fn cohort_matches_for_analysis(
+ &self,
+ flag: &FeatureFlag,
+ person_properties: Option<&HashMap<String, Value>>,
+ ) -> HashMap<CohortId, CohortMembership> {
+ let cohort_filters: Vec<&PropertyFilter> = flag
+ .filters
+ .groups
+ .iter()
+ .filter_map(|group| group.properties.as_ref())
+ .flatten()
+ .filter(|filter| filter.is_cohort())
+ .collect();
+
+ if cohort_filters.is_empty() {
+ return HashMap::new();
+ }
+
+ let Some(cohorts) = self.flag_evaluation_state.cohorts.clone() else {
+ return HashMap::new();
+ };
+
+ let target_properties = person_properties.unwrap_or(&EMPTY_PROPERTY_MAP);
+
+ // A condition can name a cohort the flags payload no longer carries, because Django omits
+ // deleted and cross-team cohorts but keeps the filters that name them. Those failures stay
+ // out of the map, so the analysis reports them as unknown instead of as a non-match.
+ let (cohort_matches, errors) =
+ self.resolve_cohort_matches(&cohort_filters, target_properties, &cohorts);
+
+ for error in errors {
+ warn!("Cohort left unresolved for condition analysis: {error:?}");
+ }
+
+ // A non-match on a behavioral or lifecycle cohort is the dynamic path's default, not a
+ // checked answer, which is why the matcher reports it as `cohort_not_evaluated`.
+ cohort_matches
+ .into_iter()
+ .map(|(cohort_id, is_member)| {
+ let membership = if is_member {
+ CohortMembership::Member
+ } else if cohorts
+ .iter()
+ .any(|cohort| cohort.id == cohort_id && cohort.has_behavioral_condition())
+ {
+ CohortMembership::UnverifiedNonMember
+ } else {
+ CohortMembership::NonMember
+ };
+ (cohort_id, membership)
+ })
+ .collect()
}
/// Evaluates feature flags with property and hash key overrides.
@@ -1179,6 +1286,8 @@ impl FeatureFlagMatcher {
// filters resolve against the group rather than the person.
let merged_group_props =
self.merged_group_properties_for_flag(flag, group_property_overrides);
+ let cohort_matches =
+ self.cohort_matches_for_analysis(flag, merged_person_props.as_ref());
FlagDetails::create_with_analysis(
flag,
flag_match,
@@ -1186,6 +1295,7 @@ impl FeatureFlagMatcher {
merged_person_props.as_ref(),
Some(&merged_group_props),
Some(&self.flag_evaluation_state.flag_evaluation_results),
+ Some(&cohort_matches),
PropertyMatchingContext::new(
self.timezone,
self.use_explicit_exact_matching,
@@ -3021,4 +3131,79 @@ mod tests {
}
assert_eq!(result.len(), 1 + expected_extras.len());
}
+
+ #[test]
+ fn test_cohort_analysis_keeps_resolved_memberships_when_another_cohort_fails() {
+ // A flag can name a cohort the flags payload no longer carries, because Django omits
+ // deleted and cross-team cohorts but keeps the filters that name them. Resolving the set as
+ // a unit drops the memberships that did resolve along with it.
+ let cohort: Cohort = serde_json::from_value(serde_json::json!({
+ "id": 1,
+ "team_id": 1,
+ "deleted": false,
+ "is_calculating": false,
+ "is_static": false,
+ "errors_calculating": 0,
+ "groups": [],
+ "filters": {
+ "properties": {
+ "type": "OR",
+ "values": [{
+ "type": "OR",
+ "values": [{
+ "key": "plan",
+ "type": "person",
+ "value": "enterprise",
+ "operator": "exact"
+ }]
+ }]
+ }
+ }
+ }))
+ .unwrap();
+
+ // Cohort 999 comes first, so a resolver that stopped on the first failure would lose
+ // cohort 1 instead of reporting it.
+ let filters: Vec<PropertyFilter> = [999, 1]
+ .into_iter()
+ .map(|id| {
+ serde_json::from_value(serde_json::json!({
+ "key": "id",
+ "value": id,
+ "type": "cohort",
+ "operator": "in"
+ }))
+ .unwrap()
+ })
+ .collect();
+ let filter_refs: Vec<&PropertyFilter> = filters.iter().collect();
+
+ let target_properties =
+ HashMap::from([("plan".to_string(), Value::String("enterprise".to_string()))]);
+
+ // Cohort 999 is absent from the loaded list, so resolving it fails.
+ let (resolved, errors) = FeatureFlagMatcher::resolve_cohort_matches_from_cache(
+ &filter_refs,
+ &target_properties,
+ &[cohort],
+ HashMap::new(),
+ PropertyMatchingContext::new(Tz::UTC, false),
+ );
+
+ assert_eq!(
+ errors.len(),
+ 1,
+ "the failing cohort must be reported, so the strict path can still fail on it"
+ );
+ assert_eq!(
+ resolved.get(&1),
+ Some(&true),
+ "a resolved membership must survive another cohort failing"
+ );
+ assert_eq!(
+ resolved.get(&999),
+ None,
+ "an unresolvable cohort must be absent, so analysis reads it as unknown"
+ );
+ }
}
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index 7d2c5973fbda..40c76838ccd8 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -618,6 +618,146 @@ mod tests {
assert_eq!(industry_analysis.actual_value, Some(json!("tech")));
}
+ /// `match_property` cannot evaluate a cohort filter, so a winning condition used to claim its
+ /// own properties did not match. The cohort is dynamic on purpose, because the evaluation state
+ /// caches static and realtime memberships only.
+ #[tokio::test]
+ async fn test_detailed_analysis_resolves_cohort_filters_against_cohort_membership() {
+ 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 cohort_row = context
+ .insert_cohort(
+ team.id,
+ None,
+ json!({
+ "properties": {
+ "type": "OR",
+ "values": [{
+ "type": "OR",
+ "values": [{
+ "key": "plan",
+ "type": "person",
+ "value": "enterprise",
+ "negation": false,
+ "operator": "exact"
+ }]
+ }]
+ }
+ }),
+ false,
+ )
+ .await
+ .unwrap();
+
+ context
+ .insert_person(
+ team.id,
+ "cohort_member".to_string(),
+ Some(json!({"plan": "enterprise"})),
+ )
+ .await
+ .unwrap();
+ context
+ .insert_person(
+ team.id,
+ "non_member".to_string(),
+ Some(json!({"plan": "free"})),
+ )
+ .await
+ .unwrap();
+
+ let flag = mock!(FeatureFlag,
+ team_id: team.id,
+ filters: FlagFilters {
+ groups: vec![FlagPropertyGroup {
+ properties: Some(vec![PropertyFilter {
+ key: "id".to_string(),
+ value: Some(json!(cohort_row.id)),
+ operator: Some(OperatorType::In),
+ prop_type: PropertyType::Cohort,
+ group_type_index: None,
+ negation: Some(false),
+ compiled_regex: None,
+ extra: Default::default(),
+ }]),
+ rollout_percentage: Some(100.0),
+ variant: None,
+ ..Default::default()
+ }],
+ multivariate: None,
+ aggregation_group_type_index: None,
+ payloads: None,
+ feature_enrollment: None,
+ holdout: None,
+ early_exit: None,
+ non_v1: None,
+ extra: Default::default(),
+ }
+ );
+
+ for (distinct_id, is_member) in [("cohort_member", true), ("non_member", false)] {
+ let mut matcher = FeatureFlagMatcher::new(
+ distinct_id.to_string(),
+ None, // device_id
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache.clone(),
+ empty_group_type_cache(),
+ None,
+ )
+ .with_detailed_analysis(true);
+
+ let flags = flag_list_with_metadata(vec![flag.clone()]);
+ let result = matcher
+ .evaluate_all_feature_flags(flags, None, None, 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(is_member));
+
+ let conditions = flag_details
+ .conditions
+ .as_ref()
+ .expect("detailed_analysis(true) should populate conditions");
+ assert_eq!(conditions.len(), 1);
+
+ assert_eq!(conditions[0].matched, is_member, "user {distinct_id}");
+ assert_eq!(
+ conditions[0].properties_matched, is_member,
+ "user {distinct_id}"
+ );
+
+ // A member's condition explanation must agree with the MATCHED badge.
+ let expected_condition = if is_member {
+ "Condition 1 matched and passed 100% rollout"
+ } else {
+ "Condition 1 did not match properties"
+ };
+ assert_eq!(
+ conditions[0].explanation, expected_condition,
+ "user {distinct_id}"
+ );
+
+ let properties = &conditions[0].properties;
+ assert_eq!(properties.len(), 1);
+ assert_eq!(properties[0].matched, is_member, "user {distinct_id}");
+ let expected = if is_member {
+ format!("Person is in cohort {}", cohort_row.id)
+ } else {
+ format!("Person is not in cohort {}", cohort_row.id)
+ };
+ assert_eq!(properties[0].explanation, expected, "user {distinct_id}");
+ }
+ }
+
/// 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,
@@ -3771,6 +3911,102 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn test_detailed_analysis_resolves_static_cohort_filters_against_cohort_membership() {
+ // A static member's membership reaches condition analysis only through the cache that
+ // `prepare_flag_evaluation_state` seeds, because the dynamic path scores every static
+ // cohort as a non-match. Without that seed the condition shows MATCHED above a line
+ // saying the person is not in the cohort.
+ 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 cohort = context
+ .insert_cohort(team.id, Some("Static Cohort".to_string()), json!({}), true)
+ .await
+ .unwrap();
+
+ let distinct_id = "static_analysis_user".to_string();
+ context
+ .insert_person(team.id, distinct_id.clone(), Some(json!({})))
+ .await
+ .unwrap();
+ let person_id = context
+ .get_person_id_by_distinct_id(team.id, &distinct_id)
+ .await
+ .unwrap();
+ context
+ .add_person_to_cohort(cohort.id, person_id)
+ .await
+ .unwrap();
+
+ let flag = mock!(FeatureFlag,
+ team_id: team.id,
+ filters: FlagFilters {
+ non_v1: None,
+ groups: vec![FlagPropertyGroup {
+ properties: Some(vec![PropertyFilter {
+ key: "id".to_string(),
+ value: Some(json!(cohort.id)),
+ operator: Some(OperatorType::In),
+ prop_type: PropertyType::Cohort,
+ group_type_index: None,
+ negation: Some(false),
+ compiled_regex: None,
+ extra: Default::default(),
+ }]),
+ rollout_percentage: Some(100.0),
+ variant: None,
+ ..Default::default()
+ }],
+ multivariate: None,
+ aggregation_group_type_index: None,
+ payloads: None,
+ feature_enrollment: None,
+ holdout: None,
+ early_exit: None,
+ extra: Default::default(),
+ }
+ );
+
+ let mut matcher = FeatureFlagMatcher::new(
+ distinct_id,
+ None, // device_id
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache.clone(),
+ empty_group_type_cache(),
+ None,
+ )
+ .with_detailed_analysis(true);
+
+ let flags = flag_list_with_metadata(vec![flag.clone()]);
+ let result = matcher
+ .evaluate_all_feature_flags(flags, None, None, 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);
+ assert!(conditions[0].matched);
+ assert_eq!(
+ conditions[0].properties[0].explanation,
+ format!("Person is in cohort {}", cohort.id)
+ );
+ assert!(conditions[0].properties[0].matched);
+ }
+
fn flag_with_group(
team_id: TeamId,
group: FlagPropertyGroup,