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 flags whose dependency failed (#109565)

Phil Haack8f6e8a8dc53e
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.md
index 6e42460f1fbe..3fcef94b343f 100644
--- a/docs/internal/feature-flags/flag-evaluation-engine.md
+++ b/docs/internal/feature-flags/flag-evaluation-engine.md
@@ -472,6 +472,27 @@ match filter.value {
Evaluated results are cached in `FlagEvaluationState.flag_evaluation_results` for subsequent dependent flags. Flags with missing or cyclic dependencies evaluate to `false` with reason `MissingDependency`.
+A failed flag records no result, so a dependent would otherwise read its `flag_evaluates_to` condition as a non-match.
+Instead, when a flag fails earlier in the request, for example because the persons database fetch failed, the dependent compares two answers: the answer it would give if the failed flag matched, and the answer from its other conditions.
+A filter on the failed flag passes, and the other filters and the rollout of its condition still apply, so that condition can still be a definite non-match.
+A condition is also a definite non-match when no single value of the failed flag satisfies all its filters on that flag, for example `true` together with `false`.
+If that condition matches, its variant is the first answer.
+With `early_exit`, the condition can instead stop on its rollout, and then the first answer is no match.
+The dependent returns `failed: true` with the `dependency_failed` reason when the two answers differ, and its normal value when they agree.
+An SDK can then tell the error apart from a configured `false`.
+The two answers agree, for example, when an earlier condition matches, or when a later condition matches with the same variant.
+The check is conservative.
+Two conditions on the same failed flag can fail a dependent even when every value of that flag gives the same answer.
+The failure reaches transitive dependents stage by stage.
+The check runs only after a flag has failed in the request.
+An unsupported non-v1 flag is the exception: it fails, but its dependents read it as false, as described above.
+The batch evaluation endpoint adds a person to the cohort when the target is enabled, and it never reads the variant.
+So it compares the two answers by match only for the target, and for each dependency that only `true` or `false` filters read.
+A failed flag that could change only the variant of one of these flags does not fail it.
+A dependency that an evaluated flag filters on by variant keeps the variant comparison.
+The batch evaluation endpoint retries a target that failed with `dependency_failed` only when every dependency that failed on its own reports a transient code.
+An unsupported non-v1 dependency does not count, because its dependents read it as false.
+
### Partial flag evaluation
When `flag_keys` is provided in the request, the dependency graph is filtered to include only the requested flags and their transitive dependencies. This avoids evaluating unrelated flags.
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index 0815fb820947..a85c246e16cb 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -17,6 +17,9 @@
//! series as live `/flags`, so a large cohort run dominates those on its pod.
//! - The matcher always runs with `skip_writes(true)`: experience-continuity hash key
//! overrides are read but never written.
+//! - The matcher compares dependency answers by match only for the target and for each
+//! dependency that no evaluated flag reads by variant (`enabled_only_flag_keys`), because the
+//! caller reads only the target's `enabled`.
//! - Flags are always read fresh from Postgres (never the hypercache) so the
//! `expected_version` optimistic-lock check is meaningful.
//!
@@ -46,13 +49,16 @@ use tracing::warn;
use uuid::Uuid;
use crate::{
- api::{errors::FlagError, types::FlagsResponse},
+ api::{
+ errors::{FlagError, CODE_DEPENDENCY_FAILED, CODE_FLAG_DATA_PARSING},
+ types::FlagsResponse,
+ },
database::{get_connection_with_metrics, PostgresRouter},
flags::{
cache_builder::compute_flag_dependencies_or_single_stage,
feature_flag_list::PreparedFlags,
flag_matching::FeatureFlagMatcher,
- flag_models::{FeatureFlag, FeatureFlagList},
+ flag_models::{EvaluationMetadata, FeatureFlag, FeatureFlagId, FeatureFlagList},
},
handler::authentication::is_internal_request_inner,
metrics::consts::{
@@ -362,15 +368,63 @@ pub async fn batch_flag_evaluation(
result.map(Json)
}
+/// Keys of the flags the matcher compares by match only: the target, and each of its dependencies
+/// that no evaluated flag reads by variant. A person joins the cohort on the target's `enabled`
+/// alone. A dependency that only `true` or `false` filters read cannot change that through its
+/// variant.
+fn enabled_only_flag_keys(
+ flags: &[FeatureFlag],
+ target_id: FeatureFlagId,
+ evaluation_metadata: &EvaluationMetadata,
+) -> HashSet<String> {
+ let dependency_ids = evaluation_metadata.transitive_deps.get(&target_id);
+ let evaluated: Vec<&FeatureFlag> = flags
+ .iter()
+ .filter(|flag| {
+ flag.id == target_id || dependency_ids.is_some_and(|ids| ids.contains(&flag.id))
+ })
+ .collect();
+ let read_by_variant: HashSet<FeatureFlagId> = evaluated
+ .iter()
+ .flat_map(|flag| flag.filters.flag_ids_read_by_variant())
+ .collect();
+ evaluated
+ .into_iter()
+ .filter(|flag| !read_by_variant.contains(&flag.id))
+ .map(|flag| flag.key.clone())
+ .collect()
+}
+
fn failure_code(result: &Result<FlagsResponse, FlagError>, target_key: &str) -> Option<String> {
- match result {
- Ok(response) => response
+ let response = match result {
+ Ok(response) => response,
+ Err(e) => return Some(e.evaluation_error_code()),
+ };
+ let target = response
+ .flags
+ .get(target_key)
+ .filter(|details| details.failed)?;
+ // `dependency_failed` does not say whether a retry can help, so report the code of a failed
+ // dependency. The request names only the target, so the other flags in the response are its
+ // dependencies. A retry helps only when no dependency failed permanently. Dependents of a flag
+ // with an unsupported format read it as false, so that failure cannot fail the target.
+ if target.reason.code == CODE_DEPENDENCY_FAILED {
+ let root_codes: Vec<&str> = response
.flags
- .get(target_key)
+ .values()
.filter(|details| details.failed)
- .map(|details| details.reason.code.clone()),
- Err(e) => Some(e.evaluation_error_code()),
+ .map(|details| details.reason.code.as_str())
+ .filter(|code| *code != CODE_DEPENDENCY_FAILED && *code != CODE_FLAG_DATA_PARSING)
+ .collect();
+ if let Some(code) = root_codes
+ .iter()
+ .find(|code| !is_transient_failure(code))
+ .or(root_codes.first())
+ {
+ return Some(code.to_string());
+ }
}
+ Some(target.reason.code.clone())
}
/// Whether a failure code comes from a transient database fault or a timeout, which a second
@@ -526,6 +580,8 @@ async fn handle_batch_flag_evaluation(
let evaluation_metadata =
compute_flag_dependencies_or_single_stage(request.team_id, &flags_vec);
+ let enabled_only_flag_keys =
+ enabled_only_flag_keys(&flags_vec, flags_vec[target_index].id, &evaluation_metadata);
let flag_list = FeatureFlagList {
flags: PreparedFlags::seal(flags_vec),
@@ -599,6 +655,7 @@ async fn handle_batch_flag_evaluation(
.with_parallel_eval_threshold(state.config.parallel_eval_threshold)
// Read-only: experience-continuity overrides are consulted but never written.
.with_skip_writes(true)
+ .with_enabled_only_flag_keys(enabled_only_flag_keys.clone())
.with_timezone(team_timezone);
let flag_list = flag_list.clone();
@@ -675,6 +732,7 @@ mod tests {
use super::*;
use crate::api::types::{FlagDetails, FromFeatureAndMatch};
use crate::config::DEFAULT_TEST_CONFIG;
+ use crate::flags::config_format::decode_filters;
use crate::flags::flag_match_reason::FeatureFlagMatchReason;
use crate::flags::flag_matching::FeatureFlagMatch;
use crate::mock;
@@ -682,10 +740,40 @@ mod tests {
use crate::utils::test_utils::{counter_total, TestContext};
use common_database::{get_pool_with_config, PoolConfig};
use metrics_util::debugging::DebuggingRecorder;
+ use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
+ #[test]
+ fn enabled_only_flag_keys_skip_dependencies_read_by_variant() {
+ let flag = |id: i32, key: &str, properties: Value| {
+ mock!(FeatureFlag,
+ id: id,
+ key: key.to_string(),
+ filters: decode_filters(json!({"groups": [{"properties": properties}]})).unwrap()
+ )
+ };
+ let reads = |flag_id: i32, value: Value| json!({"key": flag_id.to_string(), "type": "flag", "value": value, "operator": "flag_evaluates_to"});
+ let flags = vec![
+ flag(1, "failed", json!([])),
+ flag(2, "read_by_match", json!([reads(1, json!(true))])),
+ flag(3, "read_by_variant", json!([reads(1, json!(true))])),
+ flag(
+ 4,
+ "target",
+ json!([reads(2, json!(true)), reads(3, json!("control"))]),
+ ),
+ flag(5, "unrelated", json!([])),
+ ];
+ let metadata = compute_flag_dependencies_or_single_stage(1, &flags);
+
+ assert_eq!(
+ enabled_only_flag_keys(&flags, 4, &metadata),
+ HashSet::from(["failed", "read_by_match", "target"].map(String::from))
+ );
+ }
+
fn target_flag_response(details: FlagDetails) -> Result<FlagsResponse, FlagError> {
Ok(FlagsResponse::new(
false,
@@ -700,6 +788,35 @@ mod tests {
target_flag_response(FlagDetails::create_error(&flag, &error, None))
}
+ fn target_with_failed_dependencies(errors: &[FlagError]) -> Result<FlagsResponse, FlagError> {
+ let target = mock!(FeatureFlag, key: "target".to_string());
+ let mut flags = HashMap::from([(
+ "target".to_string(),
+ FlagDetails::create_error(&target, &FlagError::DependencyFailed(2), None),
+ )]);
+ for (dependency_id, error) in (2..).zip(errors) {
+ let key = format!("dependency_{dependency_id}");
+ let dependency = mock!(FeatureFlag, id: dependency_id, key: key.clone());
+ flags.insert(key, FlagDetails::create_error(&dependency, error, None));
+ }
+ let healthy = mock!(FeatureFlag, id: 99, key: "healthy_dependency".to_string());
+ flags.insert(
+ "healthy_dependency".to_string(),
+ FlagDetails::create(
+ &healthy,
+ &FeatureFlagMatch {
+ matches: false,
+ variant: None,
+ reason: FeatureFlagMatchReason::NoConditionMatch,
+ condition_index: None,
+ payload: None,
+ evaluation_v2: None,
+ },
+ ),
+ );
+ Ok(FlagsResponse::new(true, flags, None, Uuid::nil()))
+ }
+
fn evaluated() -> Result<FlagsResponse, FlagError> {
let flag = mock!(FeatureFlag, key: "target".to_string());
target_flag_response(FlagDetails::create(
@@ -742,13 +859,47 @@ mod tests {
false,
Some("recovered")
)]
- #[case::dependency_failed_flag(
+ #[case::missing_dependency_flag(
|| failed_target_flag(FlagError::DependencyNotFound(DependencyType::Cohort, 1)),
evaluated,
1,
true,
None
)]
+ #[case::transient_failure_in_dependency(
+ || target_with_failed_dependencies(&[FlagError::TimeoutError(Some("pool_timeout".to_string()))]),
+ evaluated,
+ 1,
+ false,
+ Some("recovered")
+ )]
+ #[case::permanent_failure_in_dependency(
+ || target_with_failed_dependencies(&[FlagError::DependencyNotFound(DependencyType::Cohort, 1)]),
+ evaluated,
+ 1,
+ true,
+ None
+ )]
+ #[case::transient_and_permanent_failures_in_dependencies(
+ || target_with_failed_dependencies(&[
+ FlagError::TimeoutError(Some("pool_timeout".to_string())),
+ FlagError::DependencyNotFound(DependencyType::Cohort, 1),
+ ]),
+ evaluated,
+ 1,
+ true,
+ None
+ )]
+ #[case::transient_failure_beside_unsupported_dependency(
+ || target_with_failed_dependencies(&[
+ FlagError::TimeoutError(Some("pool_timeout".to_string())),
+ FlagError::flag_data_parsing("unsupported feature flag configuration format"),
+ ]),
+ evaluated,
+ 1,
+ false,
+ Some("recovered")
+ )]
#[case::database_error(
|| Err(FlagError::DatabaseError(sqlx::Error::ColumnNotFound("id".to_string()), None)),
evaluated,
diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rs
index 828a3b8b12b8..a411faf6cc9f 100644
--- a/rust/feature-flags/src/api/errors.rs
+++ b/rust/feature-flags/src/api/errors.rs
@@ -115,6 +115,8 @@ pub enum FlagError {
TimeoutError(Option<String>),
#[error("Dependency of type {0} with id {1} not found")]
DependencyNotFound(DependencyType, i64),
+ #[error("Flag dependency {0} failed to evaluate")]
+ DependencyFailed(i64),
#[error("Failed to parse cohort filters")]
CohortFiltersParsingError,
#[error("Dependency cycle detected: {0} id {1} starts the cycle")]
@@ -130,11 +132,12 @@ pub enum FlagError {
RemoteConfigDecryptFailed(String),
}
-/// Codes that `IntoResponse` branches on, so the constructor and the arm cannot
-/// drift apart. The codes used at one site only stay inline: a single literal has
-/// no second reference to disagree with.
+/// Codes that more than one site compares against, so the constructor and each
+/// comparison cannot drift apart. The codes used at one site only stay inline: a
+/// single literal has no second reference to disagree with.
pub(crate) const CODE_FLAG_DATA_PARSING: &str = "flag_data_parsing_error";
pub(crate) const CODE_PERSON_NOT_FOUND: &str = "person_not_found";
+pub(crate) const CODE_DEPENDENCY_FAILED: &str = "dependency_failed";
impl FlagError {
/// The `Internal error: ` prefix reaches customers as the `$feature_flag_reason`
@@ -242,6 +245,7 @@ impl FlagError {
FlagError::DatabaseError(_, _) => ("database_error", 500),
FlagError::RowNotFound => ("row_not_found", 500),
FlagError::DependencyNotFound(_, _) => ("dependency_not_found", 500),
+ FlagError::DependencyFailed(_) => (CODE_DEPENDENCY_FAILED, 500),
FlagError::CohortFiltersParsingError => ("cohort_filters_parsing_error", 500),
FlagError::DependencyCycle(_, _) => ("dependency_cycle", 500),
FlagError::HashKeyOverrideError => ("hash_key_override_error", 500),
@@ -357,6 +361,7 @@ impl FlagError {
DependencyType::Cohort => "Cohort dependency not found".to_string(),
DependencyType::Flag => "Flag dependency not found".to_string(),
},
+ FlagError::DependencyFailed(_) => "Flag dependency failed to evaluate".to_string(),
FlagError::DependencyCycle(dependency_type, _) => match dependency_type {
DependencyType::Cohort => "Cohort dependency cycle detected".to_string(),
DependencyType::Flag => "Flag dependency cycle detected".to_string(),
@@ -537,6 +542,10 @@ impl IntoResponse for FlagError {
tracing::error!("Dependency of type {dependency_type} with id {dependency_id} not found");
(StatusCode::INTERNAL_SERVER_ERROR, format!("Dependency of type {dependency_type} with id {dependency_id} not found"))
}
+ FlagError::DependencyFailed(dependency_id) => {
+ tracing::error!("Flag dependency {dependency_id} failed to evaluate");
+ (StatusCode::INTERNAL_SERVER_ERROR, format!("Flag dependency {dependency_id} failed to evaluate"))
+ }
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())
@@ -1067,6 +1076,7 @@ mod tests {
FlagError::DatabaseError(sqlx::Error::RowNotFound, Some("test context".to_string())),
FlagError::TimeoutError(None),
FlagError::DependencyNotFound(DependencyType::Flag, 1),
+ FlagError::DependencyFailed(2),
FlagError::DependencyCycle(DependencyType::Cohort, 2),
FlagError::CohortFiltersParsingError,
FlagError::person_not_found(),
@@ -1179,6 +1189,7 @@ mod tests {
FlagError::DatabaseError(sqlx::Error::RowNotFound, None),
FlagError::RowNotFound,
FlagError::DependencyNotFound(DependencyType::Flag, 1),
+ FlagError::DependencyFailed(2),
FlagError::CohortFiltersParsingError,
FlagError::DependencyCycle(DependencyType::Cohort, 2),
FlagError::data_parsing(anyhow::anyhow!("bad payload")),
@@ -1294,6 +1305,7 @@ mod tests {
FlagError::DatabaseError(sqlx::Error::RowNotFound, Some("test context".to_string())),
FlagError::TimeoutError(None),
FlagError::DependencyNotFound(DependencyType::Flag, 1),
+ FlagError::DependencyFailed(2),
FlagError::DependencyCycle(DependencyType::Cohort, 2),
FlagError::CohortFiltersParsingError,
FlagError::person_not_found(),
diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index c72e820c0a73..fff7a1845eeb 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -194,7 +194,10 @@ pub fn extract_cohort_ids_from_flag_filters(flags: &[FeatureFlag]) -> HashSet<Co
///
/// `compute_flag_dependencies` returns no error for flag input, because `remove_all_cycles`
/// removes every cycle before the stage computation runs. The fallback guards against a later
-/// change to the graph code.
+/// change to the graph code. In one stage, a dependent can evaluate before its dependency. It
+/// also does not see a failure raised during that stage. In both cases its `flag_evaluates_to`
+/// condition reads as a non-match. A dependency that failed before evaluation, such as in
+/// persons DB preparation, still fails its dependents with `dependency_failed`.
pub(crate) fn compute_flag_dependencies_or_single_stage(
team_id: TeamId,
flags: &[FeatureFlag],
diff --git a/rust/feature-flags/src/flags/flag_filters.rs b/rust/feature-flags/src/flags/flag_filters.rs
index 4af6e1db03ef..cf456712f36a 100644
--- a/rust/feature-flags/src/flags/flag_filters.rs
+++ b/rust/feature-flags/src/flags/flag_filters.rs
@@ -56,6 +56,22 @@ impl FlagFilters {
requirements
}
+ /// Flag IDs whose variant this config reads. A v1 `flag_evaluates_to` filter with a string
+ /// value reads the variant, and a `true` or `false` value reads only whether the flag
+ /// matched. Every v2 flag reference counts, because this method does not inspect v2
+ /// predicate values.
+ pub fn flag_ids_read_by_variant(&self) -> Vec<FeatureFlagId> {
+ if !self.is_v1() {
+ return self.requirements().flag_ids;
+ }
+ self.groups
+ .iter()
+ .flat_map(|group| group.properties.iter().flatten())
+ .filter(|property| matches!(property.value, Some(Value::String(_))))
+ .filter_map(|property| property.get_feature_flag_id())
+ .collect()
+ }
+
/// Returns the person property key used for early access feature enrollment.
pub fn enrollment_key(flag_key: &str) -> String {
format!("$feature_enrollment/{}", flag_key)
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index 039fe25191e4..fc6ff61462e8 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -40,7 +40,7 @@ use crate::metrics::consts::{
PROPERTY_CACHE_HITS_COUNTER, PROPERTY_CACHE_MISSES_COUNTER,
};
use crate::properties::property_matching::{match_property, PropertyMatchingContext};
-use crate::properties::property_models::{PropertyFilter, PropertyType};
+use crate::properties::property_models::{OperatorType, PropertyFilter, PropertyType};
use crate::rayon_dispatcher::RayonDispatcher;
use crate::utils::graph_utils::PrecomputedDependencyGraph;
use anyhow::Result;
@@ -208,6 +208,7 @@ pub struct FlagEvaluationState {
cohort_matches: Option<HashMap<CohortId, bool>>,
/// Cache of flag evaluation results to avoid repeated DB lookups
flag_evaluation_results: HashMap<FeatureFlagId, FlagValue>,
+ failed_flag_ids: HashSet<FeatureFlagId>,
}
impl FlagEvaluationState {
@@ -299,6 +300,77 @@ impl FlagEvaluationState {
pub fn add_flag_evaluation_result(&mut self, flag_id: FeatureFlagId, flag_value: FlagValue) {
self.flag_evaluation_results.insert(flag_id, flag_value);
}
+
+ /// Returns the flag this filter depends on when that flag failed earlier in this request.
+ /// A flag with a recorded result never counts. An unsupported flag fails, but it is
+ /// pre-seeded `false`, so its dependents still read it as false. A malformed filter never
+ /// counts either, because `match_flag_value_to_flag_filter` rejects it for every value.
+ fn failed_dependency(&self, filter: &PropertyFilter) -> Option<FeatureFlagId> {
+ if self.failed_flag_ids.is_empty()
+ || filter.operator != Some(OperatorType::FlagEvaluatesTo)
+ || !matches!(filter.value, Some(Value::Bool(_) | Value::String(_)))
+ {
+ return None;
+ }
+ let flag_id = filter.get_feature_flag_id()?;
+ (!self.flag_evaluation_results.contains_key(&flag_id)
+ && self.failed_flag_ids.contains(&flag_id))
+ .then_some(flag_id)
+ }
+
+ /// Returns true when no single value of some failed flag satisfies all of the filters on that
+ /// flag, for example `true` together with `false`, or two different variants.
+ /// `is_condition_match` passes each filter on a failed flag on its own. This check finds the
+ /// conflict that those separate passes miss.
+ fn failed_dependency_filters_conflict(&self, filters: &[PropertyFilter]) -> bool {
+ let mut filters_by_flag: HashMap<FeatureFlagId, Vec<&PropertyFilter>> = HashMap::new();
+ for filter in filters {
+ if let Some(flag_id) = self.failed_dependency(filter) {
+ filters_by_flag.entry(flag_id).or_default().push(filter);
+ }
+ }
+ filters_by_flag
+ .into_iter()
+ .any(|(flag_id, filters_on_flag)| {
+ if filters_on_flag.len() < 2 {
+ return false;
+ }
+ let variants = filters_on_flag
+ .iter()
+ .filter_map(|filter| match &filter.value {
+ Some(Value::String(variant)) => Some(FlagValue::String(variant.clone())),
+ _ => None,
+ });
+ // A variant that no filter names passes the same filters as `true`.
+ let can_match = [FlagValue::Boolean(false), FlagValue::Boolean(true)]
+ .into_iter()
+ .chain(variants)
+ .any(|value| {
+ let results = HashMap::from([(flag_id, value)]);
+ filters_on_flag
+ .iter()
+ .all(|filter| match_flag_value_to_flag_filter(filter, &results))
+ });
+ !can_match
+ })
+ }
+}
+
+#[derive(Debug, PartialEq)]
+enum ConditionAnswer {
+ Match(Option<String>),
+ NoMatch,
+}
+
+impl ConditionAnswer {
+ fn is_match(&self) -> bool {
+ matches!(self, ConditionAnswer::Match(_))
+ }
+}
+
+struct AnswerIfDependencyMatched {
+ failed_dependency: FeatureFlagId,
+ answer: ConditionAnswer,
}
static EMPTY_PROPERTY_MAP: std::sync::LazyLock<HashMap<String, Value>> =
@@ -387,6 +459,10 @@ pub struct FeatureFlagMatcher {
rayon_dispatcher: Option<RayonDispatcher>,
/// When true, skip all writes to PostgreSQL and Redis.
skip_writes: bool,
+ /// Keys of flags whose variant neither the caller nor any evaluated flag reads. A failed
+ /// dependency fails one of these flags only when it could change whether the flag matches.
+ /// Every other flag keeps the variant comparison.
+ enabled_only_flag_keys: HashSet<String>,
/// Flag IDs that should be skipped during evaluation.
/// Populated once per request from `FeatureFlagList::filtered_out_flag_ids`.
pub(crate) filtered_out_flag_ids: HashSet<i32>,
@@ -453,6 +529,14 @@ fn merge_distinct_id_into_person_properties(
overrides
}
+fn ids_of_failed_flags<'a>(
+ details: impl Iterator<Item = &'a FlagDetails> + 'a,
+) -> impl Iterator<Item = FeatureFlagId> + 'a {
+ details
+ .filter(|details| details.failed)
+ .map(|details| details.metadata.id)
+}
+
impl FeatureFlagMatcher {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -478,6 +562,7 @@ impl FeatureFlagMatcher {
parallel_eval_threshold: DEFAULT_PARALLEL_EVAL_THRESHOLD,
rayon_dispatcher: None,
skip_writes: false,
+ enabled_only_flag_keys: HashSet::new(),
filtered_out_flag_ids: HashSet::new(),
enable_realtime_cohort_evaluation: false,
use_explicit_exact_matching: false,
@@ -518,6 +603,11 @@ impl FeatureFlagMatcher {
self
}
+ pub fn with_enabled_only_flag_keys(mut self, flag_keys: HashSet<String>) -> Self {
+ self.enabled_only_flag_keys = flag_keys;
+ self
+ }
+
pub fn with_cohort_membership_provider(
mut self,
provider: Arc<dyn CohortMembershipProvider>,
@@ -1049,6 +1139,8 @@ impl FeatureFlagMatcher {
}
// Step 3: Evaluate flags stage by stage in dependency order
+ self.flag_evaluation_state.failed_flag_ids =
+ ids_of_failed_flags(evaluated_flags_map.values()).collect();
for stage in evaluation_stages {
let (level_evaluated_flags_map, level_errors) = self
.evaluate_flags_in_level(
@@ -1062,6 +1154,11 @@ impl FeatureFlagMatcher {
)
.await?;
errors_while_computing_flags |= level_errors;
+ if level_errors {
+ self.flag_evaluation_state
+ .failed_flag_ids
+ .extend(ids_of_failed_flags(level_evaluated_flags_map.values()));
+ }
evaluated_flags_map.extend(level_evaluated_flags_map);
}
@@ -1310,16 +1407,20 @@ impl FeatureFlagMatcher {
*errors_while_computing_flags = true;
with_canonical_log(|log| log.flags_errored += 1);
- if let FlagError::DependencyNotFound(dependency_type, dependency_id) = e {
- warn!(
+ match e {
+ FlagError::DependencyNotFound(dependency_type, dependency_id) => warn!(
"Feature flag '{}' targeting deleted {} with id {} for distinct_id '{}': {:?}",
flag.key, dependency_type, dependency_id, self.distinct_id, e
- );
- } else {
- error!(
+ ),
+ // The failed dependency already logged its own error.
+ FlagError::DependencyFailed(dependency_id) => debug!(
+ "Feature flag '{}' failed because dependency {} failed",
+ flag.key, dependency_id
+ ),
+ _ => error!(
"Error evaluating feature flag '{}' for distinct_id '{}': {:?}",
flag.key, self.distinct_id, e
- );
+ ),
}
let reason = e.evaluation_error_code();
@@ -1609,6 +1710,12 @@ impl FeatureFlagMatcher {
flag.get_conditions().iter().enumerate().collect();
let early_exit_enabled = flag.filters.early_exit.unwrap_or(false);
+ // A condition on a failed flag cannot settle the answer. Each such condition records the
+ // answer the flag would give if the failed flag matched it. The flag fails only when one
+ // of those answers differs from the answer from its other conditions. Server SDKs read
+ // `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();
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
@@ -1742,6 +1849,12 @@ impl FeatureFlagMatcher {
had_unevaluable_cohort_conditions = true;
}
+ let failed_dependency = condition
+ .properties
+ .iter()
+ .flatten()
+ .find_map(|filter| self.flag_evaluation_state.failed_dependency(filter));
+
// OutOfRolloutBound means the condition's property filters (if any) already
// matched and only the rollout check failed, so re-evaluating later groups
// can't change the outcome.
@@ -1749,14 +1862,47 @@ impl FeatureFlagMatcher {
&& !is_match
&& reason == FeatureFlagMatchReason::OutOfRolloutBound
{
- return Ok(FeatureFlagMatch {
- matches: false,
- variant: None,
- reason: FeatureFlagMatchReason::OutOfRolloutBound,
- condition_index: Some(index),
- payload: None,
- evaluation_v2: None,
- });
+ // If the failed flag matched, the flag would stop here with no match.
+ // Otherwise the later conditions decide.
+ if let Some(failed_dependency) = failed_dependency {
+ answers_if_dependency_matched.push(AnswerIfDependencyMatched {
+ failed_dependency,
+ answer: ConditionAnswer::NoMatch,
+ });
+ } else {
+ if let Some(dependency) = self.dependency_that_changes_answer(
+ flag,
+ &answers_if_dependency_matched,
+ &ConditionAnswer::NoMatch,
+ ) {
+ return Err(FlagError::DependencyFailed(dependency.into()));
+ }
+ return Ok(FeatureFlagMatch {
+ matches: false,
+ variant: None,
+ reason: FeatureFlagMatchReason::OutOfRolloutBound,
+ condition_index: Some(index),
+ payload: None,
+ evaluation_v2: None,
+ });
+ }
+ }
+
+ if is_match {
+ if let Some(failed_dependency) = failed_dependency {
+ let variant = self.condition_variant(
+ flag,
+ condition,
+ aggregation,
+ hash_key_overrides,
+ request_hash_key_override,
+ )?;
+ answers_if_dependency_matched.push(AnswerIfDependencyMatched {
+ failed_dependency,
+ answer: ConditionAnswer::Match(variant),
+ });
+ continue;
+ }
}
// Update highest_match and highest_index
@@ -1771,15 +1917,22 @@ impl FeatureFlagMatcher {
highest_index = new_highest_index;
if is_match {
- let variant = match flag.pinned_variant(condition) {
- Some(pinned) => Some(pinned.to_string()),
- None => self.get_matching_variant(
+ let variant = self.condition_variant(
+ flag,
+ condition,
+ aggregation,
+ hash_key_overrides,
+ request_hash_key_override,
+ )?;
+ if !answers_if_dependency_matched.is_empty() {
+ if let Some(dependency) = self.dependency_that_changes_answer(
flag,
- aggregation,
- hash_key_overrides,
- request_hash_key_override,
- )?,
- };
+ &answers_if_dependency_matched,
+ &ConditionAnswer::Match(variant.clone()),
+ ) {
+ return Err(FlagError::DependencyFailed(dependency.into()));
+ }
+ }
let payload = self.get_matching_payload(variant.as_deref(), flag);
return Ok(FeatureFlagMatch {
@@ -1793,6 +1946,14 @@ impl FeatureFlagMatcher {
}
}
+ if let Some(dependency) = self.dependency_that_changes_answer(
+ flag,
+ &answers_if_dependency_matched,
+ &ConditionAnswer::NoMatch,
+ ) {
+ return Err(FlagError::DependencyFailed(dependency.into()));
+ }
+
condition_timer.label("outcome", "success").fin();
// When person conditions were evaluated (and didn't match) but group conditions
@@ -1884,6 +2045,25 @@ impl FeatureFlagMatcher {
})
}
+ fn dependency_that_changes_answer(
+ &self,
+ flag: &FeatureFlag,
+ answers_if_dependency_matched: &[AnswerIfDependencyMatched],
+ answer: &ConditionAnswer,
+ ) -> Option<FeatureFlagId> {
+ let compare_variants = !self.enabled_only_flag_keys.contains(&flag.key);
+ answers_if_dependency_matched
+ .iter()
+ .find(|candidate| {
+ if compare_variants {
+ candidate.answer != *answer
+ } else {
+ candidate.answer.is_match() != answer.is_match()
+ }
+ })
+ .map(|candidate| candidate.failed_dependency)
+ }
+
/// 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.
@@ -1934,12 +2114,30 @@ impl FeatureFlagMatcher {
);
}
+ if self
+ .flag_evaluation_state
+ .failed_dependency_filters_conflict(flag_property_filters)
+ {
+ return Ok((false, FeatureFlagMatchReason::NoConditionMatch));
+ }
+
// Single-pass evaluation: flag-value and property filters are evaluated in Vec order
// and short-circuit immediately on mismatch. Cohort filters (the most expensive)
// are deferred and batch-evaluated after the loop to avoid unnecessary work.
let mut cohort_filters: Vec<&PropertyFilter> = Vec::new();
for filter in flag_property_filters {
if filter.depends_on_feature_flag() {
+ // A filter on a flag that failed earlier in this request passes here, so the
+ // other filters and the rollout still decide whether the condition can
+ // match. `get_match` uses such a match only as the answer the flag would give
+ // if the failed flag matched.
+ if self
+ .flag_evaluation_state
+ .failed_dependency(filter)
+ .is_some()
+ {
+ continue;
+ }
if !match_flag_value_to_flag_filter(
filter,
&self.flag_evaluation_state.flag_evaluation_results,
@@ -2436,6 +2634,25 @@ impl FeatureFlagMatcher {
}
}
+ fn condition_variant(
+ &self,
+ flag: &FeatureFlag,
+ condition: &FlagPropertyGroup,
+ aggregation: Option<i32>,
+ hash_key_overrides: Option<&HashMap<String, String>>,
+ request_hash_key_override: &Option<String>,
+ ) -> Result<Option<String>, FlagError> {
+ match flag.pinned_variant(condition) {
+ Some(pinned) => Ok(Some(pinned.to_string())),
+ None => self.get_matching_variant(
+ flag,
+ aggregation,
+ hash_key_overrides,
+ request_hash_key_override,
+ ),
+ }
+ }
+
/// Returns the variant key for this flag based on the hashed identifier.
/// The aggregation determines which identifier is hashed (group key vs distinct_id).
pub(crate) fn get_matching_variant(
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index 40c76838ccd8..be2f9ea3f274 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -16,6 +16,7 @@ mod tests {
cohort_models::{Cohort, CohortId, CohortType, MembershipStampPolicy},
membership::{CohortMembershipError, CohortMembershipProvider},
},
+ database::PostgresRouter,
flags::{
feature_flag_list::PreparedFlags,
flag_group_type_mapping::{GroupTypeCacheManager, GroupTypeMapping},
@@ -37,7 +38,7 @@ mod tests {
mock::MockInto,
test_utils::{
failing_group_type_cache, flag_list_with_metadata, mock_group_type_cache,
- TestContext,
+ setup_invalid_pg_client, TestContext,
},
},
};
@@ -1341,6 +1342,332 @@ mod tests {
}
}
+ #[rstest::rstest]
+ #[case::flags_endpoint(false)]
+ #[case::batch_endpoint(true)]
+ #[tokio::test]
+ async fn test_flags_depending_on_a_failed_flag_fail_only_when_their_answer_needs_it(
+ #[case] batch_endpoint: bool,
+ ) {
+ let enabled_only_flag_keys = if batch_endpoint {
+ HashSet::from(
+ [
+ "dependent_with_pinned_variant_flag",
+ "dependent_on_pinned_variant_dependency_flag",
+ ]
+ .map(String::from),
+ )
+ } else {
+ HashSet::new()
+ };
+ let failing_db = setup_invalid_pg_client().await;
+ let router = PostgresRouter::new(
+ failing_db.clone(),
+ failing_db.clone(),
+ failing_db.clone(),
+ failing_db.clone(),
+ );
+ let mut matcher = FeatureFlagMatcher::new(
+ "test_user".to_string(),
+ None,
+ 1,
+ router,
+ Arc::new(CohortCacheManager::new(failing_db, None, None)),
+ empty_group_type_cache(),
+ None,
+ )
+ .with_enabled_only_flag_keys(enabled_only_flag_keys);
+
+ let rollout_flag = mock!(FeatureFlag, id: 1, key: "rollout_flag".mock_into());
+ let person_flag = mock!(FeatureFlag,
+ id: 2,
+ key: "person_flag".mock_into(),
+ filters: mock!(PropertyFilter,
+ key: "email".mock_into(),
+ value: Some(json!("[email protected]")),
+ prop_type: PropertyType::Person
+ ).mock_into()
+ );
+ let dependent_flag = mock!(FeatureFlag,
+ id: 3,
+ key: "dependent_flag".mock_into(),
+ filters: dep_filter(person_flag.id, FlagValue::Boolean(true)).mock_into()
+ );
+ let dependent_with_catch_all_flag = mock!(FeatureFlag,
+ id: 4,
+ key: "dependent_with_catch_all_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(false))])
+ ),
+ mock!(FlagPropertyGroup),
+ ]
+ )
+ );
+ let transitive_dependent_flag = mock!(FeatureFlag,
+ id: 5,
+ key: "transitive_dependent_flag".mock_into(),
+ filters: dep_filter(dependent_flag.id, FlagValue::Boolean(false)).mock_into()
+ );
+ let healthy_dependent_flag = mock!(FeatureFlag,
+ id: 6,
+ key: "healthy_dependent_flag".mock_into(),
+ filters: dep_filter(rollout_flag.id, FlagValue::Boolean(true)).mock_into()
+ );
+ let catch_all_before_dependency_flag = mock!(FeatureFlag,
+ id: 7,
+ key: "catch_all_before_dependency_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![
+ mock!(FlagPropertyGroup),
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))])
+ ),
+ ]
+ )
+ );
+ let dependent_out_of_rollout_flag = mock!(FeatureFlag,
+ id: 8,
+ key: "dependent_out_of_rollout_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))]),
+ rollout_percentage: Some(0.0)
+ )]
+ )
+ );
+ // Every user hashes to "control", so an unpinned condition never returns "test".
+ let control_for_everyone = || MultivariateFlagOptions {
+ variants: vec![
+ MultivariateFlagVariant {
+ key: "control".to_string(),
+ rollout_percentage: 100.0,
+ ..Default::default()
+ },
+ MultivariateFlagVariant {
+ key: "test".to_string(),
+ rollout_percentage: 0.0,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ };
+ let pinned_test_then_control = || {
+ mock!(FlagFilters,
+ groups: vec![
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))]),
+ variant: Some("test".to_string())
+ ),
+ mock!(FlagPropertyGroup),
+ ],
+ multivariate: Some(control_for_everyone())
+ )
+ };
+ let dependent_with_pinned_variant_flag = mock!(FeatureFlag,
+ id: 9,
+ key: "dependent_with_pinned_variant_flag".mock_into(),
+ filters: pinned_test_then_control()
+ );
+ let pinned_variant_dependency_flag = mock!(FeatureFlag,
+ id: 17,
+ key: "pinned_variant_dependency_flag".mock_into(),
+ filters: pinned_test_then_control()
+ );
+ let dependent_on_pinned_variant_dependency_flag = mock!(FeatureFlag,
+ id: 18,
+ key: "dependent_on_pinned_variant_dependency_flag".mock_into(),
+ filters: dep_filter(pinned_variant_dependency_flag.id, FlagValue::String("control".to_string())).mock_into()
+ );
+ let dependent_with_same_pinned_variant_flag = mock!(FeatureFlag,
+ id: 11,
+ key: "dependent_with_same_pinned_variant_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))]),
+ variant: Some("test".to_string())
+ ),
+ mock!(FlagPropertyGroup, variant: Some("test".to_string())),
+ ],
+ multivariate: Some(control_for_everyone())
+ )
+ );
+ let dependent_stopping_early_flag = mock!(FeatureFlag,
+ id: 12,
+ key: "dependent_stopping_early_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))]),
+ rollout_percentage: Some(0.0)
+ ),
+ mock!(FlagPropertyGroup),
+ ],
+ early_exit: Some(true)
+ )
+ );
+ let dependent_stopping_early_without_later_match_flag = mock!(FeatureFlag,
+ id: 13,
+ key: "dependent_stopping_early_without_later_match_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))]),
+ rollout_percentage: Some(0.0)
+ )],
+ early_exit: Some(true)
+ )
+ );
+ let dependent_with_early_exit_flag = mock!(FeatureFlag,
+ id: 10,
+ key: "dependent_with_early_exit_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))])
+ ),
+ mock!(FlagPropertyGroup, rollout_percentage: Some(0.0)),
+ ],
+ early_exit: Some(true)
+ )
+ );
+ let dependent_on_variant_flag = mock!(FeatureFlag,
+ id: 14,
+ key: "dependent_on_variant_flag".mock_into(),
+ filters: dep_filter(person_flag.id, FlagValue::String("test".to_string())).mock_into()
+ );
+ let dependent_with_hashed_variant_flag = mock!(FeatureFlag,
+ id: 15,
+ key: "dependent_with_hashed_variant_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![
+ mock!(FlagPropertyGroup,
+ properties: Some(vec![dep_filter(person_flag.id, FlagValue::Boolean(true))])
+ ),
+ mock!(FlagPropertyGroup, variant: Some("control".to_string())),
+ ],
+ multivariate: Some(control_for_everyone())
+ )
+ );
+ let dependent_with_conflicting_filters_flag = mock!(FeatureFlag,
+ id: 16,
+ key: "dependent_with_conflicting_filters_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![mock!(FlagPropertyGroup,
+ properties: Some(vec![
+ dep_filter(person_flag.id, FlagValue::Boolean(true)),
+ dep_filter(person_flag.id, FlagValue::Boolean(false)),
+ ])
+ )]
+ )
+ );
+ let dependent_on_flag_and_its_variant_flag = mock!(FeatureFlag,
+ id: 19,
+ key: "dependent_on_flag_and_its_variant_flag".mock_into(),
+ filters: mock!(FlagFilters,
+ groups: vec![mock!(FlagPropertyGroup,
+ properties: Some(vec![
+ dep_filter(person_flag.id, FlagValue::Boolean(true)),
+ dep_filter(person_flag.id, FlagValue::String("test".to_string())),
+ ])
+ )]
+ )
+ );
+ let mut flags = flag_list_with_metadata(vec![
+ rollout_flag,
+ person_flag,
+ dependent_flag,
+ dependent_with_catch_all_flag,
+ transitive_dependent_flag,
+ healthy_dependent_flag,
+ catch_all_before_dependency_flag,
+ dependent_out_of_rollout_flag,
+ dependent_with_pinned_variant_flag,
+ dependent_with_early_exit_flag,
+ dependent_with_same_pinned_variant_flag,
+ dependent_stopping_early_flag,
+ dependent_stopping_early_without_later_match_flag,
+ dependent_on_variant_flag,
+ dependent_with_hashed_variant_flag,
+ dependent_with_conflicting_filters_flag,
+ pinned_variant_dependency_flag,
+ dependent_on_pinned_variant_dependency_flag,
+ dependent_on_flag_and_its_variant_flag,
+ ]);
+ // Preloaded cohorts keep the cohort definitions lookup off the failing pool.
+ flags.cohorts = Some(Arc::from(Vec::new()));
+
+ let result = matcher
+ .evaluate_all_feature_flags(flags, None, None, None, Uuid::new_v4(), None, false)
+ .await
+ .unwrap();
+
+ let mut settled = vec![
+ ("rollout_flag", FlagValue::Boolean(true)),
+ ("healthy_dependent_flag", FlagValue::Boolean(true)),
+ ("dependent_with_catch_all_flag", FlagValue::Boolean(true)),
+ ("catch_all_before_dependency_flag", FlagValue::Boolean(true)),
+ ("dependent_out_of_rollout_flag", FlagValue::Boolean(false)),
+ (
+ "dependent_with_same_pinned_variant_flag",
+ FlagValue::String("test".to_string()),
+ ),
+ (
+ "dependent_stopping_early_without_later_match_flag",
+ FlagValue::Boolean(false),
+ ),
+ (
+ "dependent_with_hashed_variant_flag",
+ FlagValue::String("control".to_string()),
+ ),
+ (
+ "dependent_with_conflicting_filters_flag",
+ FlagValue::Boolean(false),
+ ),
+ ];
+ let mut failed = vec![
+ "dependent_flag",
+ "transitive_dependent_flag",
+ "dependent_with_early_exit_flag",
+ "dependent_stopping_early_flag",
+ "dependent_on_variant_flag",
+ "pinned_variant_dependency_flag",
+ "dependent_on_pinned_variant_dependency_flag",
+ "dependent_on_flag_and_its_variant_flag",
+ ];
+ if batch_endpoint {
+ settled.push((
+ "dependent_with_pinned_variant_flag",
+ FlagValue::String("control".to_string()),
+ ));
+ } else {
+ failed.push("dependent_with_pinned_variant_flag");
+ }
+
+ assert!(result.errors_while_computing_flags);
+ for (key, value) in settled {
+ assert!(!result.flags[key].failed, "{key}");
+ assert_eq!(result.flags[key].to_value(), value, "{key}");
+ }
+ let stopped_early = &result.flags["dependent_stopping_early_without_later_match_flag"];
+ assert_eq!(stopped_early.reason.code, "out_of_rollout_bound");
+ assert_eq!(stopped_early.reason.condition_index, Some(0));
+ assert_eq!(
+ result.flags["person_flag"].reason.code,
+ "timeout:pool_timeout"
+ );
+ for key in failed {
+ let details = &result.flags[key];
+ assert!(
+ details.failed,
+ "{key} must fail when a flag it depends on fails"
+ );
+ assert!(!details.enabled, "{key}");
+ assert_eq!(details.reason.code, "dependency_failed", "{key}");
+ }
+ }
+
#[tokio::test]
async fn test_flags_that_depends_on_other_multivariate_flag_boolean_match() {
let context = TestContext::new(None).await;