: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): preserve distinct_id in local evaluation (#58057)
Phil Haackb8bc42a31ce6
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex 4eb3185d57c6..7faa09427f21 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -363,6 +363,22 @@ impl FlagSnapshot {}}+/// Mirrors Python's `add_local_person_and_group_properties` so flag conditions+/// matching on `distinct_id` evaluate without a DB lookup. Always injects the+/// request `distinct_id` (including `""`) unless an explicit+/// `person_property_overrides["distinct_id"]` is already present, in which case+/// the explicit override wins.+fn merge_distinct_id_into_person_properties(+ distinct_id: &str,+ overrides: Option<HashMap<String, Value>>,+) -> HashMap<String, Value> {+ let mut overrides = overrides.unwrap_or_default();+ overrides+ .entry("distinct_id".to_string())+ .or_insert_with(|| Value::String(distinct_id.to_string()));+ overrides+}+impl FeatureFlagMatcher {#[allow(clippy::too_many_arguments)]pub fn new(@@ -461,6 +477,11 @@ impl FeatureFlagMatcher {) -> Result<FlagsResponse, FlagError> {let eval_timer = common_metrics::timing_guard(FLAG_EVALUATION_TIME, &[]);+ let person_property_overrides = Some(merge_distinct_id_into_person_properties(+ &self.distinct_id,+ person_property_overrides,+ ));+let precomputed = PrecomputedDependencyGraph::build(&feature_flags, flag_keys.as_deref());self.filtered_out_flag_ids = feature_flags.filtered_out_flag_ids;@@ -2496,4 +2517,53 @@ mod tests {assert!(stub.filters.groups.is_empty());}}++ #[rstest::rstest]+ #[case::injects_when_overrides_absent("user_42", None, "user_42", vec![])]+ #[case::injects_when_overrides_lack_distinct_id(+ "user_42",+ Some(vec![("email", "[email protected]")]),+ "user_42",+ vec![("email", "[email protected]")],+ )]+ #[case::explicit_override_wins(+ "user_42",+ Some(vec![("distinct_id", "explicit")]),+ "explicit",+ vec![],+ )]+ #[case::injects_empty_string_when_overrides_absent("", None, "", vec![])]+ #[case::injects_empty_string_when_overrides_lack_distinct_id(+ "",+ Some(vec![("foo", "bar")]),+ "",+ vec![("foo", "bar")],+ )]+ #[case::explicit_override_wins_over_empty_request_distinct_id(+ "",+ Some(vec![("distinct_id", "explicit")]),+ "explicit",+ vec![],+ )]+ fn test_merge_distinct_id_into_person_properties(+ #[case] request_distinct_id: &str,+ #[case] overrides: Option<Vec<(&str, &str)>>,+ #[case] expected_distinct_id: &str,+ #[case] expected_extras: Vec<(&str, &str)>,+ ) {+ let overrides = overrides.map(|kvs| {+ kvs.into_iter()+ .map(|(k, v)| (k.to_string(), Value::String(v.to_string())))+ .collect::<HashMap<_, _>>()+ });+ let result = merge_distinct_id_into_person_properties(request_distinct_id, overrides);+ assert_eq!(+ result.get("distinct_id"),+ Some(&Value::String(expected_distinct_id.to_string())),+ );+ for (k, v) in &expected_extras {+ assert_eq!(result.get(*k), Some(&Value::String((*v).to_string())));+ }+ assert_eq!(result.len(), 1 + expected_extras.len());+ }}diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rsindex 962581ec3627..b4dfb38cd1be 100644--- a/rust/feature-flags/src/flags/flag_matching_utils.rs+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs@@ -456,11 +456,13 @@ async fn fetch_group_properties(}/// Apply person and cohort results to the flag evaluation state.-fn apply_person_cohort_to_state(- state: &mut FlagEvaluationState,- result: PersonCohortResult,- distinct_id: String,-) {+///+/// `distinct_id` is intentionally not injected here. `evaluate_all_feature_flags`+/// folds `self.distinct_id` into `person_property_overrides` upfront via+/// `merge_distinct_id_into_person_properties`, and overrides extend on top of+/// these DB-loaded properties at merge time, so adding `distinct_id` here would+/// just be overwritten on the way out.+fn apply_person_cohort_to_state(state: &mut FlagEvaluationState, result: PersonCohortResult) {let person_processing_timer = common_metrics::timing_guard(FLAG_PERSON_PROCESSING_TIME, &[]);if let Some(ref person) = result.person {@@ -472,8 +474,7 @@ fn apply_person_cohort_to_state(state.set_cohort_matches(cohort_matches);}- let mut all_person_properties: HashMap<String, Value> = if let Some(ref person) = result.person- {+ let person_properties: HashMap<String, Value> = if let Some(ref person) = result.person {match person.properties.as_object() {Some(obj) => obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),None => HashMap::new(),@@ -482,11 +483,7 @@ fn apply_person_cohort_to_state(HashMap::new()};- // Always add distinct_id to person properties to match Python implementation.- // This allows flags to filter on distinct_id even when no other person properties exist.- all_person_properties.insert("distinct_id".to_string(), Value::String(distinct_id));-- state.set_person_properties(all_person_properties);+ state.set_person_properties(person_properties);person_processing_timer.fin();}@@ -538,14 +535,14 @@ pub async fn fetch_and_locally_cache_all_relevant_properties(fetch_group_properties(&reader, team_id, group_type_to_key),)?;- apply_person_cohort_to_state(flag_evaluation_state, person_cohort, distinct_id);+ apply_person_cohort_to_state(flag_evaluation_state, person_cohort);for (idx, props) in group.group_properties {flag_evaluation_state.set_group_properties(idx, props);}} else {let person_cohort =fetch_person_and_cohorts(&reader, team_id, &distinct_id, &static_cohort_ids).await?;- apply_person_cohort_to_state(flag_evaluation_state, person_cohort, distinct_id);+ apply_person_cohort_to_state(flag_evaluation_state, person_cohort);}Ok(())diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex 38338afc1e24..580e68c601cb 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -208,6 +208,77 @@ mod tests {);}+ // The injected `distinct_id` case passes `Some(HashMap::new())` so the+ // only way the override can be populated is the matcher's own injection+ // of `self.distinct_id`.+ #[rstest::rstest]+ #[case::injected_from_request("request_only_user", "request_only_user", None)]+ #[case::explicit_override_wins("request_user", "explicit_user", Some("explicit_user"))]+ #[tokio::test]+ async fn test_distinct_id_flag_matches_locally(+ #[case] matcher_distinct_id: &str,+ #[case] flag_value: &str,+ #[case] explicit_override: Option<&str>,+ ) {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let flag = mock!(FeatureFlag,+ team_id: team.id,+ filters: mock!(crate::properties::property_models::PropertyFilter,+ key: "distinct_id".mock_into(),+ value: Some(json!(flag_value)),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person+ ).mock_into()+ );++ let mut matcher = FeatureFlagMatcher::new(+ matcher_distinct_id.to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );++ let overrides = match explicit_override {+ Some(value) => HashMap::from([("distinct_id".to_string(), json!(value))]),+ None => HashMap::new(),+ };++ reset_fetch_calls_count();++ let result = matcher+ .evaluate_all_feature_flags(+ flag_list_with_metadata(vec![flag.clone()]),+ Some(overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ assert_eq!(+ result.flags.get("test_flag").unwrap().to_value(),+ FlagValue::Boolean(true)+ );+ assert_eq!(+ get_fetch_calls_count(),+ 0,+ "distinct_id-only filter should evaluate without a DB property fetch"+ );+ }+#[tokio::test]async fn test_person_only_flags_succeed_without_group_type_mappings() {let context = TestContext::new(None).await;@@ -5329,14 +5400,23 @@ mod tests {None,);- matcher- .prepare_flag_evaluation_state(&[&flag])+ let result = matcher+ .evaluate_all_feature_flags(+ flag_list_with_metadata(vec![flag.clone()]),+ None,+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ ).await.unwrap();-- let match_result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(match_result.matches);- assert_eq!(match_result.variant, None);+ assert!(!result.errors_while_computing_flags);+ assert_eq!(+ result.flags.get("flag1").unwrap().to_value(),+ FlagValue::Boolean(true)+ );}fn build_device_bucketing_flag(team_id: TeamId) -> FeatureFlag {