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): fail closed when group properties were never fetched (#90970)

Gustavo H. Strassburger53642f268c08
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.md
index 39f9b77fead2..9f067ada3e99 100644
--- a/docs/internal/feature-flags/flag-evaluation-engine.md
+++ b/docs/internal/feature-flags/flag-evaluation-engine.md
@@ -448,10 +448,11 @@ The `FlagEvaluationState` struct caches all data needed for a single request, av
```rust
pub struct FlagEvaluationState {
person_id: Option<PersonId>,
- person_properties: Option<HashMap<String, Value>>,
+ person_uuid: Option<Uuid>,
+ person_property_state: PersonPropertyState,
group_properties: HashMap<GroupTypeIndex, HashMap<String, Value>>,
- cohorts: Option<Vec<Cohort>>,
- static_cohort_matches: Option<HashMap<CohortId, bool>>,
+ cohorts: Option<Arc<[Cohort]>>,
+ cohort_matches: Option<HashMap<CohortId, bool>>,
flag_evaluation_results: HashMap<FeatureFlagId, FlagValue>,
}
```
@@ -460,14 +461,28 @@ Property overrides from the request body are merged on top of DB-fetched propert
GeoIP-derived `$geoip_*` properties follow the same rule. They are added to the request overrides before evaluation, but only fill keys the request didn't supply.
See [GeoIP enrichment of `person_properties`](rust-service-overview.md#geoip-enrichment-of-person_properties).
+### Unfetched properties fail closed
+
+A property map that was never fetched is not the same as a property map that came back empty. An empty map means the property is unset, which makes a negative operator such as `is_not` match. A map that was never fetched says nothing, so treating it as empty grants the flag to exactly the people or groups the condition excludes.
+
+Both property sources record whether their fetch ran, and a filter whose source never ran evaluates to no match whichever way the filter points:
+
+- `person_property_state` distinguishes `Pending` (prep has not run) from `Skipped` (request overrides cover every key the batch needs) and `Fetched`.
+- The key set of `group_properties` carries the same distinction per group type. A missing index means the fetch never ran; a present index is authoritative, so an empty map there means the group has no stored properties.
+- `group_type_mapping` records `Uninitialized`, `Loaded`, or `Failed`. A group filter fails closed unless the mapping resolves its group type index: a failed lookup says nothing about any group, and a loaded mapping that lacks the index — a cache entry from before the group type was added — says nothing about that one.
+
+One case deliberately keeps the old behavior: a group type the request supplies no key for. It applies only after the mapping resolves the filter's index to a group type name and the request omits that name. The request never claimed to be in a group of that type, so there is no group context to fail closed on, and filters on it match as before.
+
+Self-hosted upgrades across this change can see different `/flags` and `/decide` responses without any change to the request or the flag. A negative group filter that previously matched because of a fetch miss now stops matching. A condition that combines person and group filters now loads the group types referenced only by those filters, so the group's stored properties decide the filter where an empty map used to.
+
## Data fetching strategy
The evaluation engine follows a lazy-but-batched approach:
1. **Flag definitions**: Fetched once per request from HyperCache (Redis -> S3 -> PostgreSQL), including pre-computed `evaluation_metadata` when available
-2. **Group type mappings**: Fetched once per request if any flag uses groups
+2. **Group type mappings**: Fetched once per request if any flag references a group type, through flag-level or condition-level aggregation or through an individual group property filter. The outcome is reused for the rest of the request, so a failed lookup is not retried
3. **Person properties**: Fetched once per request from PostgreSQL, merged with request overrides
-4. **Group properties**: Fetched once per request from PostgreSQL, merged with request overrides
+4. **Group properties**: Fetched once per request from PostgreSQL, merged with request overrides. A group filter keeps its flag in this preparation only when the fetch can serve it — the mapping resolves the filter's index, the request carries a usable key for that group type, and no request override already supplies the filtered property — so a flag whose only database need is an unservable group filter skips the person and group queries entirely
5. **Cohort definitions**: Fetched from moka cache (backed by PostgreSQL)
6. **Static cohort memberships**: Fetched once per request via batched query
7. **Hash key overrides**: Fetched once per request if any flag uses experience continuity
diff --git a/rust/feature-flags/src/flags/flag_filters.rs b/rust/feature-flags/src/flags/flag_filters.rs
index f4ed1a042e88..5553e0ea3259 100644
--- a/rust/feature-flags/src/flags/flag_filters.rs
+++ b/rust/feature-flags/src/flags/flag_filters.rs
@@ -2,7 +2,9 @@ use std::collections::HashMap;
use serde_json::Value;
+use crate::flags::flag_group_type_mapping::GroupTypeIndex;
use crate::flags::flag_models::FlagFilters;
+use crate::properties::property_models::PropertyFilter;
impl FlagFilters {
/// Returns the person property key used for early access feature enrollment.
@@ -20,6 +22,7 @@ impl FlagFilters {
&self,
overrides: &HashMap<String, Value>,
flag_key: &str,
+ group_filter_needs_db: &dyn Fn(&PropertyFilter, Option<GroupTypeIndex>) -> bool,
) -> bool {
self.aggregation_group_type_index.is_some()
|| (self.feature_enrollment == Some(true) && {
@@ -29,10 +32,15 @@ impl FlagFilters {
.groups
.iter()
.any(|group| matches!(group.aggregation_group_type_index, Some(Some(_))))
- || self
- .groups
- .iter()
- .any(|group| group.requires_db_properties(overrides))
+ || self.groups.iter().any(|group| {
+ // Group filters resolve their index against the condition's aggregation,
+ // so the caller-supplied decision gets the same aggregation matching uses.
+ let effective_aggregation =
+ group.effective_aggregation(self.aggregation_group_type_index);
+ group.requires_db_properties(overrides, &|prop| {
+ group_filter_needs_db(prop, effective_aggregation)
+ })
+ })
}
pub fn requires_cohort_filters(&self) -> bool {
@@ -100,7 +108,7 @@ mod tests {
),
]);
- assert!(f.requires_db_properties(&overrides, "test-flag"));
+ assert!(f.requires_db_properties(&overrides, "test-flag", &|_, _| true));
}
{
@@ -117,7 +125,7 @@ mod tests {
),
]);
- assert!(!f.requires_db_properties(&overrides, "test-flag"));
+ assert!(!f.requires_db_properties(&overrides, "test-flag", &|_, _| true));
}
}
@@ -150,7 +158,7 @@ mod tests {
// Even though there are no properties, we still need to evaluate the DB properties
// because the group type index is set.
- assert!(f.requires_db_properties(&HashMap::new(), "test-flag"));
+ assert!(f.requires_db_properties(&HashMap::new(), "test-flag", &|_, _| true));
}
#[test]
@@ -158,7 +166,7 @@ mod tests {
let mut f = mock!(FlagFilters, groups: vec![]);
f.feature_enrollment = Some(true);
- assert!(f.requires_db_properties(&HashMap::new(), "my-flag"));
+ assert!(f.requires_db_properties(&HashMap::new(), "my-flag", &|_, _| true));
}
#[test]
@@ -170,7 +178,7 @@ mod tests {
FlagFilters::enrollment_key("my-flag"),
Value::String("true".to_string()),
)]);
- assert!(!f.requires_db_properties(&overrides, "my-flag"));
+ assert!(!f.requires_db_properties(&overrides, "my-flag", &|_, _| true));
}
#[test]
@@ -180,7 +188,7 @@ mod tests {
f.holdout = Some(mock!(Holdout));
// Holdouts don't require DB properties.
- assert!(!f.requires_db_properties(&HashMap::new(), "test-flag"));
+ assert!(!f.requires_db_properties(&HashMap::new(), "test-flag", &|_, _| true));
}
#[test]
@@ -197,7 +205,7 @@ mod tests {
{
let overrides =
HashMap::from([("some_key".to_string(), Value::String("value".to_string()))]);
- assert!(f.requires_db_properties(&overrides, "test-flag"));
+ assert!(f.requires_db_properties(&overrides, "test-flag", &|_, _| true));
}
{
@@ -212,7 +220,7 @@ mod tests {
Value::String("value".to_string()),
),
]);
- assert!(!f.requires_db_properties(&overrides, "test-flag"));
+ assert!(!f.requires_db_properties(&overrides, "test-flag", &|_, _| true));
}
}
@@ -242,7 +250,7 @@ mod tests {
),
]);
- assert!(f.requires_db_properties(&overrides, "test-flag"));
+ assert!(f.requires_db_properties(&overrides, "test-flag", &|_, _| true));
}
{
@@ -259,7 +267,7 @@ mod tests {
),
]);
- assert!(!f.requires_db_properties(&overrides, "test-flag"));
+ assert!(!f.requires_db_properties(&overrides, "test-flag", &|_, _| true));
}
}
}
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index 1d6535d2f5ae..1a2e41c9388f 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -144,6 +144,32 @@ pub(crate) enum PersonPropertyState {
Fetched(HashMap<String, Value>),
}
+/// Outcome of the group type mapping lookup for a request.
+///
+/// The mapping resolves a group type index to the name the request keys its `groups` by, so
+/// without it there is no way to tell "the caller sent no group of this type" from "the lookup
+/// failed". Keeping the failure in the same value as the mapping stops those two from being
+/// answered independently — see `FeatureFlagMatcher::filter_needs_partial_props`.
+#[derive(Clone, Debug, Default)]
+enum GroupTypeMappingState {
+ /// The lookup has not run for this request (initial state)
+ #[default]
+ Uninitialized,
+ /// The lookup ran and returned a mapping, which may be empty for a team with no group types
+ Loaded(GroupTypeMapping),
+ /// The lookup ran and failed
+ Failed,
+}
+
+impl GroupTypeMappingState {
+ fn mapping(&self) -> Option<&GroupTypeMapping> {
+ match self {
+ Self::Loaded(mapping) => Some(mapping),
+ _ => None,
+ }
+ }
+}
+
/// This struct maintains evaluation state by caching database-sourced data during feature flag evaluation.
/// It stores person IDs, properties, group properties, and cohort matches that are fetched from the database,
/// allowing them to be reused across multiple flag evaluations within the same request without additional DB lookups.
@@ -157,7 +183,12 @@ pub struct FlagEvaluationState {
person_uuid: Option<Uuid>,
/// Person property fetch state: pending, skipped, or fetched (with property data)
person_property_state: PersonPropertyState,
- /// Properties for each group type involved in flag evaluation
+ /// Properties for each group type whose properties DB prep ran for this evaluation.
+ ///
+ /// The key set carries the group-level analogue of `PersonPropertyState`: a missing index
+ /// means the fetch never ran, so nothing about that group type's properties is known. A
+ /// present index means the fetch ran and its map is authoritative, so an empty map means
+ /// the group genuinely has no properties (no `posthog_group` row).
group_properties: HashMap<GroupTypeIndex, HashMap<String, Value>>,
/// Cohorts for the current request, shared via `Arc` either from the
/// preloaded hypercache slice or wrapped from a `CohortCacheManager`
@@ -230,6 +261,20 @@ impl FlagEvaluationState {
self.group_properties.insert(group_type_index, properties);
}
+ /// Record that group-property DB prep ran for this group type, without disturbing
+ /// properties already stored for it. Must be called for every requested index once the
+ /// fetch succeeds, including indexes the query returned no row for — an empty map there
+ /// is an authoritative "this group has no properties", not a missing fetch.
+ pub fn mark_group_properties_fetched(&mut self, group_type_index: GroupTypeIndex) {
+ self.group_properties.entry(group_type_index).or_default();
+ }
+
+ /// True when group-property DB prep never ran for this group type, so an absent
+ /// key in the resolved property map carries no information — see `group_properties`.
+ pub(crate) fn group_properties_pending(&self, group_type_index: GroupTypeIndex) -> bool {
+ !self.group_properties.contains_key(&group_type_index)
+ }
+
pub fn set_cohort_matches(&mut self, matches: HashMap<CohortId, bool>) {
self.cohort_matches = Some(matches);
}
@@ -274,11 +319,10 @@ impl PropertyContext<'_> {
PropertyType::Person | PropertyType::PersonMetadata => {
self.person_properties.unwrap_or(&*EMPTY_PROPERTY_MAP)
}
- PropertyType::Group => {
- let gti = filter.group_type_index.or(self.aggregation);
- gti.and_then(|idx| self.group_properties.get(&idx))
- .unwrap_or(&*EMPTY_PROPERTY_MAP)
- }
+ PropertyType::Group => filter
+ .group_filter_index(self.aggregation)
+ .and_then(|idx| self.group_properties.get(&idx))
+ .unwrap_or(&*EMPTY_PROPERTY_MAP),
PropertyType::Cohort | PropertyType::Flag => match self.aggregation {
Some(gti) => self
.group_properties
@@ -314,8 +358,9 @@ pub struct FeatureFlagMatcher {
pub cohort_cache: Arc<CohortCacheManager>,
/// Shared in-process cache for group type mappings
group_type_cache: Arc<GroupTypeCacheManager>,
- /// Lazily populated mapping for the current team (fetched via group_type_cache)
- group_type_mapping: Option<GroupTypeMapping>,
+ /// Outcome of the group type mapping lookup for the current team, fetched once per
+ /// request via `group_type_cache`.
+ group_type_mapping: GroupTypeMappingState,
/// State maintained during flag evaluation, including cached DB lookups
pub(crate) flag_evaluation_state: FlagEvaluationState,
/// Group key mappings for group-based flag evaluation
@@ -413,7 +458,7 @@ impl FeatureFlagMatcher {
router,
cohort_cache,
group_type_cache,
- group_type_mapping: None,
+ group_type_mapping: GroupTypeMappingState::default(),
groups: groups.unwrap_or_default(),
flag_evaluation_state: FlagEvaluationState::default(),
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
@@ -839,6 +884,7 @@ impl FeatureFlagMatcher {
.prepare_evaluation_state_if_needed(
&flags,
&overrides.person_property_overrides,
+ &overrides.group_property_overrides,
&mut evaluated_flags_map,
)
.await;
@@ -883,6 +929,7 @@ impl FeatureFlagMatcher {
&mut self,
flags: &[&FeatureFlag],
person_property_overrides: &Option<HashMap<String, Value>>,
+ group_property_overrides: &Option<HashMap<String, HashMap<String, Value>>>,
evaluated_flags_map: &mut HashMap<String, FlagDetails>,
) -> bool {
let flags_requiring_db_preparation = flags_require_db_preparation(
@@ -891,6 +938,13 @@ impl FeatureFlagMatcher {
.as_ref()
.unwrap_or(&HashMap::new()),
&self.filtered_out_flag_ids,
+ &|filter, effective_aggregation| {
+ self.group_filter_needs_db_prep(
+ filter,
+ effective_aggregation,
+ group_property_overrides.as_ref(),
+ )
+ },
);
if flags_requiring_db_preparation.is_empty() || self.only_use_override_person_properties {
@@ -1133,7 +1187,7 @@ impl FeatureFlagMatcher {
group_type_index: GroupTypeIndex,
group_property_overrides: Option<&'a HashMap<String, HashMap<String, Value>>>,
) -> Option<&'a HashMap<String, Value>> {
- let mapping = self.group_type_mapping.as_ref()?;
+ let mapping = self.group_type_mapping.mapping()?;
let index_to_type_map = mapping.group_indexes_to_types();
let group_type = index_to_type_map.get(&group_type_index)?;
let group_overrides = group_property_overrides?;
@@ -1158,10 +1212,8 @@ impl FeatureFlagMatcher {
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);
- }
+ if let Some(gti) = property.group_filter_index(condition_aggregation) {
+ referenced_indexes.insert(gti);
}
}
}
@@ -1455,17 +1507,7 @@ impl FeatureFlagMatcher {
// This checks the group key directly rather than calling hashed_identifier,
// which will be called again later in check_rollout/get_matching_variant.
if let Some(group_type_index) = aggregation {
- let has_group_key = self
- .group_type_mapping
- .as_ref()
- .and_then(|m| m.group_indexes_to_types().get(&group_type_index))
- .and_then(|name| self.groups.get(name))
- .is_some_and(|v| match v {
- Value::String(s) => !s.is_empty(),
- Value::Number(_) => true,
- _ => false,
- });
- if !has_group_key {
+ if !self.has_group_key(group_type_index) {
inc(
FLAG_CONDITION_SKIPPED_COUNTER,
&[("reason".to_string(), "missing_group_type".to_string())],
@@ -1708,9 +1750,9 @@ impl FeatureFlagMatcher {
// flags out before evaluation, so the guard protects any path that reaches
// evaluation with the state still Pending. Cohort filters get the same
// treatment below, refusing to evaluate outright since cohort membership
- // is unknowable under Pending.
- let partial_props = filter.prop_type != PropertyType::Group
- && self.flag_evaluation_state.person_properties_pending();
+ // is unknowable under Pending. Group filters get the equivalent guard
+ // keyed on their own group type — see `filter_needs_partial_props`.
+ let partial_props = self.filter_needs_partial_props(filter, property_context);
if !match_property(
filter,
props,
@@ -1789,6 +1831,110 @@ impl FeatureFlagMatcher {
)
}
+ /// Seeds the mapping that `initialize_group_type_mappings_if_needed` loads in production,
+ /// for tests that exercise matching without running DB prep.
+ #[cfg(test)]
+ pub(crate) fn set_group_type_mapping_for_test(&mut self, mapping: GroupTypeMapping) {
+ self.group_type_mapping = GroupTypeMappingState::Loaded(mapping);
+ }
+
+ /// Whether the request supplied a usable group key for this group type name. Without one
+ /// there is no group to load properties for, so group filters on that type have no
+ /// context at all — distinct from having a key whose properties weren't fetched.
+ fn has_usable_group_key(&self, group_type: &str) -> bool {
+ self.groups.get(group_type).is_some_and(|v| match v {
+ Value::String(s) => !s.is_empty(),
+ Value::Number(_) => true,
+ _ => false,
+ })
+ }
+
+ /// `has_usable_group_key` by group type index. False both when the request omitted the
+ /// group and when the mapping can't resolve the index, so callers that must tell those
+ /// apart resolve the name themselves — see `filter_needs_partial_props`.
+ fn has_group_key(&self, group_type_index: GroupTypeIndex) -> bool {
+ self.group_type_mapping
+ .mapping()
+ .and_then(|m| m.group_indexes_to_types().get(&group_type_index))
+ .is_some_and(|group_type| self.has_usable_group_key(group_type))
+ }
+
+ /// Whether DB preparation would load anything this group filter can use. Selecting a
+ /// filter pulls its whole flag into preparation, and with it the person-property query,
+ /// so a filter only counts when the fetch can serve it: the mapping resolves its index,
+ /// the request carries a usable key for that group type, and no group property override
+ /// already supplies the filtered key. In every other state the fetch would load nothing
+ /// for the filter, and matching handles those states itself — see
+ /// `filter_needs_partial_props`.
+ fn group_filter_needs_db_prep(
+ &self,
+ filter: &PropertyFilter,
+ effective_aggregation: Option<GroupTypeIndex>,
+ group_property_overrides: Option<&HashMap<String, HashMap<String, Value>>>,
+ ) -> bool {
+ let Some(gti) = filter.group_filter_index(effective_aggregation) else {
+ return false;
+ };
+ let Some(group_type) = self
+ .group_type_mapping
+ .mapping()
+ .and_then(|m| m.group_indexes_to_types().get(&gti))
+ else {
+ return false;
+ };
+ if !self.has_usable_group_key(group_type) {
+ return false;
+ }
+ !group_property_overrides
+ .and_then(|overrides| overrides.get(group_type))
+ .is_some_and(|group_overrides| group_overrides.contains_key(&filter.key))
+ }
+
+ /// Whether a filter must be matched with `partial_props`, i.e. treat an absent key as
+ /// "unknown" (an error, which the caller turns into no-match) rather than as
+ /// "the property is not set" (which would make negative operators match by accident).
+ ///
+ /// This is only true when the relevant property source was never fetched. Fetched and
+ /// deliberately-skipped property maps are authoritative, so an absent key there
+ /// genuinely means the property is unset.
+ fn filter_needs_partial_props(
+ &self,
+ filter: &PropertyFilter,
+ property_context: &PropertyContext,
+ ) -> bool {
+ if filter.prop_type != PropertyType::Group {
+ return self.flag_evaluation_state.person_properties_pending();
+ }
+
+ // A group filter with no resolvable group type index can't be routed to a group
+ // property map at all, so there is nothing to fail closed on.
+ let Some(gti) = filter.group_filter_index(property_context.aggregation) else {
+ return false;
+ };
+
+ // Without a resolved name for the index, nothing is known about the group: the
+ // lookup failed, or a loaded mapping predates the group type (a stale cache entry).
+ // The request may carry this very group under the name that can't be resolved, so
+ // this must not read as "no group context" — fail closed.
+ let Some(group_type) = self
+ .group_type_mapping
+ .mapping()
+ .and_then(|m| m.group_indexes_to_types().get(&gti))
+ else {
+ return true;
+ };
+
+ // No group key means no group context whatsoever — the request never claimed to be
+ // in a group of this type. Failing closed there would silently stop matching for
+ // every caller that doesn't send `groups`, which is a much broader behavior change
+ // than the fetch-miss this guard is for, so keep the existing semantics.
+ if !self.has_usable_group_key(group_type) {
+ return false;
+ }
+
+ self.flag_evaluation_state.group_properties_pending(gti)
+ }
+
/// Checks if a condition requires person/group properties to evaluate.
/// Returns false for rollout-only conditions or conditions with only flag-value filters.
fn condition_needs_properties(condition: &FlagPropertyGroup) -> bool {
@@ -1821,7 +1967,7 @@ impl FeatureFlagMatcher {
match prop.prop_type {
PropertyType::Person | PropertyType::PersonMetadata => needs_person = true,
PropertyType::Group => {
- if let Some(gti) = prop.group_type_index.or(effective_aggregation) {
+ if let Some(gti) = prop.group_filter_index(effective_aggregation) {
group_types.insert(gti);
}
}
@@ -1953,7 +2099,7 @@ impl FeatureFlagMatcher {
) -> Result<String, FlagError> {
if let Some(group_type_index) = aggregation_group_type_index {
// Group-based flag
- let group_key = match self.group_type_mapping.as_ref().and_then(|m| {
+ let group_key = match self.group_type_mapping.mapping().and_then(|m| {
m.group_indexes_to_types()
.get(&group_type_index)
.and_then(|group_type_name| self.groups.get(group_type_name))
@@ -2174,7 +2320,7 @@ impl FeatureFlagMatcher {
// Load group type mappings if needed. Errors are intentionally not propagated here:
// in the batch path (evaluate_flags_with_overrides), a group type mapping failure
// should not poison person-based flags in the same batch. prepare_group_data
- // gracefully returns an empty map when self.group_type_mapping is None, so
+ // gracefully returns an empty map when the mapping was never loaded, so
// group-based flags will fail individually rather than taking down the whole batch.
if self.initialize_group_type_mappings_if_needed(flags).await {
tracing::warn!("Failed to init group type mappings");
@@ -2284,33 +2430,54 @@ impl FeatureFlagMatcher {
Ok(())
}
+ /// Every group type index a flag can read during evaluation: flag-level aggregation,
+ /// per-condition aggregation, and the explicit `group_type_index` on individual group
+ /// property filters. Indexes may repeat, so collect into a set where uniqueness matters.
+ ///
+ /// The filter-level indexes matter for mixed targeting, where a person-aggregated
+ /// condition still carries a group filter with its own index.
+ /// `PropertyContext::resolve_for_filter` resolves such a filter against exactly that
+ /// index, so omitting it from the fetch would silently resolve the filter against an
+ /// empty map instead of the group's real properties.
+ pub(crate) fn referenced_group_type_indexes(
+ flag: &FeatureFlag,
+ ) -> impl Iterator<Item = GroupTypeIndex> + '_ {
+ flag.get_group_type_index()
+ .into_iter()
+ .chain(flag.get_conditions().iter().flat_map(|condition| {
+ condition
+ .aggregation_group_type_index
+ .flatten()
+ .into_iter()
+ .chain(
+ condition
+ .properties
+ .iter()
+ .flatten()
+ // No aggregation fallback here: the arms above already chain
+ // every aggregation index, so only explicit indexes are added.
+ .filter_map(|prop| prop.group_filter_index(None)),
+ )
+ }))
+ }
+
/// Builds a paired mapping from group type index to group key for flag
/// evaluation, filtered to only the group types required by the given flags.
fn prepare_group_data(
&mut self,
flags: &[&FeatureFlag],
) -> Result<HashMap<GroupTypeIndex, String>, FlagError> {
- // Collect group type indexes from both flag-level and per-condition aggregation,
- // so we fetch data for all group types referenced by any condition.
let required_type_indexes: HashSet<GroupTypeIndex> = flags
.iter()
- .flat_map(|flag| {
- let flag_level = flag.get_group_type_index();
- let condition_level = flag
- .get_conditions()
- .iter()
- .filter_map(|c| c.aggregation_group_type_index.flatten());
- flag_level.into_iter().chain(condition_level)
- })
+ .flat_map(|flag| Self::referenced_group_type_indexes(flag))
.collect();
if required_type_indexes.is_empty() {
return Ok(HashMap::new());
}
- let mapping = match &self.group_type_mapping {
- Some(m) => m,
- None => return Ok(HashMap::new()),
+ let Some(mapping) = self.group_type_mapping.mapping() else {
+ return Ok(HashMap::new());
};
let types_to_indexes = mapping.group_types_to_indexes();
@@ -2399,7 +2566,10 @@ impl FeatureFlagMatcher {
log.eval.property_cache_misses += 1;
log.eval.group_properties_not_cached = true;
});
- // Return empty HashMap instead of error - no properties is a valid state
+ // Return an empty HashMap instead of an error: a group with no `posthog_group`
+ // row genuinely has no properties. Whether the fetch actually ran is tracked
+ // separately by `FlagEvaluationState::group_properties_pending`, which
+ // `is_condition_match` consults so a fetch miss can't be read as "unset".
Ok(HashMap::new())
}
}
@@ -2493,14 +2663,23 @@ impl FeatureFlagMatcher {
/// This function checks if any of the feature flags have group type indices and initializes the group type mapping cache if needed.
/// It returns a boolean indicating if there were any errors while initializing the group type mapping cache.
async fn initialize_group_type_mappings_if_needed(&mut self, flags: &[&FeatureFlag]) -> bool {
- // Check if we need to fetch group type mappings — any flag or condition uses group aggregation
+ // The lookup is request-scoped, and the batch path runs it before
+ // `prepare_flag_evaluation_state` runs it again. `GroupTypeCacheManager` does not cache
+ // failures, so without reusing the recorded outcome a single outage costs every affected
+ // request two waits on two failed queries.
+ match self.group_type_mapping {
+ GroupTypeMappingState::Loaded(_) => return false,
+ GroupTypeMappingState::Failed => return true,
+ GroupTypeMappingState::Uninitialized => {}
+ }
+
+ // Check if we need to fetch group type mappings — any flag references a group type,
+ // whether through aggregation or through an individual group property filter. The
+ // filter case must be included: without the mapping, `prepare_group_data` returns
+ // an empty map and those filters evaluate against no properties at all.
let has_type_indexes = flags.iter().any(|flag| {
!self.filtered_out_flag_ids.contains(&flag.id)
- && (flag.get_group_type_index().is_some()
- || flag
- .get_conditions()
- .iter()
- .any(|c| matches!(c.aggregation_group_type_index, Some(Some(_)))))
+ && Self::referenced_group_type_indexes(flag).next().is_some()
});
if !has_type_indexes {
@@ -2511,17 +2690,19 @@ impl FeatureFlagMatcher {
let mut errors_while_computing_flags = false;
match self.group_type_cache.get_mappings(self.team_id).await {
- Ok(mapping) if mapping.is_empty() => {
- tracing::warn!("No group type mappings found for team {}", self.team_id);
- // Empty mappings are not an error — the team simply has no group types configured.
- // Group-based flags won't match, but person flags in the same batch should succeed
- // without surfacing errorsWhileComputingFlags to the client.
- }
Ok(mapping) => {
- self.group_type_mapping = Some(mapping);
+ if mapping.is_empty() {
+ // Empty mappings are not an error — the team simply has no group types
+ // configured. Group-based flags won't match, but person flags in the same
+ // batch should succeed without surfacing errorsWhileComputingFlags to the
+ // client.
+ tracing::warn!("No group type mappings found for team {}", self.team_id);
+ }
+ self.group_type_mapping = GroupTypeMappingState::Loaded(mapping);
}
Err(_) => {
errors_while_computing_flags = true;
+ self.group_type_mapping = GroupTypeMappingState::Failed;
}
}
diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rs
index acf03d365296..48c4a8d21e44 100644
--- a/rust/feature-flags/src/flags/flag_matching_utils.rs
+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs
@@ -603,6 +603,14 @@ pub async fn fetch_and_locally_cache_all_relevant_properties(
)?;
apply_person_cohort_to_state(flag_evaluation_state, person_cohort);
+ // Mark every requested index as fetched, not just the ones the query returned a
+ // row for. The group query is authoritative for all requested (index, key) pairs,
+ // so "no row" means the group genuinely has no properties. Recording that keeps it
+ // distinguishable from "prep never ran", which is what
+ // `FlagEvaluationState::group_properties_pending` keys on.
+ for &idx in group_type_to_key.keys() {
+ flag_evaluation_state.mark_group_properties_fetched(idx);
+ }
for (idx, props) in group.group_properties {
flag_evaluation_state.set_group_properties(idx, props);
}
diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rs
index 1cc500263bdb..f1cf52f62d5e 100644
--- a/rust/feature-flags/src/flags/flag_operations.rs
+++ b/rust/feature-flags/src/flags/flag_operations.rs
@@ -1,4 +1,6 @@
+use crate::flags::flag_group_type_mapping::GroupTypeIndex;
use crate::flags::flag_models::*;
+use crate::properties::property_models::PropertyFilter;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
@@ -34,9 +36,17 @@ impl FeatureFlag {
///
/// This is true if the flag has a group type index set
/// OR if the flag has a cohort filter
- /// OR if the flag has a property filter and the property filter is not present in the overrides
- pub fn requires_db_preparation(&self, overrides: &HashMap<String, Value>) -> bool {
- self.filters.requires_db_properties(overrides, &self.key)
+ /// OR if the flag has a person property filter that is not present in the overrides
+ /// OR if the flag has a group property filter that `group_filter_needs_db` selects
+ /// (the caller owns the request's group context — see
+ /// `FeatureFlagMatcher::group_filter_needs_db_prep`)
+ pub fn requires_db_preparation(
+ &self,
+ overrides: &HashMap<String, Value>,
+ group_filter_needs_db: &dyn Fn(&PropertyFilter, Option<GroupTypeIndex>) -> bool,
+ ) -> bool {
+ self.filters
+ .requires_db_properties(overrides, &self.key, group_filter_needs_db)
|| self.filters.requires_cohort_filters()
}
@@ -130,11 +140,13 @@ pub fn flags_require_db_preparation<'a>(
flags: &[&'a FeatureFlag],
overrides: &HashMap<String, Value>,
filtered_out_flag_ids: &HashSet<i32>,
+ group_filter_needs_db: &dyn Fn(&PropertyFilter, Option<GroupTypeIndex>) -> bool,
) -> Vec<&'a FeatureFlag> {
flags
.iter()
.filter(|flag| {
- !filtered_out_flag_ids.contains(&flag.id) && flag.requires_db_preparation(overrides)
+ !filtered_out_flag_ids.contains(&flag.id)
+ && flag.requires_db_preparation(overrides, group_filter_needs_db)
})
.copied()
.collect()
@@ -1233,12 +1245,12 @@ mod tests {
)]);
assert!(flag.get_group_type_index().is_none());
- assert!(!flag.requires_db_preparation(&overrides));
+ assert!(!flag.requires_db_preparation(&overrides, &|_, _| true));
flag.filters.aggregation_group_type_index = Some(0);
assert!(flag.get_group_type_index().is_some());
- assert!(flag.requires_db_preparation(&overrides));
+ assert!(flag.requires_db_preparation(&overrides, &|_, _| true));
}
#[test]
@@ -1253,7 +1265,7 @@ mod tests {
Value::String("value".to_string()),
)]);
- assert!(flag.requires_db_preparation(&overrides));
+ assert!(flag.requires_db_preparation(&overrides, &|_, _| true));
}
#[test]
@@ -1273,7 +1285,7 @@ mod tests {
Value::String("value".to_string()),
),
]);
- assert!(flag.requires_db_preparation(&overrides));
+ assert!(flag.requires_db_preparation(&overrides, &|_, _| true));
}
{
@@ -1287,7 +1299,7 @@ mod tests {
Value::String("value".to_string()),
),
]);
- assert!(!flag.requires_db_preparation(&overrides));
+ assert!(!flag.requires_db_preparation(&overrides, &|_, _| true));
}
}
@@ -1297,7 +1309,7 @@ mod tests {
let mut flag = mock!(FeatureFlag);
flag.filters.holdout = Some(mock!(Holdout));
- assert!(!flag.requires_db_preparation(&HashMap::new()));
+ assert!(!flag.requires_db_preparation(&HashMap::new(), &|_, _| true));
}
// ======== Tests for experience continuity optimization helper methods ========
@@ -1716,18 +1728,19 @@ mod tests {
let overrides = HashMap::new();
// Without filtering, both flags require DB preparation
- let result = flags_require_db_preparation(&flags, &overrides, &HashSet::new());
+ let result =
+ flags_require_db_preparation(&flags, &overrides, &HashSet::new(), &|_, _| true);
assert_eq!(result.len(), 2);
// With flag_a filtered out, only flag_b requires preparation
let filtered = HashSet::from([1]);
- let result = flags_require_db_preparation(&flags, &overrides, &filtered);
+ let result = flags_require_db_preparation(&flags, &overrides, &filtered, &|_, _| true);
assert_eq!(result.len(), 1);
assert_eq!(result[0].key, "flag_b");
// With both filtered, none require preparation
let filtered = HashSet::from([1, 2]);
- let result = flags_require_db_preparation(&flags, &overrides, &filtered);
+ let result = flags_require_db_preparation(&flags, &overrides, &filtered, &|_, _| true);
assert!(result.is_empty());
}
}
diff --git a/rust/feature-flags/src/flags/flag_property_group.rs b/rust/feature-flags/src/flags/flag_property_group.rs
index cf5cd16f6387..e12ae751f509 100644
--- a/rust/feature-flags/src/flags/flag_property_group.rs
+++ b/rust/feature-flags/src/flags/flag_property_group.rs
@@ -1,4 +1,5 @@
use crate::flags::flag_models::FlagPropertyGroup;
+use crate::properties::property_models::{PropertyFilter, PropertyType};
use serde_json::Value;
use std::collections::HashMap;
@@ -30,14 +31,25 @@ impl FlagPropertyGroup {
/// Returns true if the overrides are not enough to evaluate the group locally.
///
- /// This is true if the group is rolled out to some percentage greater than 0.0
- /// and all the properties in the group require DB properties to be evaluated.
- pub fn requires_db_properties(&self, overrides: &HashMap<String, Value>) -> bool {
+ /// This is true if the group is rolled out to some percentage greater than 0.0 and any
+ /// of its filters still needs the database. Person overrides answer that for person
+ /// filters; group filters depend on request group context the flag model does not hold,
+ /// so the caller supplies that decision — see
+ /// `FeatureFlagMatcher::group_filter_needs_db_prep`.
+ pub fn requires_db_properties(
+ &self,
+ overrides: &HashMap<String, Value>,
+ group_filter_needs_db: &dyn Fn(&PropertyFilter) -> bool,
+ ) -> bool {
self.is_rolled_out_to_some()
&& self.properties.as_ref().is_some_and(|properties| {
- properties
- .iter()
- .any(|prop| prop.requires_db_property(overrides))
+ properties.iter().any(|prop| {
+ if prop.prop_type == PropertyType::Group {
+ group_filter_needs_db(prop)
+ } else {
+ prop.requires_db_property(overrides)
+ }
+ })
})
}
@@ -115,7 +127,7 @@ mod tests {
variant: None,
..Default::default()
};
- assert!(!group.requires_db_properties(&HashMap::new()));
+ assert!(!group.requires_db_properties(&HashMap::new(), &|_| true));
}
#[test]
@@ -136,7 +148,7 @@ mod tests {
"another_key".to_string(),
Value::String("another_value".to_string()),
)]);
- assert!(group.requires_db_properties(&overrides));
+ assert!(group.requires_db_properties(&overrides, &|_| true));
}
{
@@ -148,7 +160,7 @@ mod tests {
Value::String("another_value".to_string()),
),
]);
- assert!(!group.requires_db_properties(&overrides));
+ assert!(!group.requires_db_properties(&overrides, &|_| true));
}
}
@@ -164,7 +176,7 @@ mod tests {
..Default::default()
};
- assert!(!group.requires_db_properties(&HashMap::new()));
+ assert!(!group.requires_db_properties(&HashMap::new(), &|_| true));
}
#[test]
diff --git a/rust/feature-flags/src/flags/property_filter.rs b/rust/feature-flags/src/flags/property_filter.rs
index 254e937c9f82..b5735da94656 100644
--- a/rust/feature-flags/src/flags/property_filter.rs
+++ b/rust/feature-flags/src/flags/property_filter.rs
@@ -3,6 +3,7 @@ use serde_json::Value;
use std::collections::HashMap;
use crate::cohorts::cohort_models::CohortId;
+use crate::flags::flag_group_type_mapping::GroupTypeIndex;
use crate::flags::flag_models::FeatureFlagId;
use crate::properties::property_matching::{
lookup_key_for, to_string_representation, REGEX_BACKTRACK_LIMIT,
@@ -45,19 +46,45 @@ impl PropertyFilter {
self.key.parse::<FeatureFlagId>().ok()
}
+ /// The group type index a group filter reads at match time: the filter's explicit
+ /// `group_type_index`, or the condition's effective aggregation index for legacy filters
+ /// without one. `None` for non-group filters, and for group filters with no index in
+ /// reach. Every path that routes a group filter to a property map or a fetch resolves
+ /// through here, so they cannot drift apart.
+ pub fn group_filter_index(
+ &self,
+ effective_aggregation: Option<GroupTypeIndex>,
+ ) -> Option<GroupTypeIndex> {
+ if self.prop_type != PropertyType::Group {
+ return None;
+ }
+ self.group_type_index.or(effective_aggregation)
+ }
+
/// Returns true if the filter requires DB properties to be evaluated.
///
- /// This is true if the filter key is not in the overrides, but only for non cohort and non flag filters.
+ /// This is true if the filter key is not in the person property overrides, but only for non
+ /// cohort and non flag filters.
+ ///
+ /// The overrides hold person properties, so they can only satisfy a filter that reads the
+ /// person property map. A group filter reads its own group's property map, which no person
+ /// override populates, so a same-named person property says nothing about it. This method
+ /// therefore always selects group filters; the batch preparation scan refines that with the
+ /// request's group context instead — see `FeatureFlagMatcher::group_filter_needs_db_prep`.
///
/// Uses `lookup_key_for` rather than the raw `self.key` so PersonMetadata filters check the
/// sentinel-prefixed key (e.g. `__posthog_person_metadata__created_at`). Without this, an SDK
/// caller sending a raw `created_at` in `person_properties` overrides would make this return
/// `false`, skip the DB fetch, and let the filter fall through to operator defaults — silently
/// bypassing the real persons-table value.
- pub fn requires_db_property(&self, overrides: &HashMap<String, Value>) -> bool {
- !self.is_cohort()
- && !self.depends_on_feature_flag()
- && !overrides.contains_key(lookup_key_for(self).as_ref())
+ pub fn requires_db_property(&self, person_property_overrides: &HashMap<String, Value>) -> bool {
+ if self.is_cohort() || self.depends_on_feature_flag() {
+ return false;
+ }
+ if self.prop_type == PropertyType::Group {
+ return true;
+ }
+ !person_property_overrides.contains_key(lookup_key_for(self).as_ref())
}
/// Pre-compiles the regex pattern for Regex/NotRegex operators.
@@ -140,6 +167,30 @@ mod tests {
assert!(!filter.requires_db_property(&sentinel));
}
+ #[test]
+ fn test_group_filter_requires_db_when_person_override_shares_its_key() {
+ let filter = mock!(crate::properties::property_models::PropertyFilter, key: "tier".mock_into(), prop_type: PropertyType::Group, group_type_index: Some(1), operator: Some(OperatorType::Exact));
+
+ // A person `tier` says nothing about the organization's `tier`, so the group's
+ // properties still have to be fetched.
+ let person_tier = HashMap::from([("tier".to_string(), Value::String("free".to_string()))]);
+ assert!(filter.requires_db_property(&person_tier));
+ }
+
+ #[test]
+ fn test_group_filter_index_resolves_explicit_index_then_aggregation() {
+ let explicit = mock!(crate::properties::property_models::PropertyFilter, key: "tier".mock_into(), prop_type: PropertyType::Group, group_type_index: Some(2), operator: Some(OperatorType::Exact));
+ assert_eq!(explicit.group_filter_index(Some(1)), Some(2));
+
+ let legacy = mock!(crate::properties::property_models::PropertyFilter, key: "tier".mock_into(), prop_type: PropertyType::Group, operator: Some(OperatorType::Exact));
+ assert_eq!(legacy.group_filter_index(Some(1)), Some(1));
+ assert_eq!(legacy.group_filter_index(None), None);
+
+ // A person filter never resolves to a group map, whatever the aggregation.
+ let person = mock!(crate::properties::property_models::PropertyFilter, key: "tier".mock_into(), prop_type: PropertyType::Person, operator: Some(OperatorType::Exact));
+ assert_eq!(person.group_filter_index(Some(1)), None);
+ }
+
#[test]
fn test_filter_does_not_require_db_property_if_cohort_or_flag_filter() {
// Cohort filter.
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index f211af374b5e..27eb51041bba 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -18,7 +18,7 @@ mod tests {
},
flags::{
feature_flag_list::PreparedFlags,
- flag_group_type_mapping::GroupTypeCacheManager,
+ flag_group_type_mapping::{GroupTypeCacheManager, GroupTypeMapping},
flag_match_reason::FeatureFlagMatchReason,
flag_matching::{FeatureFlagMatch, FeatureFlagMatcher, PropertyContext},
flag_matching_utils::{
@@ -35,7 +35,10 @@ mod tests {
utils::{
graph_utils::PrecomputedDependencyGraph,
mock::MockInto,
- test_utils::{flag_list_with_metadata, mock_group_type_cache, TestContext},
+ test_utils::{
+ failing_group_type_cache, flag_list_with_metadata, mock_group_type_cache,
+ TestContext,
+ },
},
};
@@ -1778,6 +1781,493 @@ mod tests {
assert_eq!(reason, FeatureFlagMatchReason::ConditionMatch);
}
+ /// Builds a matcher whose seeded group type mapping knows "organization" at index 0 —
+ /// or, when `mapping_knows_organization` is false, a loaded but empty mapping, the
+ /// stale-cache shape a request sees when the mapping was cached before the group type
+ /// was added. Group-property DB prep is deliberately never run, so
+ /// `group_properties_pending(0)` holds unless the caller marks the index fetched.
+ async fn group_matcher_without_group_prep(
+ with_group_key: bool,
+ mapping_knows_organization: bool,
+ ) -> (TestContext, FeatureFlagMatcher) {
+ let context = TestContext::new(None).await;
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ let organization_at_zero = HashMap::from([("organization".to_string(), 0)]);
+ let groups =
+ with_group_key.then(|| HashMap::from([("organization".to_string(), json!("acme"))]));
+ let mut matcher = FeatureFlagMatcher::new(
+ "test_user".to_string(),
+ None,
+ 1,
+ context.create_postgres_router(),
+ cohort_cache,
+ mock_group_type_cache(organization_at_zero.clone()),
+ groups,
+ );
+ // Set in production by `initialize_group_type_mappings_if_needed`, which a bare
+ // `is_condition_match` test doesn't reach.
+ let seeded_mapping = if mapping_knows_organization {
+ organization_at_zero
+ } else {
+ HashMap::new()
+ };
+ matcher.set_group_type_mapping_for_test(GroupTypeMapping::new(seeded_mapping));
+ (context, matcher)
+ }
+
+ fn organization_tier_filter(operator: OperatorType) -> PropertyFilter {
+ PropertyFilter {
+ key: "tier".to_string(),
+ value: Some(json!("enterprise")),
+ operator: Some(operator),
+ prop_type: PropertyType::Group,
+ group_type_index: Some(1),
+ negation: None,
+ compiled_regex: None,
+ extra: Default::default(),
+ }
+ }
+
+ /// A flag whose single condition aggregates on the person but filters on an organization
+ /// property. This mixed shape is the one that reaches the group fetch state at all: a
+ /// group-aggregated condition is skipped outright when no group key is present.
+ fn mixed_targeting_flag(team_id: TeamId, operator: OperatorType) -> FeatureFlag {
+ mock!(FeatureFlag,
+ team_id: team_id,
+ filters: FlagFilters {
+ groups: vec![FlagPropertyGroup {
+ properties: Some(vec![organization_tier_filter(operator)]),
+ rollout_percentage: Some(100.0),
+ variant: None,
+ aggregation_group_type_index: Some(None),
+ extra: Default::default(),
+ }],
+ aggregation_group_type_index: None,
+ ..Default::default()
+ }
+ )
+ }
+
+ /// Regression test: the group-property analogue of the person `Pending` guard. A
+ /// negative operator must not read an unfetched group property map as "this group has
+ /// no tier", which would grant the flag to precisely the enterprise organizations the
+ /// condition excludes. The other cases pin the deliberate limits of that guard: the
+ /// no-group-key exception applies only after the mapping resolves the filter's index,
+ /// so a stale mapping that predates the group type must not read as "no group key".
+ #[rstest::rstest]
+ #[case::pending_fails_closed(
+ true,
+ true,
+ false,
+ false,
+ "an unfetched group property must not satisfy is_not"
+ )]
+ #[case::fetched_empty_matches(
+ true,
+ true,
+ true,
+ true,
+ "a fetched and genuinely empty group has no tier, so is_not should match"
+ )]
+ #[case::no_group_key_matches(
+ false,
+ true,
+ false,
+ true,
+ "no group context should keep pre-existing behavior rather than fail closed"
+ )]
+ #[case::stale_mapping_fails_closed(
+ true,
+ false,
+ false,
+ false,
+ "a loaded mapping that lacks the filter's index says nothing about the group, so is_not must not match"
+ )]
+ #[tokio::test]
+ async fn test_is_condition_match_group_is_not_honors_group_property_fetch_state(
+ #[case] with_group_key: bool,
+ #[case] mapping_knows_organization: bool,
+ #[case] mark_fetched: bool,
+ #[case] expected_match: bool,
+ #[case] scenario: &str,
+ ) {
+ let (_context, mut matcher) =
+ group_matcher_without_group_prep(with_group_key, mapping_knows_organization).await;
+ let flag = mock!(FeatureFlag);
+ if mark_fetched {
+ matcher
+ .flag_evaluation_state
+ .mark_group_properties_fetched(0);
+ }
+ assert_eq!(
+ matcher.flag_evaluation_state.group_properties_pending(0),
+ !mark_fetched
+ );
+
+ let condition = FlagPropertyGroup {
+ variant: None,
+ properties: Some(vec![PropertyFilter {
+ group_type_index: Some(0),
+ ..organization_tier_filter(OperatorType::IsNot)
+ }]),
+ rollout_percentage: Some(100.0),
+ ..Default::default()
+ };
+
+ // Mirrors what the lazy loader caches for an index with no fetched properties.
+ let group_properties = if with_group_key {
+ HashMap::from([(0, HashMap::new())])
+ } else {
+ HashMap::new()
+ };
+ let ctx = PropertyContext {
+ person_properties: None,
+ group_properties: &group_properties,
+ aggregation: None,
+ };
+ let (is_match, _) = matcher
+ .is_condition_match(&flag, &condition, &ctx, None, &None)
+ .unwrap();
+ assert_eq!(is_match, expected_match, "{scenario}");
+ }
+
+ /// Regression test: a real `GroupTypeCacheManager` failure must reach the fail-closed
+ /// guard, and its outcome must be reused for the rest of the request. Without the mapping
+ /// the matcher cannot tell "the request sent no organization" from "the lookup broke", and
+ /// the former reading would let `is_not` match an empty property map for an organization
+ /// that is in fact excluded. The batch path also asks for the mapping once during setup
+ /// and once during preparation, and failures are not cached, so without the recorded
+ /// outcome an outage would cost every affected request two failed queries.
+ #[tokio::test]
+ async fn test_mixed_targeting_is_not_fails_closed_when_mapping_lookup_fails() {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ context
+ .create_group(
+ team.id,
+ "organization",
+ "acme",
+ json!({"tier": "enterprise"}),
+ )
+ .await
+ .unwrap();
+ context
+ .insert_person(
+ team.id,
+ "test_user".to_string(),
+ Some(json!({"plan": "pro"})),
+ )
+ .await
+ .unwrap();
+
+ // A matching person filter alongside the group filter keeps the flag in DB
+ // preparation — a failed mapping leaves nothing to fetch for the group filter
+ // itself — and leaves the guard as the only thing stopping the match.
+ let mut flag = mixed_targeting_flag(team.id, OperatorType::IsNot);
+ flag.filters.groups[0]
+ .properties
+ .as_mut()
+ .unwrap()
+ .push(PropertyFilter {
+ key: "plan".to_string(),
+ value: Some(json!("pro")),
+ operator: Some(OperatorType::Exact),
+ prop_type: PropertyType::Person,
+ group_type_index: None,
+ negation: None,
+ compiled_regex: None,
+ extra: Default::default(),
+ });
+
+ let (group_type_cache, mapping_fetch_calls) = failing_group_type_cache();
+ let mut matcher = FeatureFlagMatcher::new(
+ "test_user".to_string(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ group_type_cache,
+ Some(HashMap::from([("organization".to_string(), json!("acme"))])),
+ );
+
+ // A mapping failure is deliberately not propagated: it must not poison person flags in
+ // the same batch, so evaluation proceeds and the guard is what stops the match.
+ let result = matcher
+ .evaluate_all_feature_flags(
+ flag_list_with_metadata(vec![flag.clone()]),
+ None,
+ None,
+ None,
+ Uuid::new_v4(),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ result.flags.get(&flag.key).unwrap().to_value(),
+ FlagValue::Boolean(false),
+ "a failed mapping lookup knows nothing about the organization, so is_not must not match"
+ );
+ assert_eq!(
+ mapping_fetch_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the request must reuse its first failed mapping lookup rather than query again"
+ );
+ }
+
+ /// Regression test: an organization the request names but that has no `posthog_group` row
+ /// must still count as fetched. The fetch is authoritative for every requested pair, so
+ /// "no row" means the organization genuinely has no tier and `is_not` should match. If the
+ /// fetch path stopped recording that, the fail-closed guard would reject every such
+ /// organization instead.
+ #[tokio::test]
+ async fn test_mixed_targeting_is_not_matches_group_with_no_stored_row() {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+
+ let flag = mixed_targeting_flag(team.id, OperatorType::IsNot);
+ let mut matcher = FeatureFlagMatcher::new(
+ "test_user".to_string(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ mock_group_type_cache(HashMap::from([("organization".to_string(), 1)])),
+ Some(HashMap::from([(
+ "organization".to_string(),
+ json!("no-such-org"),
+ )])),
+ );
+
+ matcher
+ .prepare_flag_evaluation_state(&[&flag])
+ .await
+ .unwrap();
+ assert!(
+ !matcher.flag_evaluation_state.group_properties_pending(1),
+ "the fetch ran for the requested organization, so index 1 must not read as pending"
+ );
+
+ let match_result = matcher.get_match(&flag, None, None, None, &None).unwrap();
+ assert!(
+ match_result.matches,
+ "an organization with no stored properties has no tier, so is_not should match"
+ );
+ }
+
+ /// Regression test: a group filter carrying its own `group_type_index` on a
+ /// person-aggregated condition must have its properties loaded, so the organization's
+ /// stored tier decides the flag. Before the fetch covered filter-level indexes, both
+ /// operators resolved against an empty map, so `is` never matched and `is_not` always did.
+ #[rstest::rstest]
+ #[case::exact_matches_stored_tier(OperatorType::Exact, true)]
+ #[case::is_not_rejects_stored_tier(OperatorType::IsNot, false)]
+ #[tokio::test]
+ async fn test_mixed_targeting_reads_stored_group_properties(
+ #[case] operator: OperatorType,
+ #[case] expected_match: bool,
+ ) {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ context
+ .create_group(
+ team.id,
+ "organization",
+ "acme",
+ json!({"tier": "enterprise"}),
+ )
+ .await
+ .unwrap();
+
+ let flag = mixed_targeting_flag(team.id, operator);
+ let mut matcher = FeatureFlagMatcher::new(
+ "test_user".to_string(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ mock_group_type_cache(HashMap::from([("organization".to_string(), 1)])),
+ Some(HashMap::from([("organization".to_string(), json!("acme"))])),
+ );
+
+ matcher
+ .prepare_flag_evaluation_state(&[&flag])
+ .await
+ .unwrap();
+ let match_result = matcher.get_match(&flag, None, None, None, &None).unwrap();
+
+ assert_eq!(
+ match_result.matches, expected_match,
+ "the organization's stored tier should decide the flag"
+ );
+ }
+
+ /// Regression test: a group filter the fetch cannot serve must not pull its flag into
+ /// DB preparation. With no usable organization key there is nothing to fetch for the
+ /// filter and matching keeps the old no-group-key result either way, so selecting the
+ /// flag anyway only cost an unnecessary person-property query.
+ #[tokio::test]
+ async fn test_mixed_targeting_without_group_key_skips_db_preparation() {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+
+ let flag = mixed_targeting_flag(team.id, OperatorType::IsNot);
+ let mut matcher = FeatureFlagMatcher::new(
+ "test_user".to_string(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ mock_group_type_cache(HashMap::from([("organization".to_string(), 1)])),
+ None,
+ );
+
+ reset_fetch_calls_count();
+ let result = matcher
+ .evaluate_all_feature_flags(
+ flag_list_with_metadata(vec![flag.clone()]),
+ None,
+ None,
+ None,
+ Uuid::new_v4(),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(!result.errors_while_computing_flags);
+ assert_eq!(
+ result.flags.get(&flag.key).unwrap().to_value(),
+ FlagValue::Boolean(true),
+ "no group key keeps the pre-existing is_not behavior"
+ );
+ assert_eq!(
+ get_fetch_calls_count(),
+ 0,
+ "nothing is fetchable for this flag, so preparation must not run the person query"
+ );
+ }
+
+ /// Regression test: a person property override must not stand in for a same-named group
+ /// property. The request sends `tier` for the person while the condition filters on the
+ /// organization's `tier`, and only the organization's stored value may decide the flag.
+ /// When the override suppressed DB preparation, the organization's properties stayed
+ /// unfetched and the fail-closed guard rejected the condition whichever way it pointed.
+ #[tokio::test]
+ async fn test_person_property_override_does_not_satisfy_same_named_group_filter() {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ context
+ .create_group(
+ team.id,
+ "organization",
+ "acme",
+ json!({"tier": "enterprise"}),
+ )
+ .await
+ .unwrap();
+
+ let flag = mixed_targeting_flag(team.id, OperatorType::Exact);
+ let mut matcher = FeatureFlagMatcher::new(
+ "test_user".to_string(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ mock_group_type_cache(HashMap::from([("organization".to_string(), 1)])),
+ Some(HashMap::from([("organization".to_string(), json!("acme"))])),
+ );
+
+ let result = matcher
+ .evaluate_all_feature_flags(
+ flag_list_with_metadata(vec![flag.clone()]),
+ Some(HashMap::from([("tier".to_string(), json!("free"))])),
+ None,
+ None,
+ Uuid::new_v4(),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(!result.errors_while_computing_flags);
+ assert_eq!(
+ result.flags.get(&flag.key).unwrap().to_value(),
+ FlagValue::Boolean(true),
+ "the organization is enterprise, so the person's own tier must not decide the flag"
+ );
+ }
+
+ /// Regression test: a group filter carrying its own `group_type_index` must be counted
+ /// as a referenced group type even when no condition aggregates on it, otherwise its
+ /// properties are never fetched and it always resolves against an empty map.
+ #[test]
+ fn test_referenced_group_type_indexes_includes_filter_level_index() {
+ let flag = mock!(FeatureFlag,
+ filters: FlagFilters {
+ groups: vec![FlagPropertyGroup {
+ properties: Some(vec![
+ mock!(PropertyFilter,
+ key: "tier".mock_into(),
+ value: Some(json!("enterprise")),
+ prop_type: PropertyType::Group,
+ group_type_index: Some(3)
+ ),
+ mock!(PropertyFilter,
+ key: "plan".mock_into(),
+ value: Some(json!("pro")),
+ prop_type: PropertyType::Person
+ ),
+ ]),
+ rollout_percentage: Some(100.0),
+ variant: None,
+ // Person-aggregated: index 3 is referenced only by the filter.
+ aggregation_group_type_index: Some(None),
+ extra: Default::default(),
+ }],
+ ..Default::default()
+ }
+ );
+
+ assert_eq!(
+ FeatureFlagMatcher::referenced_group_type_indexes(&flag).collect::<HashSet<_>>(),
+ HashSet::from([3])
+ );
+ }
+
/// Regression test: a `NOT_IN` cohort filter must not match when person-property DB prep
/// never ran. Cohort evaluation reads the same property map as direct filters, so under
/// `Pending` the person looks like they have no properties, the cohort resolves to "not a
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index 1ece9c9bb126..99fd717fd932 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -1933,6 +1933,41 @@ pub fn mock_group_type_cache(
Arc::new(GroupTypeCacheManager::new_with_fetcher(fetcher, None, None))
}
+pub struct FailingGroupTypeFetcher {
+ fetch_calls: Arc<std::sync::atomic::AtomicU32>,
+}
+
+#[async_trait]
+impl GroupTypeMappingFetcher for FailingGroupTypeFetcher {
+ async fn fetch(
+ &self,
+ _team_id: common_types::TeamId,
+ ) -> Result<GroupTypeMapping, GroupTypeFetchError> {
+ self.fetch_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Err(GroupTypeFetchError::DatabaseUnavailable)
+ }
+}
+
+/// A group type cache whose lookups always fail, for tests that need the matcher to see a
+/// real mapping error rather than a seeded one. Also returns the number of lookups that
+/// reached the fetcher, so tests can pin that a request reuses its first failed outcome
+/// instead of querying again.
+pub fn failing_group_type_cache() -> (
+ Arc<GroupTypeCacheManager>,
+ Arc<std::sync::atomic::AtomicU32>,
+) {
+ let fetch_calls = Arc::new(std::sync::atomic::AtomicU32::new(0));
+ let cache = Arc::new(GroupTypeCacheManager::new_with_fetcher(
+ FailingGroupTypeFetcher {
+ fetch_calls: Arc::clone(&fetch_calls),
+ },
+ None,
+ None,
+ ));
+ (cache, fetch_calls)
+}
+
/// Delete a single auth token cache entry from Redis.
///
/// Both secret API tokens and personal API keys share the same cache namespace