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): surface early-access enrollment in flag test evaluation (#66137)

Ben Lea98c58ab2b144
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
index d7279818ce97..08ec52f41aec 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
@@ -15,6 +15,10 @@ import { PropertyDefinitionType } from '~/types'
import type { ConditionAnalysis, TestResult } from './featureFlagTestingLogic'
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
+
const CONDITION_DISPLAY_STYLES = {
success: {
card: 'border-success bg-success-highlight',
@@ -416,7 +420,9 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla
>
<div className="flex items-center gap-2 mb-2">
<h6 className="font-medium text-sm">
- Condition #{condition.index}
+ {condition.index === SUPER_CONDITION_INDEX
+ ? 'Early access enrollment'
+ : `Condition #${condition.index + 1}`}
</h6>
{condition.display.label && (
<span
diff --git a/products/feature_flags/mcp/apps/FeatureFlagTestingView.test.tsx b/products/feature_flags/mcp/apps/FeatureFlagTestingView.test.tsx
new file mode 100644
index 000000000000..8b23796f3c91
--- /dev/null
+++ b/products/feature_flags/mcp/apps/FeatureFlagTestingView.test.tsx
@@ -0,0 +1,92 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import { type ReactElement } from 'react'
+
+import {
+ type ConditionAnalysis,
+ type FeatureFlagTestingData,
+ FeatureFlagTestingView,
+ SUPER_CONDITION_INDEX,
+} from './FeatureFlagTestingView'
+
+// quill is a workspace package that isn't transformed under the frontend jest harness — stub it
+// so this stays a unit test of FeatureFlagTestingView's own logic (matched-condition label + guard).
+jest.mock(
+ '@posthog/quill',
+ () => ({
+ Card: ({ children }: { children: ReactElement }) => <div>{children}</div>,
+ CardHeader: ({ children }: { children: ReactElement }) => <div>{children}</div>,
+ CardTitle: ({ children }: { children: ReactElement }) => <div>{children}</div>,
+ CardDescription: ({ children }: { children: ReactElement }) => <div>{children}</div>,
+ CardContent: ({ children }: { children: ReactElement }) => <div>{children}</div>,
+ Badge: ({ children }: { children: ReactElement }) => <span>{children}</span>,
+ }),
+ { virtual: true }
+)
+
+const baseFlag: FeatureFlagTestingData = {
+ flag_key: 'beta-feature',
+ result: true,
+ reason: 'condition_match',
+ condition_index: 0,
+ payload: null,
+ person_properties: {},
+ conditions: [],
+}
+
+describe('FeatureFlagTestingView', () => {
+ afterEach(cleanup)
+
+ const matchedConditionCases: Array<{
+ reason: string
+ condition_index: number | null
+ conditions: ConditionAnalysis[]
+ expectedLabel: string
+ }> = [
+ // The matcher always sets condition_index: Some(0) for an enrollment win, and the analysis
+ // builder prepends a matched entry at the sentinel index — the label reads that entry.
+ {
+ reason: 'super_condition_value',
+ condition_index: 0,
+ conditions: [{ index: SUPER_CONDITION_INDEX, matched: true, rollout_percentage: 100 }],
+ 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' },
+ { reason: 'condition_match', condition_index: 2, conditions: [], expectedLabel: '#3' },
+ ]
+
+ test.each(matchedConditionCases)(
+ 'labels the matched condition for reason $reason',
+ ({ reason, condition_index, conditions, expectedLabel }) => {
+ render(<FeatureFlagTestingView flag={{ ...baseFlag, reason, condition_index, conditions }} />)
+
+ expect(screen.getByText('Matched condition:')).toBeTruthy()
+ expect(screen.getByText(expectedLabel)).toBeTruthy()
+ }
+ )
+
+ it('derives the enrollment 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 re-checking flag.reason === 'super_condition_value'.
+ render(
+ <FeatureFlagTestingView
+ flag={{
+ ...baseFlag,
+ reason: 'condition_match',
+ condition_index: 0,
+ conditions: [{ index: SUPER_CONDITION_INDEX, matched: true, rollout_percentage: 100 }],
+ }}
+ />
+ )
+
+ expect(screen.getByText('Early access enrollment')).toBeTruthy()
+ })
+
+ 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 }} />)
+
+ expect(screen.queryByText('Matched condition:')).toBeNull()
+ })
+})
diff --git a/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx b/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx
index 8b84d37ddfe9..7ea2ac75dc79 100644
--- a/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx
+++ b/products/feature_flags/mcp/apps/FeatureFlagTestingView.tsx
@@ -4,6 +4,10 @@ import { Badge, Card, CardContent, CardHeader, CardTitle, CardDescription } from
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
+
export interface ConditionAnalysis {
index: number
matched: boolean
@@ -46,6 +50,19 @@ export function FeatureFlagTestingView({ flag }: FeatureFlagTestingViewProps): R
return String(flag.result)
}
+ 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.
+ const matchedCondition = flag.conditions.find((condition) => condition.matched)
+ if (matchedCondition?.index === SUPER_CONDITION_INDEX) {
+ return 'Early access enrollment'
+ }
+ if (flag.reason === 'holdout_condition_value') {
+ return 'Holdout'
+ }
+ return `#${flag.condition_index! + 1}`
+ }
+
return (
<div className="p-4">
<div className="flex flex-col gap-2">
@@ -76,10 +93,10 @@ export function FeatureFlagTestingView({ flag }: FeatureFlagTestingViewProps): R
<span className="font-medium">Reason: </span>
<span className="text-secondary">{flag.reason}</span>
</div>
- {flag.condition_index !== null && (
+ {(flag.condition_index !== null || flag.reason === 'holdout_condition_value') && (
<div className="text-sm">
<span className="font-medium">Matched condition: </span>
- <span className="text-secondary">#{flag.condition_index + 1}</span>
+ <span className="text-secondary">{matchedConditionLabel()}</span>
</div>
)}
{flag.payload != null && (
@@ -124,15 +141,22 @@ export function FeatureFlagTestingView({ flag }: FeatureFlagTestingViewProps): R
</CardHeader>
<CardContent>
<div className="flex flex-col gap-1">
- {flag.conditions.map((condition, index) => (
- <Card key={index}>
+ {flag.conditions.map((condition) => (
+ <Card key={condition.index}>
<CardContent>
<div className="flex items-center gap-2">
- <span className="text-sm font-medium">Condition #{index + 1}:</span>
+ <span className="text-sm font-medium">
+ {condition.index === SUPER_CONDITION_INDEX
+ ? 'Early access enrollment:'
+ : `Condition #${condition.index + 1}:`}
+ </span>
<Badge variant={condition.matched ? 'success' : 'destructive'}>
{condition.matched ? 'Matched' : 'No match'}
</Badge>
- <Badge>{condition.rollout_percentage}% rollout</Badge>
+ {/* enrollment super condition has no rollout */}
+ {condition.index !== SUPER_CONDITION_INDEX && (
+ <Badge>{condition.rollout_percentage}% rollout</Badge>
+ )}
{condition.variant && <Badge variant="info">{condition.variant}</Badge>}
</div>
{(condition.explanation || condition.reason) && (
diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rs
index ffdc12848675..0bcf46b684d5 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};
+use crate::flags::flag_models::{FeatureFlag, FeatureFlagId, FlagFilters};
use crate::properties::property_matching::match_property;
use crate::properties::property_models::OperatorType;
use chrono_tz::Tz;
@@ -397,6 +397,12 @@ pub struct PropertyAnalysis {
pub explanation: String,
}
+/// `ConditionAnalysis::index` for the early-access enrollment entry, which has no position among
+/// the zero-based release conditions. Negative so consumers can label it instead of "Condition #N".
+/// Mirrored independently in `FeatureFlagTestingTab.tsx` and `FeatureFlagTestingView.tsx`: update
+/// both if this value ever changes.
+pub const SUPER_CONDITION_INDEX: i32 = -1;
+
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ConditionAnalysis {
pub index: i32,
@@ -604,17 +610,14 @@ impl FlagDetails {
// flag-level group index here.
let effective_aggregation = group.effective_aggregation(flag.get_group_type_index());
- // Determine if this condition matched based on overall flag result and condition index
- // Only mark as matched if the flag itself matched AND this is the matching condition
- if flag_match.matches {
- if let Some(condition_index) = flag_match.condition_index {
- condition_matched = index == condition_index;
- } else if matches!(flag_match.reason, FeatureFlagMatchReason::ConditionMatch) {
- // Fallback: assume first condition matched if we have a condition match but no index
- condition_matched = index == 0;
- }
+ // Only a real ConditionMatch wins a release condition. Enrollment wins report
+ // condition_index Some(0) and holdout wins report None, but neither is a ConditionMatch,
+ // so gating on the reason keeps both from being attributed to a release condition here.
+ if flag_match.matches
+ && matches!(flag_match.reason, FeatureFlagMatchReason::ConditionMatch)
+ {
+ condition_matched = index == flag_match.condition_index.unwrap_or(0);
}
- // If flag_match.matches is false, condition_matched remains false for all conditions
// Analyze properties within this group
if let Some(properties) = &group.properties {
@@ -794,23 +797,26 @@ impl FlagDetails {
is_zero_rollout && all_properties_matched
};
+ // 1-based to match the frontend's Condition #N headers.
let explanation = if this_condition_rollout_excluded {
format!(
"Condition {} matched properties but was excluded by {}% rollout",
- index, rollout_percentage
+ index + 1,
+ rollout_percentage
)
} else if all_properties_matched && condition_matched {
format!(
"Condition {} matched and passed {}% rollout",
- index, rollout_percentage
+ index + 1,
+ rollout_percentage
)
} else if all_properties_matched && !condition_matched {
format!(
"Condition {} matched properties but was not evaluated due to an earlier condition matching",
- index
+ index + 1
)
} else {
- format!("Condition {} did not match properties", index)
+ format!("Condition {} did not match properties", index + 1)
};
let analysis = ConditionAnalysis {
@@ -827,8 +833,77 @@ 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.
+ if flag.filters.feature_enrollment == Some(true) {
+ analyses.insert(
+ 0,
+ Self::build_enrollment_condition_analysis(flag, flag_match, property_values),
+ );
+ }
+
analyses
}
+
+ /// Synthetic [`ConditionAnalysis`] for the early-access enrollment super condition.
+ fn build_enrollment_condition_analysis(
+ flag: &FeatureFlag,
+ flag_match: &FeatureFlagMatch,
+ property_values: Option<&HashMap<String, Value>>,
+ ) -> ConditionAnalysis {
+ let enrollment_key = FlagFilters::enrollment_key(&flag.key);
+
+ // Mirrors the matcher's opted-in check; absent means enrollment doesn't apply.
+ let actual_value = property_values.and_then(|props| props.get(&enrollment_key).cloned());
+ let enrolled = actual_value.as_ref().is_some_and(FlagFilters::is_enrolled);
+
+ // Winner only when the matcher actually resolved the flag through enrollment.
+ let matched = enrolled
+ && flag_match.matches
+ && matches!(
+ flag_match.reason,
+ FeatureFlagMatchReason::SuperConditionValue
+ );
+
+ let (property_matched, property_explanation, explanation) = if enrolled {
+ (
+ true,
+ format!("Property '{enrollment_key}' is true (opted in)"),
+ "Enrolled in the early access feature. This overrides all release conditions and enables the flag".to_string(),
+ )
+ } else if actual_value.is_some() {
+ (
+ false,
+ format!("Property '{enrollment_key}' is set but not true (opted out)"),
+ "Opted out of the early access feature. This overrides all release conditions and disables the flag".to_string(),
+ )
+ } else {
+ (
+ false,
+ format!("Property '{enrollment_key}' is not set (not enrolled)"),
+ "Not enrolled in the early access feature. The release conditions below are evaluated normally".to_string(),
+ )
+ };
+
+ ConditionAnalysis {
+ index: SUPER_CONDITION_INDEX,
+ properties: vec![PropertyAnalysis {
+ key: enrollment_key,
+ operator: "exact".to_string(),
+ value: Value::Bool(true),
+ r#type: "person".to_string(),
+ actual_value,
+ matched: property_matched,
+ explanation: property_explanation,
+ }],
+ rollout_percentage: 100.0,
+ variant: None,
+ matched,
+ properties_matched: enrolled,
+ rollout_excluded: false,
+ explanation,
+ }
+ }
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, Eq)]
@@ -954,6 +1029,9 @@ where
mod tests {
use super::*;
use crate::flags::flag_match_reason::FeatureFlagMatchReason;
+ use crate::flags::flag_match_reason::FeatureFlagMatchReason::{
+ ConditionMatch, SuperConditionValue,
+ };
use crate::flags::flag_matching::FeatureFlagMatch;
use chrono::Utc;
use rstest::rstest;
@@ -1638,4 +1716,155 @@ mod tests {
);
assert_eq!(analysis[0].properties[0].actual_value, None);
}
+
+ #[rstest]
+ #[case::opted_in(Some("true"), SuperConditionValue, true, true, true, "Enrolled", false)]
+ #[case::opted_out(
+ Some("false"),
+ SuperConditionValue,
+ false,
+ false,
+ false,
+ "Opted out",
+ false
+ )]
+ #[case::not_enrolled(None, ConditionMatch, true, false, false, "Not enrolled", true)]
+ fn test_condition_analysis_surfaces_early_access_enrollment(
+ #[case] enrollment_value: Option<&str>,
+ #[case] reason: FeatureFlagMatchReason,
+ #[case] flag_matches: bool,
+ #[case] expected_enrollment_matched: bool,
+ #[case] expected_enrollment_properties_matched: bool,
+ #[case] expected_explanation_fragment: &str,
+ #[case] expected_release_condition_matched: bool,
+ ) {
+ use crate::flags::flag_models::FeatureFlag;
+ use std::collections::HashMap;
+
+ let flag: FeatureFlag = serde_json::from_value(json!({
+ "id": 1, "team_id": 1, "name": "beta-feature", "key": "beta-feature", "active": true,
+ "filters": {
+ "feature_enrollment": true,
+ "groups": [{
+ "properties": [{ "key": "is_scoped", "value": ["false"], "operator": "exact", "type": "person" }],
+ "rollout_percentage": 100
+ }]
+ }
+ }))
+ .unwrap();
+
+ // is_scoped="false" makes the release condition match, so opted-in/out exercise enrollment
+ // overriding an otherwise-matching release condition.
+ let enrollment_key = "$feature_enrollment/beta-feature";
+ let mut property_values = HashMap::from([("is_scoped".to_string(), json!("false"))]);
+ if let Some(v) = enrollment_value {
+ property_values.insert(enrollment_key.to_string(), json!(v));
+ }
+
+ let flag_match = FeatureFlagMatch {
+ matches: flag_matches,
+ variant: None,
+ reason,
+ condition_index: Some(0),
+ payload: None,
+ };
+
+ let analysis = FlagDetails::build_condition_analysis(
+ &flag,
+ &flag_match,
+ Some(&property_values),
+ None,
+ None,
+ chrono_tz::Tz::UTC,
+ );
+
+ // Enrollment is surfaced as the first entry (omitted entirely before the fix).
+ assert_eq!(analysis.len(), 2);
+ let enrollment = &analysis[0];
+ assert_eq!(enrollment.index, SUPER_CONDITION_INDEX);
+ assert_eq!(enrollment.matched, expected_enrollment_matched);
+ assert_eq!(
+ enrollment.properties_matched,
+ expected_enrollment_properties_matched
+ );
+ assert!(enrollment
+ .explanation
+ .contains(expected_explanation_fragment));
+ assert_eq!(
+ enrollment.properties[0].actual_value,
+ enrollment_value.map(|v| json!(v))
+ );
+
+ // The release condition wins only when the flag matched through it, never hijacked by the
+ // super condition's condition_index Some(0). is_scoped="false" is always in
+ // property_values, so the release condition's own properties always match, pinning the
+ // premise that enrollment overrides an otherwise-matching condition.
+ assert_eq!(analysis[1].index, 0);
+ assert!(analysis[1].properties_matched);
+ assert_eq!(analysis[1].matched, expected_release_condition_matched);
+ assert!(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.
+ let flag: FeatureFlag = serde_json::from_value(json!({
+ "id": 1, "team_id": 1, "name": "beta-feature", "key": "beta-feature", "active": true,
+ "filters": {
+ "feature_enrollment": true,
+ "groups": [
+ {
+ "properties": [{ "key": "is_scoped", "value": ["true"], "operator": "exact", "type": "person" }],
+ "rollout_percentage": 100
+ },
+ {
+ "properties": [{ "key": "is_scoped", "value": ["false"], "operator": "exact", "type": "person" }],
+ "rollout_percentage": 100
+ }
+ ]
+ }
+ }))
+ .unwrap();
+
+ // is_scoped="false" fails group 0's ["true"] requirement and satisfies group 1's, so the
+ // matcher resolves through group 1, not group 0.
+ let property_values = HashMap::from([("is_scoped".to_string(), json!("false"))]);
+
+ let flag_match = FeatureFlagMatch {
+ matches: true,
+ variant: None,
+ reason: ConditionMatch,
+ condition_index: Some(1),
+ payload: None,
+ };
+
+ let analysis = FlagDetails::build_condition_analysis(
+ &flag,
+ &flag_match,
+ Some(&property_values),
+ None,
+ None,
+ chrono_tz::Tz::UTC,
+ );
+
+ // Enrollment entry, then both release conditions in order, with only group 1 as the winner.
+ assert_eq!(analysis.len(), 3);
+ assert_eq!(analysis[0].index, SUPER_CONDITION_INDEX);
+ assert!(!analysis[0].matched);
+
+ assert_eq!(analysis[1].index, 0);
+ assert!(!analysis[1].properties_matched);
+ assert!(!analysis[1].matched);
+
+ assert_eq!(analysis[2].index, 1);
+ assert!(analysis[2].properties_matched);
+ assert!(analysis[2].matched);
+
+ assert!(analysis.iter().filter(|c| c.matched).count() <= 1);
+ }
}
diff --git a/rust/feature-flags/src/flags/flag_filters.rs b/rust/feature-flags/src/flags/flag_filters.rs
index eb93d815fc75..f4ed1a042e88 100644
--- a/rust/feature-flags/src/flags/flag_filters.rs
+++ b/rust/feature-flags/src/flags/flag_filters.rs
@@ -10,6 +10,12 @@ impl FlagFilters {
format!("$feature_enrollment/{}", flag_key)
}
+ /// Whether an enrollment property value means "opted in": `"true"` or boolean `true`. Any
+ /// other present value means opted out.
+ pub fn is_enrolled(value: &Value) -> bool {
+ value == "true" || value == &Value::Bool(true)
+ }
+
pub fn requires_db_properties(
&self,
overrides: &HashMap<String, Value>,
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index dbf1a46e056c..a182bba413e3 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -1329,7 +1329,7 @@ impl FeatureFlagMatcher {
let person_properties = self.get_person_properties(person_property_overrides)?;
if let Some(v) = person_properties.get(&enrollment_key) {
- let is_match = v == "true" || v == &Value::Bool(true);
+ let is_match = FlagFilters::is_enrolled(v);
let payload = self.get_matching_payload(None, flag);
return Ok(FeatureFlagMatch {
matches: is_match,