: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): evaluate 100% device-bucketed conditions without a device_id (#100512)
posthog[bot]cda2a54be116
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.mdindex c7c00b84f6ba..f131cfb8fd1c 100644--- a/docs/internal/feature-flags/flag-evaluation-engine.md+++ b/docs/internal/feature-flags/flag-evaluation-engine.md@@ -267,7 +267,8 @@ if hash <= rollout_percentage / 100.0 → user is IN the rolloutif hash > rollout_percentage / 100.0 → user is OUT (OutOfRolloutBound)```-A 100% rollout skips the hash calculation entirely.+A 100% rollout skips the rollout hash entirely. Variant selection still hashes, with its own+salt, unless the condition pins a variant by name.### Identifier resolution priority@@ -276,9 +277,17 @@ The identifier used for hashing depends on the flag configuration:| Flag type | Bucketing | Identifier (in priority order) || ----------- | ------------- | ------------------------------------------------------------------ || Group flag | N/A | Group key from `groups` map |-| Person flag | `device_id` | `$device_id` from request, fallback to `distinct_id` |+| Person flag | `device_id` | `$device_id` from request (see below when it is absent) || Person flag | `distinct_id` | DB hash_key_override > request `$anon_distinct_id` > `distinct_id` |+A person condition on a `device_id`-bucketed flag needs the `$device_id` only when the hash+decides its outcome. If the request carries no `$device_id`, a partial rollout, or an unpinned+variant set that splits the hash range, is withheld and reports `OutOfRolloutBound`. It is not+bucketed on `distinct_id`. A condition at 100% rollout is evaluated as usual when the condition+pins a variant by name, or when every hash gets the same variant: the flag has no variants, the+first variant with a non-zero share has 100%, or every share is 0%. The identifier then changes+nothing about the result.+## Condition matchingEach flag has one or more condition groups (OR'd). Within each group, property filters are AND'd.diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex 00ecc8a28b12..f29e7434a5bd 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -1490,11 +1490,20 @@ impl FeatureFlagMatcher {if aggregation.is_none() {use crate::flags::flag_models::BucketingIdentifier;- if flag.get_bucketing_identifier() == BucketingIdentifier::DeviceId- && self- .device_id- .as_ref()- .is_none_or(|device_id| device_id.is_empty())+ let buckets_on_device_id =+ flag.get_bucketing_identifier() == BucketingIdentifier::DeviceId;+ let has_device_id = self+ .device_id+ .as_ref()+ .is_some_and(|device_id| !device_id.is_empty());++ // Without a device_id there is nothing to bucket on, so the condition is+ // withheld rather than bucketed on the wrong identifier. Withholding a+ // condition whose outcome the hash cannot change would instead disable the+ // flag for everyone it targets, so the guard asks whether it can.+ if buckets_on_device_id+ && !has_device_id+ && flag.condition_needs_bucketing_hash(condition){inc(FLAG_CONDITION_SKIPPED_COUNTER,@@ -1522,7 +1531,7 @@ impl FeatureFlagMatcher {highest_index = new_highest_index;continue;}- if flag.get_bucketing_identifier() == BucketingIdentifier::DeviceId {+ if buckets_on_device_id && has_device_id {with_canonical_log(|log| log.eval.flags_device_id_bucketing += 1);}}@@ -1631,32 +1640,14 @@ impl FeatureFlagMatcher {highest_index = new_highest_index;if is_match {- // Check for variant override in the condition- let variant = if let Some(variant_override) = &condition.variant {- // Check if the override is a valid variant- if flag- .get_variants()- .iter()- .any(|v| &v.key == variant_override)- {- Some(variant_override.clone())- } else {- // If override isn't valid, fall back to computed variant- self.get_matching_variant(- flag,- aggregation,- hash_key_overrides,- request_hash_key_override,- )?- }- } else {- // No override, use computed variant- self.get_matching_variant(+ let variant = match flag.pinned_variant(condition) {+ Some(pinned) => Some(pinned.to_string()),+ None => self.get_matching_variant(flag,aggregation,hash_key_overrides,request_hash_key_override,- )?+ )?,};let payload = self.get_matching_payload(variant.as_deref(), flag);diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rsindex fdcba1b90d23..188b1197127f 100644--- a/rust/feature-flags/src/flags/flag_operations.rs+++ b/rust/feature-flags/src/flags/flag_operations.rs@@ -104,6 +104,35 @@ impl FeatureFlag {.any(|group| group.rollout_percentage_unwrapped() < 100.0)}+ /// Returns the variant this condition pins, if it names one of the flag's variants.+ /// An override that names no real variant is ignored, so the variant comes from the hash.+ pub fn pinned_variant<'c>(&self, condition: &'c FlagPropertyGroup) -> Option<&'c str> {+ let variant = condition.variant.as_deref()?;+ self.filters+ .multivariate+ .as_ref()+ .is_some_and(|m| m.variants.iter().any(|v| v.key == variant))+ .then_some(variant)+ }++ /// Returns true if the bucketing hash decides the outcome of this condition.+ ///+ /// This does not use `has_hash_dependent_variants`. That method treats a single reachable+ /// variant as hash-independent, but hashes past that variant's share still map to no+ /// variant, and reading it here would let such a flag bucket its variant on `distinct_id`.+ pub fn condition_needs_bucketing_hash(&self, condition: &FlagPropertyGroup) -> bool {+ if condition.rollout_percentage_unwrapped() < 100.0 {+ return true;+ }+ let first_live_variant = self.filters.multivariate.as_ref().and_then(|m| {+ m.variants+ .iter()+ .find(|variant| variant.rollout_percentage > 0.0)+ });+ first_live_variant.is_some_and(|variant| variant.rollout_percentage < 100.0)+ && self.pinned_variant(condition).is_none()+ }+/// Returns true if this flag requires a hash key override lookup for experience continuity.////// Experience continuity lookups are only meaningful when the hash affects the result:@@ -1600,6 +1629,47 @@ mod tests {assert!(flag.has_partial_rollout());}+ #[rstest::rstest]+ #[case::no_variants(None, None, 100.0, false)]+ #[case::empty_variants(Some(vec![]), None, 100.0, false)]+ #[case::single_variant_at_100(Some(vec![100.0]), None, 100.0, false)]+ #[case::zero_before_100(Some(vec![0.0, 100.0]), None, 100.0, false)]+ #[case::all_zero(Some(vec![0.0, 0.0]), None, 100.0, false)]+ #[case::single_variant_short_of_range(Some(vec![50.0]), None, 100.0, true)]+ #[case::unpinned_variants(Some(vec![50.0, 50.0]), None, 100.0, true)]+ #[case::pinned_variant(Some(vec![50.0, 50.0]), Some("variant-0"), 100.0, false)]+ #[case::pin_names_no_variant(Some(vec![50.0, 50.0]), Some("nonexistent"), 100.0, true)]+ #[case::pinned_variant_partial_rollout(Some(vec![50.0, 50.0]), Some("variant-0"), 50.0, true)]+ fn test_condition_needs_bucketing_hash(+ #[case] variant_percentages: Option<Vec<f64>>,+ #[case] variant: Option<&str>,+ #[case] rollout_percentage: f64,+ #[case] expected: bool,+ ) {+ let mut flag = mock!(FeatureFlag);+ flag.filters.multivariate =+ variant_percentages.map(|percentages| MultivariateFlagOptions {+ variants: percentages+ .into_iter()+ .enumerate()+ .map(|(i, rollout_percentage)| MultivariateFlagVariant {+ key: format!("variant-{i}"),+ name: None,+ rollout_percentage,+ ..Default::default()+ })+ .collect(),+ ..Default::default()+ });+ let condition = FlagPropertyGroup {+ properties: None,+ rollout_percentage: Some(rollout_percentage),+ variant: variant.map(str::to_string),+ ..Default::default()+ };+ assert_eq!(flag.condition_needs_bucketing_hash(&condition), expected);+ }+#[test]fn test_needs_hash_key_override_no_continuity() {let mut flag = mock!(FeatureFlag);diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex 4e3d821fce88..539a0ae3a558 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -6628,6 +6628,165 @@ mod tests {);}+ #[tokio::test]+ async fn test_device_id_bucketing_matches_full_rollout_without_device() {+ 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,+ key: "device-flag-full-rollout".mock_into(),+ filters: FlagFilters {+ groups: vec![mock!(FlagPropertyGroup,+ properties: Some(vec![mock!(PropertyFilter,+ key: "plan".mock_into(),+ value: Some(json!("pro")),+ prop_type: PropertyType::Person+ )]),+ rollout_percentage: Some(100.0)+ )],+ ..Default::default()+ },+ bucketing_identifier: "device_id".mock_into()+ );++ let mut person_properties = HashMap::new();+ person_properties.insert("plan".to_string(), json!("pro"));++ let matcher = FeatureFlagMatcher::new(+ "distinct-foo".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );+ let result = matcher+ .get_match(&flag, Some(&person_properties), None, None, &None)+ .unwrap();++ assert!(+ result.matches,+ "a condition at 100% rollout needs no bucket, so a missing device_id must not withhold it"+ );+ assert_eq!(result.reason, FeatureFlagMatchReason::ConditionMatch);+ }++ #[tokio::test]+ async fn test_device_id_bucketing_matches_pinned_variant_without_device() {+ 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();+ // The variants need the hash, but the condition pins one, so nothing is hashed.+ let flag = mock!(FeatureFlag,+ team_id: team.id,+ key: "device-flag-pinned-variant".mock_into(),+ filters: FlagFilters {+ groups: vec![mock!(FlagPropertyGroup,+ properties: None,+ rollout_percentage: Some(100.0),+ variant: Some("control".to_string())+ )],+ multivariate: Some(MultivariateFlagOptions {+ variants: vec![+ MultivariateFlagVariant {+ name: None,+ key: "control".to_string(),+ rollout_percentage: 40.0,+ ..Default::default()+ },+ MultivariateFlagVariant {+ name: None,+ key: "test".to_string(),+ rollout_percentage: 60.0,+ ..Default::default()+ },+ ],+ ..Default::default()+ }),+ ..Default::default()+ },+ bucketing_identifier: "device_id".mock_into()+ );++ let matcher = FeatureFlagMatcher::new(+ "distinct-foo".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();++ assert!(+ result.matches,+ "a pinned variant needs no bucket, so a missing device_id must not withhold it"+ );+ assert_eq!(result.variant, Some("control".to_string()));+ }++ #[tokio::test]+ async fn test_device_id_bucketing_withholds_unpinned_variant_without_device() {+ 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();+ // The percentages leave part of the range unassigned, so the hash picks between+ // "test" and no variant. The variant-sum rule does not reject this today.+ let flag = mock!(FeatureFlag,+ team_id: team.id,+ key: "device-flag-short-variants".mock_into(),+ filters: FlagFilters {+ groups: vec![mock!(FlagPropertyGroup,+ properties: None,+ rollout_percentage: Some(100.0)+ )],+ multivariate: Some(MultivariateFlagOptions {+ variants: vec![MultivariateFlagVariant {+ name: None,+ key: "test".to_string(),+ rollout_percentage: 50.0,+ ..Default::default()+ }],+ ..Default::default()+ }),+ ..Default::default()+ },+ bucketing_identifier: "device_id".mock_into()+ );++ let matcher = FeatureFlagMatcher::new(+ "distinct-foo".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();++ assert!(+ !result.matches,+ "an unpinned variant reads the hash, so it must not fall back to distinct_id"+ );+ assert_eq!(result.reason, FeatureFlagMatchReason::OutOfRolloutBound);+ }+#[tokio::test]async fn test_distinct_id_bucketing_ignores_device_id() {let context = TestContext::new(None).await;