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.

refactor(flags): compute what a flag needs before evaluation in one place (#109440)

Anders7a7ecdc5eeb7
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index 3cedc73217e9..22d5034d296f 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -480,16 +480,16 @@ async fn handle_batch_flag_evaluation(
// The Django caller already returns [] for group-aggregated and inactive flags
// without calling us; those two guards are defensive. The format check is not: nothing
// upstream filters a non-v1 stored config.
+ target
+ .filters
+ .require_v1()
+ .map_err(|_| BatchFlagEvaluationError::UnsupportedConfigFormat)?;
if target.get_group_type_index().is_some() {
return Err(BatchFlagEvaluationError::GroupAggregatedFlag);
}
if !target.active {
return Err(BatchFlagEvaluationError::FlagInactive);
}
- target
- .filters
- .require_v1()
- .map_err(|_| BatchFlagEvaluationError::UnsupportedConfigFormat)?;
let target_key = target.key.clone();
let expected_property_matching_version = request
diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index 51429b738593..151f4776ac7d 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -13,11 +13,11 @@ use common_types::TeamId;
use crate::api::errors::FlagError;
use crate::cohorts::cohort_models::{Cohort, CohortId};
use crate::flags::feature_flag_list::{UndecodableDocument, UndecodableFlags};
+use crate::flags::flag_filters::FlagRequirements;
use crate::flags::flag_models::{
EvaluationMetadata, FeatureFlag, FeatureFlagId, FeatureFlagList, FlagFilters,
HypercacheFlagsWrapper,
};
-use crate::properties::property_models::PropertyFilter;
use crate::utils::graph_utils::{DependencyGraph, DependencyProvider, DependencyType};
/// Maximum BFS depth when resolving transitive cohort-on-cohort dependencies.
@@ -149,8 +149,7 @@ fn omit_unsupported_flags(
fn retain_evaluable_and_referenced_flags(flags: &mut Vec<FeatureFlag>) {
let referenced_ids: HashSet<FeatureFlagId> = flags
.iter()
- .flat_map(active_flag_properties)
- .filter_map(|p| p.get_feature_flag_id())
+ .flat_map(|flag| active_flag_requirements(flag).flag_ids)
.collect();
flags.retain(|flag| is_evaluable(flag) || referenced_ids.contains(&flag.id));
}
@@ -166,24 +165,19 @@ fn blank_inactive_filters(flags: &mut [FeatureFlag]) {
}
}
-/// Yields all property filters from an active, non-deleted flag's filter groups.
-fn active_flag_properties(flag: &FeatureFlag) -> impl Iterator<Item = &PropertyFilter> {
- let groups = if is_evaluable(flag) {
- flag.filters.groups.as_slice()
+fn active_flag_requirements(flag: &FeatureFlag) -> FlagRequirements {
+ if is_evaluable(flag) {
+ flag.filters.requirements()
} else {
- &[]
- };
- groups.iter().flat_map(|g| g.properties.iter().flatten())
+ FlagRequirements::default()
+ }
}
/// Extract direct flag dependency IDs from a single flag's filters.
-///
-/// Scans `filters.groups[*].properties` for `type == "flag"` properties and
-/// parses their `key` as an integer flag ID. Inactive/deleted flags return
-/// empty deps to match Python's `_extract_direct_dependency_ids()`.
fn extract_direct_flag_dependency_ids(flag: &FeatureFlag) -> HashSet<FeatureFlagId> {
- active_flag_properties(flag)
- .filter_map(|p| p.get_feature_flag_id())
+ active_flag_requirements(flag)
+ .flag_ids
+ .into_iter()
.collect()
}
@@ -191,8 +185,7 @@ fn extract_direct_flag_dependency_ids(flag: &FeatureFlag) -> HashSet<FeatureFlag
pub fn extract_cohort_ids_from_flag_filters(flags: &[FeatureFlag]) -> HashSet<CohortId> {
flags
.iter()
- .flat_map(active_flag_properties)
- .filter_map(|p| p.get_cohort_id())
+ .flat_map(|flag| active_flag_requirements(flag).cohort_ids)
.collect()
}
@@ -327,7 +320,9 @@ async fn load_cohorts_with_deps(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::flags::config_v2::Subject;
use crate::flags::flag_models::{FeatureFlagRow, FlagFilters, FlagPropertyGroup};
+ use crate::flags::test_helpers::v2_filters_referencing;
use crate::properties::property_models::{OperatorType, PropertyFilter, PropertyType};
use crate::utils::test_utils::TestContext;
use test_case::test_case;
@@ -425,6 +420,27 @@ mod tests {
assert!(deps.is_empty());
}
+ #[test]
+ fn test_v2_references_reach_cohort_and_dependency_extraction() {
+ let mut v2 = make_flag(1, "v2_flag", true, vec![]);
+ v2.filters = v2_filters_referencing(&[Subject::Cohort(42), Subject::Flag(2)], None);
+ let mut flags = vec![
+ v2.clone(),
+ make_flag(2, "referenced", false, vec![]),
+ make_flag(3, "unreferenced", false, vec![]),
+ ];
+
+ assert_eq!(extract_direct_flag_dependency_ids(&v2), HashSet::from([2]));
+ assert_eq!(
+ extract_cohort_ids_from_flag_filters(&flags),
+ HashSet::from([42])
+ );
+ retain_evaluable_and_referenced_flags(&mut flags);
+ assert_eq!(flags.iter().map(|f| f.id).collect::<Vec<_>>(), vec![1, 2]);
+ let metadata = compute_flag_dependencies(&flags).unwrap();
+ assert_eq!(metadata.dependency_stages, vec![vec![2], vec![1]]);
+ }
+
// -------------------------------------------------------------------------
// extract_cohort_ids_from_flag_filters tests
// -------------------------------------------------------------------------
diff --git a/rust/feature-flags/src/flags/config_format.rs b/rust/feature-flags/src/flags/config_format.rs
index 757cd5ff14b9..6674d91138ce 100644
--- a/rust/feature-flags/src/flags/config_format.rs
+++ b/rust/feature-flags/src/flags/config_format.rs
@@ -26,12 +26,6 @@ impl ConfigFormat {
}
}
-fn config_format(version: Option<&Value>) -> ConfigFormat {
- version.map_or(ConfigFormat::V1, |value| {
- ConfigFormat::from_number(value.as_f64())
- })
-}
-
struct FilterDocument<const BUILD_DOCUMENT: bool> {
format: ConfigFormat,
document: Map<String, Value>,
@@ -62,9 +56,7 @@ impl<'de, const BUILD_DOCUMENT: bool> Deserialize<'de> for FilterDocument<BUILD_
if BUILD_DOCUMENT {
let mut version =
serde_json::from_str(raw.get()).unwrap_or(Value::Null);
- // Keep is_v1's Value-based check consistent with raw-token
- // dispatch. serialize_filters also writes this normalized
- // discriminator back to the cache.
+ // serialize_filters writes this normalized value back to the cache.
if format == ConfigFormat::V1 && version.as_f64() != Some(1.0) {
version = serde_json::json!(1.0);
}
@@ -87,7 +79,7 @@ impl<'de, const BUILD_DOCUMENT: bool> Deserialize<'de> for FilterDocument<BUILD_
impl FlagFilters {
pub(crate) fn is_v1(&self) -> bool {
- self.non_v1.is_none() && config_format(self.extra.get("version")) == ConfigFormat::V1
+ self.non_v1.is_none()
}
pub(crate) fn require_v1(&self) -> Result<(), FlagError> {
@@ -188,18 +180,14 @@ where
.map_err(serde::de::Error::custom)
}
-/// Derived serialization adds v1 fields to opaque documents. Stored JSON must use
-/// the retained raw document, or the passthrough map for manually constructed filters.
+/// Derived serialization adds v1 fields to opaque documents, so those keep their raw JSON.
pub(crate) fn serialize_filters<S>(filters: &FlagFilters, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
- if let Some(config) = &filters.non_v1 {
- config.document.serialize(serializer)
- } else if filters.is_v1() {
- filters.serialize(serializer)
- } else {
- filters.extra.serialize(serializer)
+ match &filters.non_v1 {
+ Some(config) => config.document.serialize(serializer),
+ None => filters.serialize(serializer),
}
}
diff --git a/rust/feature-flags/src/flags/config_v2.rs b/rust/feature-flags/src/flags/config_v2.rs
index 75021d3cc49f..52f8a52d11ae 100644
--- a/rust/feature-flags/src/flags/config_v2.rs
+++ b/rust/feature-flags/src/flags/config_v2.rs
@@ -6,11 +6,12 @@ use serde_json::value::RawValue;
use serde_json::{Map, Value};
use uuid::Uuid;
+use crate::flags::flag_group_type_mapping::GroupTypeIndex;
use crate::utils::json_size::estimate_json_heap_size;
mod properties;
mod raw;
-pub use properties::PersonPredicate;
+pub use properties::{Predicate, Subject};
pub(crate) use raw::validate_raw_document;
pub static MAX_CONFIG_BYTES: Lazy<usize> = Lazy::new(|| {
@@ -106,12 +107,14 @@ impl NonV1Config {
pub struct Config {
pub default_value: Option<Value>,
pub rules: Vec<Rule>,
+ /// The group type rules assign by, or `None` for persons. The parser does not admit it yet.
+ pub aggregation_group_type_index: Option<GroupTypeIndex>,
}
#[derive(Clone)]
pub struct Rule {
pub id: Uuid,
- pub targeting: Vec<PersonPredicate>,
+ pub targeting: Vec<Predicate>,
pub outcome: Outcome,
}
@@ -204,6 +207,7 @@ impl Config {
Ok(Self {
default_value,
rules,
+ aggregation_group_type_index: None,
})
}
@@ -286,11 +290,11 @@ impl Rule {
}
fn estimated_heap_bytes(&self) -> usize {
- self.targeting.capacity() * std::mem::size_of::<PersonPredicate>()
+ self.targeting.capacity() * std::mem::size_of::<Predicate>()
+ self
.targeting
.iter()
- .map(PersonPredicate::estimated_heap_bytes)
+ .map(Predicate::estimated_heap_bytes)
.sum::<usize>()
+ match &self.outcome {
Outcome::PercentageRollout { seed, value, .. } => {
diff --git a/rust/feature-flags/src/flags/config_v2/properties.rs b/rust/feature-flags/src/flags/config_v2/properties.rs
index 56bcf19c9527..72f2711b706b 100644
--- a/rust/feature-flags/src/flags/config_v2/properties.rs
+++ b/rust/feature-flags/src/flags/config_v2/properties.rs
@@ -5,6 +5,9 @@ use serde_json::Value;
use super::{
closed, object, required, string, ParseError, MAX_PREDICATES, PROPERTY_FIELDS, TARGETING_FIELDS,
};
+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::to_semver_representation;
use crate::properties::property_models::{
CompiledRegex, OperatorType, ESTIMATED_COMPILED_REGEX_BYTES,
@@ -12,8 +15,18 @@ use crate::properties::property_models::{
use crate::properties::relative_date::parse_relative_date_parts;
use crate::utils::json_size::estimate_json_heap_size;
+/// What a predicate reads. The parser admits only person predicates so far.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Subject {
+ Person,
+ Cohort(CohortId),
+ Group(GroupTypeIndex),
+ Flag(FeatureFlagId),
+}
+
#[derive(Clone)]
-pub struct PersonPredicate {
+pub struct Predicate {
+ pub subject: Subject,
pub key: String,
pub value: Option<Value>,
pub operator: OperatorType,
@@ -21,15 +34,15 @@ pub struct PersonPredicate {
pub compiled_regex: Option<CompiledRegex>,
}
-impl fmt::Debug for PersonPredicate {
+impl fmt::Debug for Predicate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("PersonPredicate")
+ f.debug_struct("Predicate")
.field("operator", &self.operator)
.finish_non_exhaustive()
}
}
-pub(super) fn parse_targeting(value: &Value) -> Result<Vec<PersonPredicate>, ParseError> {
+pub(super) fn parse_targeting(value: &Value) -> Result<Vec<Predicate>, ParseError> {
let targeting = object(value, "targeting")?;
closed(targeting, TARGETING_FIELDS, "targeting")?;
let properties = required(targeting, "properties")?
@@ -38,10 +51,10 @@ pub(super) fn parse_targeting(value: &Value) -> Result<Vec<PersonPredicate>, Par
if properties.len() > MAX_PREDICATES {
return Err(ParseError::LimitExceeded("properties"));
}
- properties.iter().map(PersonPredicate::parse).collect()
+ properties.iter().map(Predicate::parse).collect()
}
-impl PersonPredicate {
+impl Predicate {
fn parse(value: &Value) -> Result<Self, ParseError> {
let property = object(value, "property")?;
closed(property, PROPERTY_FIELDS, "property")?;
@@ -112,6 +125,7 @@ impl PersonPredicate {
.map_or(CompiledRegex::InvalidPattern, CompiledRegex::new)
});
Ok(Self {
+ subject: Subject::Person,
key: key.to_owned(),
value: value.cloned(),
operator,
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index 2c20ceed37ae..fe273dae5f40 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -78,8 +78,9 @@ impl FeatureFlagList {
}
/// Pre-compiles all regex patterns in property filters across a flag slice.
+ /// The v2 parser compiles its own predicates.
pub fn prepare_regexes_in_place(flags: &mut [FeatureFlag]) {
- for flag in flags.iter_mut() {
+ for flag in flags.iter_mut().filter(|flag| flag.filters.is_v1()) {
Self::prepare_group_regexes(&mut flag.filters.groups);
}
}
diff --git a/rust/feature-flags/src/flags/flag_filters.rs b/rust/feature-flags/src/flags/flag_filters.rs
index 5553e0ea3259..4af6e1db03ef 100644
--- a/rust/feature-flags/src/flags/flag_filters.rs
+++ b/rust/feature-flags/src/flags/flag_filters.rs
@@ -2,11 +2,60 @@ use std::collections::HashMap;
use serde_json::Value;
+use crate::cohorts::cohort_models::CohortId;
+use crate::flags::config_v2::Subject;
use crate::flags::flag_group_type_mapping::GroupTypeIndex;
-use crate::flags::flag_models::FlagFilters;
+use crate::flags::flag_models::{FeatureFlagId, FlagFilters};
use crate::properties::property_models::PropertyFilter;
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct FlagRequirements {
+ pub cohort_ids: Vec<CohortId>,
+ pub flag_ids: Vec<FeatureFlagId>,
+ pub aggregation_group_type_indexes: Vec<GroupTypeIndex>,
+ pub group_property_type_indexes: Vec<GroupTypeIndex>,
+}
+
impl FlagFilters {
+ /// An unsupported document references nothing: it fails per flag before evaluation.
+ pub fn requirements(&self) -> FlagRequirements {
+ let mut requirements = FlagRequirements::default();
+ if !self.is_v1() {
+ let Some(config) = self.supported_v2() else {
+ return requirements;
+ };
+ requirements
+ .aggregation_group_type_indexes
+ .extend(config.aggregation_group_type_index);
+ for predicate in config.rules.iter().flat_map(|rule| &rule.targeting) {
+ match predicate.subject {
+ Subject::Person => {}
+ Subject::Cohort(id) => requirements.cohort_ids.push(id),
+ Subject::Group(index) => requirements.group_property_type_indexes.push(index),
+ Subject::Flag(id) => requirements.flag_ids.push(id),
+ }
+ }
+ return requirements;
+ }
+ requirements
+ .aggregation_group_type_indexes
+ .extend(self.aggregation_group_type_index);
+ for group in &self.groups {
+ requirements
+ .aggregation_group_type_indexes
+ .extend(group.aggregation_group_type_index.flatten());
+ let aggregation = group.effective_aggregation(self.aggregation_group_type_index);
+ for property in group.properties.iter().flatten() {
+ requirements.cohort_ids.extend(property.get_cohort_id());
+ requirements.flag_ids.extend(property.get_feature_flag_id());
+ requirements
+ .group_property_type_indexes
+ .extend(property.group_filter_index(aggregation));
+ }
+ }
+ requirements
+ }
+
/// Returns the person property key used for early access feature enrollment.
pub fn enrollment_key(flag_key: &str) -> String {
format!("$feature_enrollment/{}", flag_key)
@@ -54,13 +103,90 @@ impl FlagFilters {
mod tests {
use rstest::rstest;
+ use serde_json::json;
+
+ use crate::flags::config_format::decode_filters;
use crate::flags::flag_models::FlagPropertyGroup;
+ use crate::flags::test_helpers::v2_filters_referencing;
use crate::mock;
use crate::properties::property_models::{PropertyFilter, PropertyType};
use crate::utils::mock::MockInto;
use super::*;
+ #[test]
+ fn requirements_read_every_v1_condition_with_matching_aggregation() {
+ let filters = decode_filters(json!({
+ "aggregation_group_type_index": 0,
+ "groups": [
+ {"rollout_percentage": 0, "properties": [
+ {"key": "id", "type": "cohort", "value": 7},
+ {"key": "8", "type": "flag", "value": true, "operator": "flag_evaluates_to"}
+ ]},
+ {"aggregation_group_type_index": null, "properties": [
+ {"key": "id", "type": "cohort", "value": "9"},
+ {"key": "tier", "type": "group", "value": "pro", "group_type_index": 3},
+ {"key": "plan", "type": "group", "value": "pro"}
+ ]},
+ {"aggregation_group_type_index": 2, "properties": [
+ {"key": "size", "type": "group", "value": 5}
+ ]}
+ ]
+ }))
+ .unwrap();
+ assert_eq!(
+ filters.requirements(),
+ FlagRequirements {
+ cohort_ids: vec![7, 9],
+ flag_ids: vec![8],
+ aggregation_group_type_indexes: vec![0, 2],
+ group_property_type_indexes: vec![3, 2],
+ }
+ );
+ }
+
+ #[test]
+ fn requirements_read_the_parsed_v2_config() {
+ let filters = v2_filters_referencing(
+ &[Subject::Cohort(7), Subject::Flag(8), Subject::Group(3)],
+ Some(1),
+ );
+ assert_eq!(
+ filters.requirements(),
+ FlagRequirements {
+ cohort_ids: vec![7],
+ flag_ids: vec![8],
+ aggregation_group_type_indexes: vec![1],
+ group_property_type_indexes: vec![3],
+ }
+ );
+ assert_eq!(
+ v2_filters_referencing(&[], None).requirements(),
+ FlagRequirements::default()
+ );
+ }
+
+ #[test]
+ fn unsupported_documents_require_nothing() {
+ let rule = |property: Value| {
+ json!({"id": "00000000-0000-4000-8000-000000000001", "rule_type": "targeted_release",
+ "targeting": {"properties": [property]}, "value": true})
+ };
+ for document in [
+ json!({"version": 3, "groups": [{"properties": [{"key": "id", "type": "cohort", "value": 7}]}]}),
+ json!({"version": 2, "return_type": "boolean", "default_value": false, "rules": [],
+ "aggregation_group_type_index": 1}),
+ json!({"version": 2, "return_type": "boolean", "default_value": false,
+ "rules": [rule(json!({"key": "id", "type": "cohort", "value": 7}))]}),
+ json!({"version": 2, "return_type": "boolean", "default_value": false,
+ "rules": [rule(json!({"key": "tier", "type": "group", "value": "pro", "group_type_index": 3}))]}),
+ ] {
+ let filters = decode_filters(document).unwrap();
+ assert!(filters.non_v1.is_some());
+ assert_eq!(filters.requirements(), FlagRequirements::default());
+ }
+ }
+
#[rstest]
#[case(100.0, true)]
#[case(50.0, true)]
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index c11f184bf18f..01abc9d76dc2 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -1235,25 +1235,17 @@ impl FeatureFlagMatcher {
/// analysis so group-typed filters resolve against the group's properties (and the
/// `$group_key` injected into overrides) rather than the person's. Every referenced
/// group type index is included, backed by an empty map if no properties were found.
- fn merged_group_properties_for_flag(
+ pub(crate) fn merged_group_properties_for_flag(
&self,
flag: &FeatureFlag,
group_property_overrides: &Option<HashMap<String, HashMap<String, Value>>>,
) -> HashMap<GroupTypeIndex, HashMap<String, Value>> {
- let mut referenced_indexes: HashSet<GroupTypeIndex> = HashSet::new();
- for group in &flag.filters.groups {
- // Mirrors the aggregation the real matching path uses (line ~1371 below), so
- // an explicit person aggregation (`Some(None)`) does not fall back to the
- // flag-level group index here.
- let condition_aggregation = group.effective_aggregation(flag.get_group_type_index());
- if let Some(properties) = &group.properties {
- for property in properties {
- if let Some(gti) = property.group_filter_index(condition_aggregation) {
- referenced_indexes.insert(gti);
- }
- }
- }
- }
+ let referenced_indexes: HashSet<GroupTypeIndex> = flag
+ .filters
+ .requirements()
+ .group_property_type_indexes
+ .into_iter()
+ .collect();
let mut merged = HashMap::new();
for gti in referenced_indexes {
@@ -2528,23 +2520,11 @@ impl FeatureFlagMatcher {
pub(crate) fn referenced_group_type_indexes(
flag: &FeatureFlag,
) -> impl Iterator<Item = GroupTypeIndex> + '_ {
- flag.get_group_type_index()
+ let requirements = flag.filters.requirements();
+ requirements
+ .aggregation_group_type_indexes
.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)),
- )
- }))
+ .chain(requirements.group_property_type_indexes)
}
/// Builds a paired mapping from group type index to group key for flag
diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rs
index d3b171e23719..2e20ef7978e4 100644
--- a/rust/feature-flags/src/flags/flag_operations.rs
+++ b/rust/feature-flags/src/flags/flag_operations.rs
@@ -1752,7 +1752,10 @@ mod tests {
assert!(flag.has_experience_continuity());
for version in [serde_json::json!(2), serde_json::json!(3)] {
- flag.filters.extra.insert("version".to_string(), version);
+ flag.filters = crate::flags::config_format::decode_filters(serde_json::json!({
+ "version": version, "groups": [{"rollout_percentage": 50}]
+ }))
+ .unwrap();
assert!(!flag.has_experience_continuity());
assert!(!flag.needs_hash_key_override());
}
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index a7172346e511..c5e492ba57bd 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -2280,6 +2280,31 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn test_v2_group_references_reach_the_group_readers() {
+ use crate::flags::config_v2::Subject;
+ use crate::flags::test_helpers::v2_filters_referencing;
+
+ let flag = mock!(FeatureFlag,
+ filters: v2_filters_referencing(&[Subject::Group(0)], Some(4))
+ );
+ assert_eq!(
+ FeatureFlagMatcher::referenced_group_type_indexes(&flag).collect::<HashSet<_>>(),
+ HashSet::from([0, 4])
+ );
+
+ let (_context, matcher) = group_matcher_without_group_prep(true, true).await;
+ let industry = HashMap::from([("industry".to_string(), json!("tech"))]);
+ let overrides = Some(HashMap::from([(
+ "organization".to_string(),
+ industry.clone(),
+ )]));
+ assert_eq!(
+ matcher.merged_group_properties_for_flag(&flag, &overrides),
+ HashMap::from([(0, industry)])
+ );
+ }
+
/// 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/flags/test_helpers.rs b/rust/feature-flags/src/flags/test_helpers.rs
index f2a0f1063c15..6368faea214b 100644
--- a/rust/feature-flags/src/flags/test_helpers.rs
+++ b/rust/feature-flags/src/flags/test_helpers.rs
@@ -5,13 +5,40 @@ use std::sync::Arc;
use crate::{
api::errors::{simplify_serde_error, FlagError},
flags::{
+ config_format::decode_filters,
+ config_v2::{Predicate, Subject},
feature_flag_list::PreparedFlags,
- flag_models::{FeatureFlagList, HypercacheFlagsWrapper},
+ flag_group_type_mapping::GroupTypeIndex,
+ flag_models::{FeatureFlagList, FlagFilters, HypercacheFlagsWrapper},
},
};
use common_redis::Client as RedisClient;
use common_types::TeamId;
+pub fn v2_filters_referencing(
+ subjects: &[Subject],
+ aggregation: Option<GroupTypeIndex>,
+) -> FlagFilters {
+ let mut filters = decode_filters(serde_json::json!({
+ "version": 2, "return_type": "boolean", "default_value": false,
+ "rules": [{"id": "00000000-0000-4000-8000-000000000001", "rule_type": "targeted_release",
+ "targeting": {"properties": [{"key": "email", "type": "person", "value": "[email protected]"}]},
+ "value": true}]
+ }))
+ .unwrap();
+ let non_v1 = Arc::make_mut(filters.non_v1.as_mut().unwrap());
+ let config = non_v1.parsed_v2.as_mut().unwrap().as_mut().unwrap();
+ config.aggregation_group_type_index = aggregation;
+ let person = config.rules[0].targeting[0].clone();
+ config.rules[0]
+ .targeting
+ .extend(subjects.iter().map(|&subject| Predicate {
+ subject,
+ ..person.clone()
+ }));
+ filters
+}
+
/// Generate the Django-compatible hypercache key for tests
/// Format: posthog:1:cache/teams/{team_id}/feature_flags/flags.json
/// The "posthog:1:" prefix matches Django's cache versioning
diff --git a/rust/feature-flags/tests/test_batch_flag_evaluation.rs b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
index 2f159f4143f4..9317731c3674 100644
--- a/rust/feature-flags/tests/test_batch_flag_evaluation.rs
+++ b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
@@ -211,19 +211,23 @@ async fn test_unsupported_config_format_rejected() -> Result<()> {
let server = ServerHandle::for_config(batch_eval_config()).await;
for version in [json!(2), json!(3), json!("1")] {
- let key = format!("unsupported-{version}");
- context
- .insert_flag(
+ for active in [true, false] {
+ let key = format!("unsupported-{version}-{active}");
+ let mut row = flag_row(
team.id,
- Some(flag_row(team.id, &key, json!({"version": version}))),
- )
- .await?;
-
- let res =
- send_batch_request(&server, Some(INTERNAL_TOKEN), &batch_body(team.id, &key, 0)).await;
- assert_eq!(res.status(), StatusCode::BAD_REQUEST);
- let json_response = res.json::<Value>().await?;
- assert_eq!(json_response["error"], "unsupported_config_format");
+ &key,
+ json!({"version": version, "aggregation_group_type_index": 1}),
+ );
+ row.active = active;
+ context.insert_flag(team.id, Some(row)).await?;
+
+ let res =
+ send_batch_request(&server, Some(INTERNAL_TOKEN), &batch_body(team.id, &key, 0))
+ .await;
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
+ let json_response = res.json::<Value>().await?;
+ assert_eq!(json_response["error"], "unsupported_config_format");
+ }
}
Ok(())
diff --git a/rust/feature-flags/tests/test_config_format.rs b/rust/feature-flags/tests/test_config_format.rs
index 302516746114..289218545302 100644
--- a/rust/feature-flags/tests/test_config_format.rs
+++ b/rust/feature-flags/tests/test_config_format.rs
@@ -227,6 +227,26 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: bool
} else {
FeatureFlagList::from_pg(db.non_persons_reader.clone(), team.id).await?
};
+ let mut loaded = vec![stored.clone()];
+ if !cached {
+ loaded.push(
+ FeatureFlagList::from_pg_keeping_undecodable(db.non_persons_reader.clone(), team.id)
+ .await?
+ .0,
+ );
+ }
+ let v1_keys = [
+ "absent",
+ "one",
+ "one-float",
+ "one-rounded",
+ "inactive",
+ "deleted",
+ ];
+ for flag in loaded.iter().flatten() {
+ let v1 = v1_keys.contains(&flag.key.as_str());
+ assert_eq!(flag.filters.non_v1.is_none(), v1, "{}", flag.key);
+ }
for (key, valid) in [
("evaluated-valid-v2", true),
("evaluated-rounded-v2", true),