: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): surface holdout in flag test evaluation breakdown (#71803)
posthog[bot]d264802b4e43
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsxindex 08ec52f41aec..9d47d77f0bc1 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx@@ -18,6 +18,14 @@ import { featureFlagTestingLogic } from './featureFlagTestingLogic'// Matches SUPER_CONDITION_INDEX in rust/feature-flags/src/api/types.rs: the early-access// enrollment super condition has no position among the zero-based release conditions.const SUPER_CONDITION_INDEX = -1+// Matches HOLDOUT_CONDITION_INDEX in rust/feature-flags/src/api/types.rs: the holdout has no+// position among the zero-based release conditions either.+const HOLDOUT_CONDITION_INDEX = -2++const SYNTHETIC_CONDITION_LABELS: Record<number, string> = {+ [SUPER_CONDITION_INDEX]: 'Early access enrollment',+ [HOLDOUT_CONDITION_INDEX]: 'Holdout',+}const CONDITION_DISPLAY_STYLES = {success: {@@ -420,9 +428,8 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla><div className="flex items-center gap-2 mb-2"><h6 className="font-medium text-sm">- {condition.index === SUPER_CONDITION_INDEX- ? 'Early access enrollment'- : `Condition #${condition.index + 1}`}+ {SYNTHETIC_CONDITION_LABELS[condition.index] ??+ `Condition #${condition.index + 1}`}</h6>{condition.display.label && (<spandiff --git a/products/feature_flags/mcp/apps/FeatureFlagTestingView.test.tsx b/products/feature_flags/mcp/apps/FeatureFlagTestingView.test.tsxindex 8b23796f3c91..0901c711491b 100644--- a/products/feature_flags/mcp/apps/FeatureFlagTestingView.test.tsx+++ b/products/feature_flags/mcp/apps/FeatureFlagTestingView.test.tsx@@ -5,6 +5,7 @@ import {type ConditionAnalysis,type FeatureFlagTestingData,FeatureFlagTestingView,+ HOLDOUT_CONDITION_INDEX,SUPER_CONDITION_INDEX,} from './FeatureFlagTestingView'@@ -51,9 +52,14 @@ describe('FeatureFlagTestingView', () => {expectedLabel: 'Early access enrollment',},// The matcher sets condition_index: None for a holdout win, which is why the guard also- // has to check flag.reason directly, not just condition_index !== null. Holdout has no- // per-condition entry yet, so its label still comes from flag.reason.- { reason: 'holdout_condition_value', condition_index: null, conditions: [], expectedLabel: 'Holdout' },+ // has to check flag.reason directly, not just condition_index !== null. The label itself+ // reads the matched entry at the holdout sentinel index, same as the enrollment case.+ {+ reason: 'holdout_condition_value',+ condition_index: null,+ conditions: [{ index: HOLDOUT_CONDITION_INDEX, matched: true, rollout_percentage: 100 }],+ expectedLabel: 'Holdout',+ },{ reason: 'condition_match', condition_index: 2, conditions: [], expectedLabel: '#3' },]@@ -84,6 +90,41 @@ describe('FeatureFlagTestingView', () => {expect(screen.getByText('Early access enrollment')).toBeTruthy()})+ it('derives the holdout label from the matched condition entry, not flag.reason', () => {+ // reason deliberately disagrees with the conditions entry, so this only passes if the+ // label reads flag.conditions rather than checking flag.reason === 'holdout_condition_value'.+ render(+ <FeatureFlagTestingView+ flag={{+ ...baseFlag,+ reason: 'condition_match',+ condition_index: 0,+ conditions: [{ index: HOLDOUT_CONDITION_INDEX, matched: true, rollout_percentage: 100 }],+ }}+ />+ )++ expect(screen.getByText('Holdout')).toBeTruthy()+ })++ it('labels the holdout entry in the condition breakdown, not "Condition #-1"', () => {+ // A holdout win now carries a synthetic entry at the holdout sentinel index; the breakdown+ // must render it as "Holdout:" rather than deriving "Condition #<sentinel+1>" from the index.+ render(+ <FeatureFlagTestingView+ flag={{+ ...baseFlag,+ reason: 'holdout_condition_value',+ condition_index: null,+ conditions: [{ index: HOLDOUT_CONDITION_INDEX, matched: true, rollout_percentage: 100 }],+ }}+ />+ )++ expect(screen.getByText('Holdout:')).toBeTruthy()+ expect(screen.queryByText(`Condition #${HOLDOUT_CONDITION_INDEX + 1}:`)).toBeNull()+ })+it('hides the matched-condition line when there is no condition index and no holdout', () => {render(<FeatureFlagTestingView flag={{ ...baseFlag, reason: 'no_condition_match', condition_index: null }} />)diff --git a/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx b/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsxindex 7ea2ac75dc79..3d85e11ad53e 100644--- a/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx+++ b/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx@@ -7,6 +7,14 @@ import { PropertyFilterList, type PropertyFilter } from './PropertyFilterList'// Matches SUPER_CONDITION_INDEX in rust/feature-flags/src/api/types.rs: the early-access// enrollment super condition has no position among the zero-based release conditions.export const SUPER_CONDITION_INDEX = -1+// Matches HOLDOUT_CONDITION_INDEX in rust/feature-flags/src/api/types.rs: the holdout has no+// position among the zero-based release conditions either.+export const HOLDOUT_CONDITION_INDEX = -2++const SYNTHETIC_CONDITION_LABELS: Record<number, string> = {+ [SUPER_CONDITION_INDEX]: 'Early access enrollment',+ [HOLDOUT_CONDITION_INDEX]: 'Holdout',+}export interface ConditionAnalysis {index: number@@ -51,12 +59,15 @@ export function FeatureFlagTestingView({ flag }: FeatureFlagTestingViewProps): R}const matchedConditionLabel = (): string => {- // Reuse the same signal the condition list below uses (a matched entry at the sentinel- // index) instead of re-deriving "was this enrollment" from flag.reason separately.+ // Reuse the same signal and label map the condition list below uses (a matched entry at+ // the sentinel index) instead of re-deriving "was this enrollment/holdout" from flag.reason.const matchedCondition = flag.conditions.find((condition) => condition.matched)- if (matchedCondition?.index === SUPER_CONDITION_INDEX) {- return 'Early access enrollment'+ const syntheticLabel = matchedCondition && SYNTHETIC_CONDITION_LABELS[matchedCondition.index]+ if (syntheticLabel) {+ return syntheticLabel}+ // Falls back to flag.reason if the backend hasn't started emitting the synthetic holdout+ // entry yet (the Rust service and this frontend deploy independently).if (flag.reason === 'holdout_condition_value') {return 'Holdout'}@@ -146,15 +157,16 @@ export function FeatureFlagTestingView({ flag }: FeatureFlagTestingViewProps): R<CardContent><div className="flex items-center gap-2"><span className="text-sm font-medium">- {condition.index === SUPER_CONDITION_INDEX- ? 'Early access enrollment:'- : `Condition #${condition.index + 1}:`}+ {`${+ SYNTHETIC_CONDITION_LABELS[condition.index] ??+ `Condition #${condition.index + 1}`+ }:`}</span><Badge variant={condition.matched ? 'success' : 'destructive'}>{condition.matched ? 'Matched' : 'No match'}</Badge>- {/* enrollment super condition has no rollout */}- {condition.index !== SUPER_CONDITION_INDEX && (+ {/* synthetic (enrollment/holdout) entries have no release rollout */}+ {condition.index >= 0 && (<Badge>{condition.rollout_percentage}% rollout</Badge>)}{condition.variant && <Badge variant="info">{condition.variant}</Badge>}diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rsindex 0bcf46b684d5..18787694e5c2 100644--- a/rust/feature-flags/src/api/types.rs+++ b/rust/feature-flags/src/api/types.rs@@ -3,7 +3,7 @@ use crate::flags::flag_group_type_mapping::GroupTypeIndex;use crate::flags::flag_match_reason::FeatureFlagMatchReason;use crate::flags::flag_matching::FeatureFlagMatch;use crate::flags::flag_matching_utils::match_flag_value_to_flag_filter;-use crate::flags::flag_models::{FeatureFlag, FeatureFlagId, FlagFilters};+use crate::flags::flag_models::{FeatureFlag, FeatureFlagId, FlagFilters, Holdout};use crate::properties::property_matching::match_property;use crate::properties::property_models::OperatorType;use chrono_tz::Tz;@@ -403,6 +403,12 @@ pub struct PropertyAnalysis {/// both if this value ever changes.pub const SUPER_CONDITION_INDEX: i32 = -1;+/// `ConditionAnalysis::index` for the holdout entry, which (like enrollment) has no position among+/// the zero-based release conditions. Distinct from `SUPER_CONDITION_INDEX` so a flag with both an+/// enrollment super condition and a holdout keeps two separate synthetic rows. Mirrored independently+/// in `FeatureFlagTestingTab.tsx` and `FeatureFlagTestingView.tsx`: update all three if it changes.+pub const HOLDOUT_CONDITION_INDEX: i32 = -2;+#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]pub struct ConditionAnalysis {pub index: i32,@@ -833,16 +839,60 @@ impl FlagDetails {analyses.push(analysis);}- // Surface the early-access enrollment super condition: the matcher applies it before the- // release conditions, but the loop above can't see it.+ // Surface synthetic entries the matcher evaluates before the release conditions above but+ // which the loop can't see, in the matcher's enrollment-then-holdout evaluation order.+ let mut synthetic = Vec::new();+if flag.filters.feature_enrollment == Some(true) {- analyses.insert(- 0,- Self::build_enrollment_condition_analysis(flag, flag_match, property_values),- );+ synthetic.push(Self::build_enrollment_condition_analysis(+ flag,+ flag_match,+ property_values,+ ));+ }++ // Holdout is only shown when the flag actually resolved through it — the "excluded from+ // holdout" case isn't distinguishable here without threading the holdout hash result down+ // from the matcher.+ if matches!(+ flag_match.reason,+ FeatureFlagMatchReason::HoldoutConditionValue+ ) {+ if let Some(holdout) = &flag.filters.holdout {+ synthetic.push(Self::build_holdout_condition_analysis(holdout, flag_match));+ }+ }++ if synthetic.is_empty() {+ return analyses;}- analyses+ synthetic.extend(analyses);+ synthetic+ }++ /// Synthetic [`ConditionAnalysis`] for the holdout, surfaced only when the matcher resolved the+ /// flag through it (reason `HoldoutConditionValue`). The holdout has no person properties — it's+ /// a hash rollout keyed on the flag's aggregation — so the entry carries no property rows and+ /// explains the exclusion percentage in prose instead.+ fn build_holdout_condition_analysis(+ holdout: &Holdout,+ flag_match: &FeatureFlagMatch,+ ) -> ConditionAnalysis {+ let exclusion_percentage = holdout.exclusion_percentage_clamped();++ ConditionAnalysis {+ index: HOLDOUT_CONDITION_INDEX,+ properties: vec![],+ rollout_percentage: 100.0,+ variant: flag_match.variant.clone(),+ matched: true,+ properties_matched: true,+ rollout_excluded: false,+ explanation: format!(+ "In the holdout group ({exclusion_percentage}% of users are held out). This overrides all release conditions and holds the flag at its holdout value"+ ),+ }}/// Synthetic [`ConditionAnalysis`] for the early-access enrollment super condition.@@ -1805,14 +1855,161 @@ mod tests {assert!(analysis.iter().filter(|c| c.matched).count() <= 1);}+ /// Shared fixture for the two holdout-surfacing tests below: a flag with a holdout and a+ /// release condition that would otherwise match on its own.+ fn held_flag_with_release_condition() -> (+ crate::flags::flag_models::FeatureFlag,+ HashMap<String, Value>,+ ) {+ use crate::flags::flag_models::FeatureFlag;++ let flag: FeatureFlag = serde_json::from_value(json!({+ "id": 1, "team_id": 1, "name": "held-flag", "key": "held-flag", "active": true,+ "filters": {+ "holdout": { "id": 42, "exclusion_percentage": 10.0 },+ "groups": [{+ "properties": [{ "key": "is_scoped", "value": ["false"], "operator": "exact", "type": "person" }],+ "rollout_percentage": 100+ }]+ }+ }))+ .unwrap();++ let property_values = HashMap::from([("is_scoped".to_string(), json!("false"))]);++ (flag, property_values)+ }++ #[test]+ fn test_condition_analysis_surfaces_holdout_winner() {+ // When the matcher resolves through the holdout, the holdout entry must be surfaced as+ // the winner and the release condition must not be attributed the win.+ let (flag, property_values) = held_flag_with_release_condition();++ let flag_match = FeatureFlagMatch {+ matches: true,+ variant: Some("holdout-42".to_string()),+ reason: FeatureFlagMatchReason::HoldoutConditionValue,+ condition_index: None,+ payload: None,+ };++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&property_values),+ None,+ None,+ chrono_tz::Tz::UTC,+ );++ // Holdout is surfaced as the first entry (omitted entirely before the fix).+ assert_eq!(analysis.len(), 2);+ let holdout = &analysis[0];+ assert_eq!(holdout.index, HOLDOUT_CONDITION_INDEX);+ assert!(holdout.matched);+ assert!(holdout.properties_matched);+ assert!(!holdout.rollout_excluded);+ assert!(holdout.properties.is_empty());+ assert_eq!(holdout.variant, Some("holdout-42".to_string()));+ assert!(holdout.explanation.contains("holdout"));+ assert!(holdout.explanation.contains("10%"));++ // The release condition matches its properties but the holdout, not it, is the winner.+ assert_eq!(analysis[1].index, 0);+ assert!(analysis[1].properties_matched);+ assert!(!analysis[1].matched);+ assert_eq!(analysis.iter().filter(|c| c.matched).count(), 1);+ }++ #[test]+ fn test_condition_analysis_omits_holdout_entry_when_flag_did_not_resolve_via_holdout() {+ // The person was excluded from the holdout and matched a release condition instead.+ // Without the holdout hash threaded down we can't describe the exclusion, so no holdout+ // entry is surfaced (only the winning release condition).+ let (flag, property_values) = held_flag_with_release_condition();++ let flag_match = FeatureFlagMatch {+ matches: true,+ variant: None,+ reason: FeatureFlagMatchReason::ConditionMatch,+ condition_index: Some(0),+ payload: None,+ };++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&property_values),+ None,+ None,+ chrono_tz::Tz::UTC,+ );++ assert_eq!(analysis.len(), 1);+ assert_eq!(analysis[0].index, 0);+ assert!(analysis[0].matched);+ }++ #[test]+ fn test_condition_analysis_orders_enrollment_before_holdout_when_both_configured() {+ // A flag with both an enrollment super condition and a holdout: when the person isn't+ // enrolled and the matcher resolves via the holdout, both synthetic entries must be+ // surfaced together, in the matcher's enrollment-then-holdout order.+ use crate::flags::flag_models::FeatureFlag;++ let flag: FeatureFlag = serde_json::from_value(json!({+ "id": 1, "team_id": 1, "name": "held-flag", "key": "held-flag", "active": true,+ "filters": {+ "feature_enrollment": true,+ "holdout": { "id": 42, "exclusion_percentage": 10.0 },+ "groups": [{+ "properties": [{ "key": "is_scoped", "value": ["false"], "operator": "exact", "type": "person" }],+ "rollout_percentage": 100+ }]+ }+ }))+ .unwrap();++ // No enrollment property set, so the person isn't enrolled and the matcher falls+ // through to the holdout.+ let property_values = HashMap::from([("is_scoped".to_string(), json!("false"))]);++ let flag_match = FeatureFlagMatch {+ matches: true,+ variant: Some("holdout-42".to_string()),+ reason: FeatureFlagMatchReason::HoldoutConditionValue,+ condition_index: None,+ payload: None,+ };++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&property_values),+ None,+ None,+ chrono_tz::Tz::UTC,+ );++ assert_eq!(analysis.len(), 3);+ assert_eq!(analysis[0].index, SUPER_CONDITION_INDEX);+ assert!(!analysis[0].matched);+ assert_eq!(analysis[1].index, HOLDOUT_CONDITION_INDEX);+ assert!(analysis[1].matched);+ assert_eq!(analysis[2].index, 0);+ assert!(!analysis[2].matched);+ assert_eq!(analysis.iter().filter(|c| c.matched).count(), 1);+ }+#[test]fn test_condition_analysis_attributes_winner_to_non_zero_release_condition() {use crate::flags::flag_models::FeatureFlag;use std::collections::HashMap;// Two release groups, plus enrollment enabled, so this also exercises the interaction- // between the enrollment entry's analyses.insert(0, ...) and attribution to a non-zero- // condition_index: the enrollment entry must stay first while group 1 still wins.+ // between the prepended enrollment entry and attribution to a non-zero condition_index:+ // the enrollment entry must stay first while group 1 still wins.let flag: FeatureFlag = serde_json::from_value(json!({"id": 1, "team_id": 1, "name": "beta-feature", "key": "beta-feature", "active": true,"filters": {diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex a182bba413e3..91e4d7161048 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -1794,7 +1794,7 @@ impl FeatureFlagMatcher {request_hash_key_override: &Option<String>,) -> Result<(bool, Option<String>, FeatureFlagMatchReason), FlagError> {if let Some(holdout) = &flag.filters.holdout {- let percentage = holdout.exclusion_percentage.clamp(0.0, 100.0);+ let percentage = holdout.exclusion_percentage_clamped();if percentage < 100.0&& self.get_holdout_hash(flag, None, request_hash_key_override)?diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rsindex 67cfecc8d11c..a281a7b7b743 100644--- a/rust/feature-flags/src/flags/flag_models.rs+++ b/rust/feature-flags/src/flags/flag_models.rs@@ -126,6 +126,14 @@ pub struct Holdout {pub exclusion_percentage: f64,}+impl Holdout {+ /// `exclusion_percentage` clamped to a valid 0-100 range, guarding against an out-of-range+ /// stored value.+ pub fn exclusion_percentage_clamped(&self) -> f64 {+ self.exclusion_percentage.clamp(0.0, 100.0)+ }+}+#[derive(Debug, Clone, Deserialize, Serialize, Default)]pub struct FlagPropertyGroup {#[serde(default, skip_serializing_if = "Option::is_none")]