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 group flags when the group type lookup fails (#112933)

Phil Haack2ed3b1d26c33
diff --git a/docs/internal/feature-flags/database-interaction-patterns.md b/docs/internal/feature-flags/database-interaction-patterns.md
index f3e86d59f4c8..712c49996e7c 100644
--- a/docs/internal/feature-flags/database-interaction-patterns.md
+++ b/docs/internal/feature-flags/database-interaction-patterns.md
@@ -96,6 +96,11 @@ The shared fetch has its own 5s cap instead of any request's deadline.
Without the cap, a fetch stuck on an unreachable database keeps running.
Every later request for the team then waits on that fetch instead of starting a new one.
A slow group type lookup uses up the shared deadline, so the properties fetch after it can fail even when person queries are fast.
+When the group type lookup stops at the deadline, a flag whose answer depends on a group condition also returns `timeout:persons_db_deadline`, unless another of its conditions settles the answer.
+A condition that aggregates by a group depends on the lookup when the request sends a usable group key, which is a non-empty string or a number.
+A condition that filters on a group property depends on the lookup when the request sends a usable group key or a group property override.
+That includes a flag that skips DB preparation because its only group filter has no resolved group type.
+See [Unfetched properties fail closed](flag-evaluation-engine.md#unfetched-properties-fail-closed).
Each stopped call increments `flags_database_error_total` with `timeout_type="persons_db_deadline"` and the call's `operation`.
The canonical log line records the first stopped call in `persons_db_deadline_exceeded`.
The internal batch evaluation endpoint does not apply the deadline. When a person's evaluation returns an error, Django leaves that person out of the static cohort and still reports the run as a success.
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.md
index 3fcef94b343f..68f4fdb43133 100644
--- a/docs/internal/feature-flags/flag-evaluation-engine.md
+++ b/docs/internal/feature-flags/flag-evaluation-engine.md
@@ -582,9 +582,17 @@ Both property sources record whether their fetch ran, and a filter whose source
- `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.
+- `group_type_mapping` records `Uninitialized`, `Loaded`, or `Failed`. A group filter fails closed unless the mapping resolves its group type index: a loaded mapping that lacks the index — a cache entry from before the group type was added — says nothing about that group.
-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.
+One case deliberately keeps the old behavior: a group type the request supplies no key for. It applies when the request carries no usable group key and no group property override, or when 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. A request without group context therefore gets the same answer under a loaded, stale, or failed mapping.
+
+A failed lookup says nothing about any group in the request, so a condition that aggregates by a group or filters on a group property cannot be evaluated when the request sends group context.
+The matcher cannot tell which group type the condition's index names, so a key or override for any group type counts.
+The matcher skips that condition and evaluates the others.
+A later condition that matches still decides the flag, although the skipped condition could have picked a different variant.
+With `early_exit`, a skipped condition below 100% rollout could instead stop on its rollout with no match, so a later match then returns `failed: true` too.
+When no condition matches, the flag returns `failed: true` with the lookup's own error code, such as `timeout:persons_db_deadline` or `database_unavailable`, instead of `false`.
+Client SDKs then keep their cached value.
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.
diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rs
index 944943704b89..34cc165cd0e4 100644
--- a/rust/feature-flags/src/api/errors.rs
+++ b/rust/feature-flags/src/api/errors.rs
@@ -7,6 +7,7 @@ use common_database::{
use common_hypercache::HyperCacheError;
use common_redis::CustomRedisError;
use serde::Serialize;
+use std::sync::Arc;
use thiserror::Error;
use crate::utils::graph_utils::DependencyType;
@@ -118,6 +119,8 @@ pub enum FlagError {
DependencyNotFound(DependencyType, i64),
#[error("Flag dependency {0} failed to evaluate")]
DependencyFailed(i64),
+ #[error("Group type mapping lookup failed: {0}")]
+ GroupTypeLookupFailed(Arc<FlagError>),
#[error("Failed to parse cohort filters")]
CohortFiltersParsingError,
#[error("Dependency cycle detected: {0} id {1} starts the cycle")]
@@ -262,6 +265,7 @@ impl FlagError {
FlagError::RowNotFound => ("row_not_found", 500),
FlagError::DependencyNotFound(_, _) => ("dependency_not_found", 500),
FlagError::DependencyFailed(_) => (CODE_DEPENDENCY_FAILED, 500),
+ FlagError::GroupTypeLookupFailed(cause) => cause.error_metadata(),
FlagError::CohortFiltersParsingError => ("cohort_filters_parsing_error", 500),
FlagError::DependencyCycle(_, _) => ("dependency_cycle", 500),
FlagError::HashKeyOverrideError => ("hash_key_override_error", 500),
@@ -334,6 +338,7 @@ impl FlagError {
}
FlagError::TimeoutError(Some(t)) => format!("timeout:{t}"),
FlagError::TimeoutError(None) => "timeout_error".to_string(),
+ FlagError::GroupTypeLookupFailed(cause) => cause.evaluation_error_code(),
FlagError::DependencyNotFound(dependency_type, _) => match dependency_type {
DependencyType::Cohort => "dependency_not_found_cohort".to_string(),
DependencyType::Flag => "dependency_not_found_flag".to_string(),
@@ -378,6 +383,7 @@ impl FlagError {
DependencyType::Flag => "Flag dependency not found".to_string(),
},
FlagError::DependencyFailed(_) => "Flag dependency failed to evaluate".to_string(),
+ FlagError::GroupTypeLookupFailed(cause) => cause.evaluation_error_description(),
FlagError::DependencyCycle(dependency_type, _) => match dependency_type {
DependencyType::Cohort => "Cohort dependency cycle detected".to_string(),
DependencyType::Flag => "Flag dependency cycle detected".to_string(),
@@ -562,6 +568,14 @@ impl IntoResponse for FlagError {
tracing::error!("Flag dependency {dependency_id} failed to evaluate");
(StatusCode::INTERNAL_SERVER_ERROR, format!("Flag dependency {dependency_id} failed to evaluate"))
}
+ FlagError::GroupTypeLookupFailed(cause) => {
+ tracing::error!("Group type mapping lookup failed: {cause:?}");
+ (
+ StatusCode::from_u16(cause.status_code())
+ .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
+ "Group type mapping lookup failed".to_string(),
+ )
+ }
FlagError::CohortFiltersParsingError => {
tracing::error!("Failed to parse cohort filters: {:?}", self);
(StatusCode::INTERNAL_SERVER_ERROR, "Failed to parse cohort filters. Please try again later or contact support if the problem persists.".to_string())
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index 47e644c1f4cd..0e4405103963 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -170,7 +170,7 @@ enum GroupTypeMappingState {
/// 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,
+ Failed(Arc<FlagError>),
}
impl GroupTypeMappingState {
@@ -388,6 +388,7 @@ pub(crate) struct PropertyContext<'a> {
pub person_properties: Option<&'a HashMap<String, Value>>,
pub group_properties: &'a HashMap<GroupTypeIndex, HashMap<String, Value>>,
pub aggregation: Option<GroupTypeIndex>,
+ pub request_has_group_context: bool,
}
impl PropertyContext<'_> {
@@ -544,6 +545,14 @@ fn ids_of_failed_flags<'a>(
.map(|details| details.metadata.id)
}
+fn is_usable_group_key(group_key: &Value) -> bool {
+ match group_key {
+ Value::String(s) => !s.is_empty(),
+ Value::Number(_) => true,
+ _ => false,
+ }
+}
+
// This is a plain fn rather than an `async fn` so that it boxes `call` before any async state
// captures it. An `async fn` would store `call` in its own state. The `before_deadline` and
// `timeout_at` futures store it again. In debug builds those copies grow the /flags handler
@@ -1473,6 +1482,11 @@ impl FeatureFlagMatcher {
"Feature flag '{}' failed because dependency {} failed",
flag.key, dependency_id
),
+ // The group type lookup already logged or counted its own failure.
+ FlagError::GroupTypeLookupFailed(cause) => debug!(
+ "Feature flag '{}' failed because the group type lookup failed: {:?}",
+ flag.key, cause
+ ),
_ => error!(
"Error evaluating feature flag '{}' for distinct_id '{}': {:?}",
flag.key, self.distinct_id, e
@@ -1772,6 +1786,21 @@ impl FeatureFlagMatcher {
// `failed: true` as false. Failing every dependent would therefore turn a settled `true`
// into false.
let mut answers_if_dependency_matched: Vec<AnswerIfDependencyMatched> = Vec::new();
+ // A later condition that matches still settles the flag. The skipped condition could
+ // have picked a different variant. With early exit, a skipped condition below 100%
+ // rollout could instead stop evaluation with no match, so a later match cannot settle
+ // the flag.
+ let mut group_lookup_error: Option<Arc<FlagError>> = None;
+ let mut group_lookup_skip_can_exit_early = false;
+ // The handler copies every request group key into the overrides as `$group_key`, also an
+ // unusable one. An override map with only an unusable `$group_key` therefore names no group.
+ let request_has_group_context = self.request_has_usable_group_key()
+ || group_property_overrides.is_some_and(|overrides| {
+ overrides
+ .values()
+ .flatten()
+ .any(|(key, value)| key != "$group_key" || is_usable_group_key(value))
+ });
let condition_timer = common_metrics::timing_guard(FLAG_EVALUATE_ALL_CONDITIONS_TIME, &[]);
for (index, condition) in conditions {
// Each condition resolves its own aggregation, falling back to the flag-level
@@ -1829,6 +1858,20 @@ impl FeatureFlagMatcher {
}
}
+ if let Some(error) =
+ self.group_lookup_error_for(condition, aggregation, request_has_group_context)
+ {
+ inc(
+ FLAG_CONDITION_SKIPPED_COUNTER,
+ &[("reason".to_string(), "group_type_lookup_failed".to_string())],
+ 1,
+ );
+ group_lookup_skip_can_exit_early |=
+ early_exit_enabled && condition.rollout_percentage_unwrapped() < 100.0;
+ group_lookup_error = Some(error);
+ continue;
+ }
+
// For group-aggregated conditions, verify we have the group key. If not, this
// condition can't match — log a warning and continue to the next condition.
// This checks the group key directly rather than calling hashed_identifier,
@@ -1891,6 +1934,7 @@ impl FeatureFlagMatcher {
person_properties: cached_person_properties.as_ref(),
group_properties: &cached_group_properties,
aggregation,
+ request_has_group_context,
};
let (is_match, reason) = self.is_condition_match(
@@ -1926,12 +1970,12 @@ impl FeatureFlagMatcher {
answer: ConditionAnswer::NoMatch,
});
} else {
- if let Some(dependency) = self.dependency_that_changes_answer(
+ if let Some(error) = self.no_match_error(
flag,
&answers_if_dependency_matched,
- &ConditionAnswer::NoMatch,
+ group_lookup_error,
) {
- return Err(FlagError::DependencyFailed(dependency.into()));
+ return Err(error);
}
return Ok(FeatureFlagMatch {
matches: false,
@@ -1989,6 +2033,10 @@ impl FeatureFlagMatcher {
return Err(FlagError::DependencyFailed(dependency.into()));
}
}
+ if let Some(error) = group_lookup_error.filter(|_| group_lookup_skip_can_exit_early)
+ {
+ return Err(FlagError::GroupTypeLookupFailed(error));
+ }
let payload = self.get_matching_payload(variant.as_deref(), flag);
return Ok(FeatureFlagMatch {
@@ -2002,12 +2050,10 @@ impl FeatureFlagMatcher {
}
}
- if let Some(dependency) = self.dependency_that_changes_answer(
- flag,
- &answers_if_dependency_matched,
- &ConditionAnswer::NoMatch,
- ) {
- return Err(FlagError::DependencyFailed(dependency.into()));
+ if let Some(error) =
+ self.no_match_error(flag, &answers_if_dependency_matched, group_lookup_error)
+ {
+ return Err(error);
}
condition_timer.label("outcome", "success").fin();
@@ -2120,6 +2166,21 @@ impl FeatureFlagMatcher {
.map(|candidate| candidate.failed_dependency)
}
+ fn no_match_error(
+ &self,
+ flag: &FeatureFlag,
+ answers_if_dependency_matched: &[AnswerIfDependencyMatched],
+ group_lookup_error: Option<Arc<FlagError>>,
+ ) -> Option<FlagError> {
+ self.dependency_that_changes_answer(
+ flag,
+ answers_if_dependency_matched,
+ &ConditionAnswer::NoMatch,
+ )
+ .map(|dependency| FlagError::DependencyFailed(dependency.into()))
+ .or_else(|| group_lookup_error.map(FlagError::GroupTypeLookupFailed))
+ }
+
/// This function determines the highest priority match evaluation for feature flag conditions.
/// It compares the current match reason with a new match reason and returns the higher priority one.
/// The priority is determined by the ordering of FeatureFlagMatchReason variants.
@@ -2304,15 +2365,16 @@ impl FeatureFlagMatcher {
self.group_type_mapping = GroupTypeMappingState::Loaded(mapping);
}
+ #[cfg(test)]
+ pub(crate) fn set_group_type_mapping_failed_for_test(&mut self, error: FlagError) {
+ self.group_type_mapping = GroupTypeMappingState::Failed(Arc::new(error));
+ }
+
/// 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,
- })
+ self.groups.get(group_type).is_some_and(is_usable_group_key)
}
/// `has_usable_group_key` by group type index. False both when the request omitted the
@@ -2325,6 +2387,37 @@ impl FeatureFlagMatcher {
.is_some_and(|group_type| self.has_usable_group_key(group_type))
}
+ fn request_has_usable_group_key(&self) -> bool {
+ self.groups.values().any(is_usable_group_key)
+ }
+
+ /// A condition names its group type by index. Only the mapping tells which group key or
+ /// group property override in the request has that index. A request without them gets
+ /// the same answer under any mapping, so its conditions evaluate as usual.
+ fn group_lookup_error_for(
+ &self,
+ condition: &FlagPropertyGroup,
+ aggregation: Option<GroupTypeIndex>,
+ request_has_group_context: bool,
+ ) -> Option<Arc<FlagError>> {
+ let GroupTypeMappingState::Failed(error) = &self.group_type_mapping else {
+ return None;
+ };
+ // A group-aggregated condition hashes the group key, so a request without a usable
+ // key gets no match from it under any mapping, even when it sends property overrides.
+ let outcome_unknown = if aggregation.is_some() {
+ self.request_has_usable_group_key()
+ } else {
+ request_has_group_context
+ && condition
+ .properties
+ .iter()
+ .flatten()
+ .any(|filter| filter.group_filter_index(None).is_some())
+ };
+ outcome_unknown.then(|| Arc::clone(error))
+ }
+
/// 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,
@@ -2378,6 +2471,12 @@ impl FeatureFlagMatcher {
return false;
};
+ // This check comes before the name lookup, so a failed or stale mapping does not change
+ // the answer for a request without group context.
+ if !property_context.request_has_group_context {
+ 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
@@ -3143,7 +3242,7 @@ impl FeatureFlagMatcher {
// request two waits on two failed queries.
match self.group_type_mapping {
GroupTypeMappingState::Loaded(_) => return false,
- GroupTypeMappingState::Failed => return true,
+ GroupTypeMappingState::Failed(_) => return true,
GroupTypeMappingState::Uninitialized => {}
}
@@ -3181,9 +3280,9 @@ impl FeatureFlagMatcher {
}
self.group_type_mapping = GroupTypeMappingState::Loaded(mapping);
}
- Err(_) => {
+ Err(e) => {
errors_while_computing_flags = true;
- self.group_type_mapping = GroupTypeMappingState::Failed;
+ self.group_type_mapping = GroupTypeMappingState::Failed(Arc::new(e));
}
}
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index 8c2430f8d17d..59e6f1bf3f18 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -11,7 +11,10 @@ mod tests {
use uuid::Uuid;
use crate::{
- api::types::{FlagValue, LegacyFlagsResponse},
+ api::{
+ errors::FlagError,
+ types::{FlagValue, LegacyFlagsResponse},
+ },
cohorts::{
cohort_cache_manager::CohortCacheManager,
cohort_models::{Cohort, CohortId, CohortType, MembershipStampPolicy},
@@ -1943,6 +1946,7 @@ mod tests {
person_properties: Some(&empty_person),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher
.is_condition_match(&flag, &condition, &ctx, None, &None)
@@ -1995,6 +1999,7 @@ mod tests {
person_properties: Some(&empty_person),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher
.is_condition_match(&flag, &condition, &ctx, None, &None)
@@ -2081,6 +2086,7 @@ mod tests {
person_properties: Some(&person_properties),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher
.is_condition_match(&flag, &condition, &ctx, None, &None)
@@ -2111,6 +2117,7 @@ mod tests {
person_properties: Some(&mismatched_properties),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher2
.is_condition_match(&flag, &condition, &ctx2, None, &None)
@@ -2136,6 +2143,7 @@ mod tests {
person_properties: Some(&person_properties),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher3
.is_condition_match(&flag, &condition, &ctx3, None, &None)
@@ -2194,6 +2202,7 @@ mod tests {
person_properties: Some(&empty_person),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher
.is_condition_match(&flag, &condition, &ctx, None, &None)
@@ -2253,6 +2262,7 @@ mod tests {
person_properties: Some(&overridden_person),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher
.is_condition_match(&flag, &condition, &ctx, None, &None)
@@ -2270,7 +2280,7 @@ mod tests {
/// 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,
+ organization_key: Option<serde_json::Value>,
mapping_knows_organization: bool,
) -> (TestContext, FeatureFlagMatcher) {
let context = TestContext::new(None).await;
@@ -2280,8 +2290,7 @@ mod tests {
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 groups = organization_key.map(|key| HashMap::from([("organization".to_string(), key)]));
let mut matcher = FeatureFlagMatcher::new(
"test_user".to_string(),
None,
@@ -2370,6 +2379,13 @@ mod tests {
false,
"a loaded mapping that lacks the filter's index says nothing about the group, so is_not must not match"
)]
+ #[case::no_group_key_stale_mapping_matches(
+ false,
+ false,
+ false,
+ true,
+ "a request with no group context gets the same answer under a stale mapping as under a loaded one"
+ )]
#[tokio::test]
async fn test_is_condition_match_group_is_not_honors_group_property_fetch_state(
#[case] with_group_key: bool,
@@ -2378,8 +2394,11 @@ mod tests {
#[case] expected_match: bool,
#[case] scenario: &str,
) {
- let (_context, mut matcher) =
- group_matcher_without_group_prep(with_group_key, mapping_knows_organization).await;
+ let (_context, mut matcher) = group_matcher_without_group_prep(
+ with_group_key.then(|| json!("acme")),
+ mapping_knows_organization,
+ )
+ .await;
let flag = mock!(FeatureFlag);
if mark_fetched {
matcher
@@ -2411,6 +2430,7 @@ mod tests {
person_properties: None,
group_properties: &group_properties,
aggregation: None,
+ request_has_group_context: with_group_key,
};
let (is_match, _) = matcher
.is_condition_match(&flag, &condition, &ctx, None, &None)
@@ -2418,8 +2438,8 @@ mod tests {
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
+ /// Regression test: a real `GroupTypeCacheManager` failure must fail the flag, 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
@@ -2453,8 +2473,8 @@ mod tests {
.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.
+ // preparation, which succeeds. The flag can then fail only in evaluation, where the
+ // failed lookup leaves the group filter unknown.
let mut flag = mixed_targeting_flag(team.id, OperatorType::IsNot);
flag.filters.groups[0]
.properties
@@ -2483,7 +2503,7 @@ mod tests {
);
// 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.
+ // the same batch, so evaluation proceeds and fails only the flags that read a group.
let result = matcher
.evaluate_all_feature_flags(
flag_list_with_metadata(vec![flag.clone()]),
@@ -2498,9 +2518,8 @@ mod tests {
.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"
+ result.flags[&flag.key].reason.code, "database_unavailable",
+ "a failed mapping lookup knows nothing about the organization, so the flag must fail"
);
assert_eq!(
mapping_fetch_calls.load(std::sync::atomic::Ordering::SeqCst),
@@ -2764,7 +2783,7 @@ mod tests {
HashSet::from([0, 4])
);
- let (_context, matcher) = group_matcher_without_group_prep(true, true).await;
+ let (_context, matcher) = group_matcher_without_group_prep(Some(json!("acme")), true).await;
let industry = HashMap::from([("industry".to_string(), json!("tech"))]);
let overrides = Some(HashMap::from([(
"organization".to_string(),
@@ -2841,6 +2860,7 @@ mod tests {
person_properties: Some(&empty_person),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher
.is_condition_match(&flag, &condition, &ctx, None, &None)
@@ -3292,6 +3312,7 @@ mod tests {
person_properties: Some(&empty_person),
group_properties: &empty_groups,
aggregation: None,
+ request_has_group_context: false,
};
let (is_match, reason) = matcher
.is_condition_match(&flag, &flag.filters.groups[0], &ctx, None, &None)
@@ -8199,7 +8220,7 @@ mod tests {
router,
Arc::new(CohortCacheManager::new(stalled_db.clone(), None, None)),
Arc::new(GroupTypeCacheManager::new(stalled_db.clone(), None, None)),
- None,
+ Some(HashMap::from([("project".to_string(), json!("p1"))])),
)
.with_persons_db_deadline(Some(deadline));
@@ -8223,7 +8244,19 @@ mod tests {
key: "group_flag".mock_into(),
filters: mock!(FlagFilters, aggregation_group_type_index: Some(0))
);
- let mut flag_list = vec![rollout_flag, person_flag, group_flag];
+ // A failed group type lookup keeps this flag out of DB preparation, so the failed
+ // properties fetch does not fail it.
+ let group_filter_flag = mock!(FeatureFlag,
+ id: 5,
+ key: "group_filter_flag".mock_into(),
+ filters: mock!(PropertyFilter,
+ key: "tier".mock_into(),
+ value: Some(json!("enterprise")),
+ prop_type: PropertyType::Group,
+ group_type_index: Some(0)
+ ).mock_into()
+ );
+ let mut flag_list = vec![rollout_flag, person_flag, group_flag, group_filter_flag];
if with_continuity_flag {
flag_list.push(continuity_flag);
}
@@ -8262,6 +8295,10 @@ mod tests {
response.flags["person_flag"].reason.code,
"timeout:persons_db_deadline"
);
+ assert_eq!(
+ response.flags["group_filter_flag"].reason.code,
+ "timeout:persons_db_deadline"
+ );
assert_eq!(
response
.flags
@@ -10816,6 +10853,132 @@ mod tests {
assert_eq!(result.condition_index, expected_condition_index);
}
+ fn organization_rollout_condition() -> FlagPropertyGroup {
+ mock!(FlagPropertyGroup, aggregation_group_type_index: Some(Some(1)))
+ }
+
+ fn person_rollout_condition(rollout_percentage: f64) -> FlagPropertyGroup {
+ mock!(FlagPropertyGroup, rollout_percentage: Some(rollout_percentage))
+ }
+
+ fn person_condition_with_organization_filter(operator: OperatorType) -> FlagPropertyGroup {
+ mock!(FlagPropertyGroup, properties: Some(vec![organization_tier_filter(operator)]))
+ }
+
+ #[derive(Debug, Clone, Copy)]
+ enum RequestGroupContext {
+ GroupKey,
+ UnusableGroupKey,
+ PropertyOverrideOnly,
+ Nothing,
+ }
+
+ /// Regression test: when the group type lookup fails, a flag whose answer depends on a
+ /// group condition must fail, so client SDKs keep their cached value instead of reading
+ /// `false`. Early exit is on, so a person condition outside its rollout must not settle the
+ /// flag after an unknown one. A person match must not settle it after an unknown condition
+ /// below 100% rollout, because that condition could stop on its rollout first.
+ #[rstest::rstest]
+ #[case::group_aggregation_fails_the_flag(
+ vec![organization_rollout_condition()],
+ RequestGroupContext::GroupKey,
+ None
+ )]
+ #[case::group_filter_fails_the_flag(
+ vec![person_condition_with_organization_filter(OperatorType::Exact)],
+ RequestGroupContext::GroupKey,
+ None
+ )]
+ #[case::group_property_override_fails_the_flag(
+ vec![person_condition_with_organization_filter(OperatorType::IsNot)],
+ RequestGroupContext::PropertyOverrideOnly,
+ None
+ )]
+ #[case::no_groups_in_request_settles_false(
+ vec![organization_rollout_condition()],
+ RequestGroupContext::Nothing,
+ Some((false, Some(0)))
+ )]
+ #[case::no_groups_in_request_matches_is_not(
+ vec![person_condition_with_organization_filter(OperatorType::IsNot)],
+ RequestGroupContext::Nothing,
+ Some((true, Some(0)))
+ )]
+ #[case::unusable_group_key_matches_is_not(
+ vec![person_condition_with_organization_filter(OperatorType::IsNot)],
+ RequestGroupContext::UnusableGroupKey,
+ Some((true, Some(0)))
+ )]
+ #[case::later_person_match_settles_true(
+ vec![organization_rollout_condition(), person_rollout_condition(100.0)],
+ RequestGroupContext::GroupKey,
+ Some((true, Some(1)))
+ )]
+ #[case::later_person_miss_fails_the_flag(
+ vec![organization_rollout_condition(), person_rollout_condition(0.0)],
+ RequestGroupContext::GroupKey,
+ None
+ )]
+ #[case::later_person_match_after_partial_rollout_fails_the_flag(
+ vec![
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![organization_tier_filter(OperatorType::Exact)]),
+ rollout_percentage: Some(0.0)
+ ),
+ person_rollout_condition(100.0),
+ ],
+ RequestGroupContext::GroupKey,
+ None
+ )]
+ #[tokio::test]
+ async fn test_failed_group_type_lookup_fails_only_unsettled_flags(
+ #[case] conditions: Vec<FlagPropertyGroup>,
+ #[case] request_groups: RequestGroupContext,
+ #[case] expected_match: Option<(bool, Option<usize>)>,
+ ) {
+ let organization_key = match request_groups {
+ RequestGroupContext::GroupKey => Some(json!("acme")),
+ RequestGroupContext::UnusableGroupKey => Some(json!("")),
+ RequestGroupContext::PropertyOverrideOnly | RequestGroupContext::Nothing => None,
+ };
+ let (_context, mut matcher) =
+ group_matcher_without_group_prep(organization_key.clone(), true).await;
+ let group_property_overrides = match request_groups {
+ RequestGroupContext::PropertyOverrideOnly => Some(HashMap::from([(
+ "organization".to_string(),
+ HashMap::from([("tier".to_string(), json!("enterprise"))]),
+ )])),
+ RequestGroupContext::UnusableGroupKey => {
+ crate::handler::properties::get_group_property_overrides(
+ organization_key.map(|key| HashMap::from([("organization".to_string(), key)])),
+ None,
+ )
+ }
+ RequestGroupContext::GroupKey | RequestGroupContext::Nothing => None,
+ };
+ matcher.set_group_type_mapping_failed_for_test(FlagError::DatabaseUnavailable);
+ let flag = mock!(FeatureFlag,
+ filters: FlagFilters {
+ groups: conditions,
+ early_exit: Some(true),
+ ..Default::default()
+ }
+ );
+
+ let result = matcher.get_match(&flag, None, group_property_overrides.as_ref(), None, &None);
+
+ match expected_match {
+ Some(expected) => {
+ let flag_match = result.unwrap();
+ assert_eq!((flag_match.matches, flag_match.condition_index), expected);
+ }
+ None => assert_eq!(
+ result.unwrap_err().evaluation_error_code(),
+ "database_unavailable"
+ ),
+ }
+ }
+
#[tokio::test]
async fn test_mixed_targeting_group_condition_matches_before_person_condition() {
// When both conditions could match, the first one (group) wins because conditions
@@ -11607,6 +11770,7 @@ mod tests {
person_properties: Some(&person_props),
group_properties: &group_props,
aggregation: None,
+ request_has_group_context: false,
};
let result = ctx.resolve_for_filter(&person_filter("plan"));
assert_eq!(result.get("plan"), Some(&json!("pro")));
@@ -11619,6 +11783,7 @@ mod tests {
person_properties: None,
group_properties: &group_props,
aggregation: None,
+ request_has_group_context: false,
};
let result = ctx.resolve_for_filter(&person_filter("plan"));
assert!(result.is_empty());
@@ -11635,6 +11800,7 @@ mod tests {
person_properties: Some(&person_props),
group_properties: &group_props,
aggregation: Some(1),
+ request_has_group_context: false,
};
// Explicit group_type_index takes precedence over aggregation
let result = ctx.resolve_for_filter(&group_filter("size", Some(0)));
@@ -11649,6 +11815,7 @@ mod tests {
person_properties: None,
group_properties: &group_props,
aggregation: Some(1),
+ request_has_group_context: false,
};
let result = ctx.resolve_for_filter(&group_filter("tier", None));
assert_eq!(result.get("tier"), Some(&json!("premium")));
@@ -11662,6 +11829,7 @@ mod tests {
person_properties: None,
group_properties: &group_props,
aggregation: None,
+ request_has_group_context: false,
};
let result = ctx.resolve_for_filter(&group_filter("size", None));
assert!(result.is_empty());