: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): fix testing tab person selector, layout, and flag dependencies (#60931)
Gustavo H. Strassburger7cebc9de3fa8
diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsxindex af9b2b5a8048..15e5c4e5ca05 100644--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx@@ -452,7 +452,14 @@ export const InfiniteListRow = ({}const itemGroup = getItemGroup(item, taxonomicGroups, group)- const itemValue = item ? itemGroup?.getValue?.(item) : null+ // Recent items are stripped to { name, id? } — getValue on the source group+ // (e.g. Persons expects distinct_ids) returns undefined. Use the canonical+ // sourceValue recorded at first selection instead.+ const itemValue = item+ ? hasRecentContext(item)+ ? (item._recentContext.sourceValue ?? itemGroup?.getValue?.(item))+ : itemGroup?.getValue?.(item)+ : nullconst normalizedValue = typeof itemValue === 'number' && typeof value === 'string' ? Number(value) : valuediff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.tsindex ed5fc6ac1a7a..6628241ff087 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts@@ -1024,5 +1024,35 @@ describe('infiniteListLogic', () => {.map((i) => i._recentContext.propertyFilter?.value)expect(cohortValues).toEqual(expect.arrayContaining([1, 2]))})++ it('preserves sourceValue on recent Persons items so the row resolves the correct distinct_id', () => {+ // Persons items are stored stripped ({name, id?}) — distinct_ids is not persisted.+ // The fix in InfiniteListRow falls back to _recentContext.sourceValue instead of+ // calling Persons.getValue (which would return undefined). This test asserts that+ // sourceValue is recorded correctly at storage time so the fallback has something to use.+ const recentLogic = recentTaxonomicFiltersLogic.build()+ recentLogic.mount()+ recentLogic.actions.recordRecentFilter({+ groupType: TaxonomicFilterGroupType.Persons,+ groupName: 'Persons',+ value: 'user-distinct-id',+ item: { name: 'Jane Doe' },+ })++ const listLogic = infiniteListLogic({+ taxonomicFilterLogicKey: 'persons-recents-test',+ listGroupType: TaxonomicFilterGroupType.RecentFilters,+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Persons, TaxonomicFilterGroupType.RecentFilters],+ showNumericalPropsOnly: false,+ })+ listLogic.mount()++ const personItems = listLogic.values.contextFilteredRecentItems+ .filter(onlyWithRecentContext)+ .filter((i) => i._recentContext.sourceGroupType === TaxonomicFilterGroupType.Persons)++ expect(personItems).toHaveLength(1)+ expect((personItems[0] as any)._recentContext.sourceValue).toBe('user-distinct-id')+ })})})diff --git a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsxindex 5e2a823d71ad..ae5560f0ee69 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx@@ -82,51 +82,53 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla{/* User Selection */}<div className="space-y-3"><LemonLabel>Select person</LemonLabel>- <TaxonomicPopover- groupType={TaxonomicFilterGroupType.Persons}- value={selectedPerson ? selectedPerson.distinct_ids[0] : ''}- onChange={(_, __, person) => {- if (person) {- setSelectedPerson(person as PersonType)- setTestFormData({- person_id: person.uuid || '',- })- } else {- setSelectedPerson(null)- setTestFormData({- person_id: '',- })- }- }}- groupTypes={[TaxonomicFilterGroupType.Persons]}- placeholder="Search for a person by name, email, or ID..."- allowClear- fullWidth- renderValue={() => {- if (selectedPerson) {- return (- <span>- {selectedPerson.name || selectedPerson.distinct_ids[0] || 'Unknown person'}- </span>- )- }- return null- }}- />+ {/* Wrapper keeps the control on its own line — both LemonLabel and the+ TaxonomicPopover render as inline-flex, so without a block wrapper a+ narrow selected value would sit beside the label instead of below it. */}+ <div>+ <TaxonomicPopover+ groupType={TaxonomicFilterGroupType.Persons}+ value={formData.distinct_id || ''}+ onChange={(value, _, person) => {+ // `value` is the person's distinct_id for every Persons-tab+ // source, including the recent tab — which only carries a+ // name + distinct_id, not the full person (no uuid/distinct_ids).+ const distinctId = typeof value === 'string' ? value : ''+ if (distinctId) {+ setSelectedPerson((person as Partial<PersonType>) ?? null)+ setTestFormData({ distinct_id: distinctId })+ } else {+ setSelectedPerson(null)+ setTestFormData({ distinct_id: '' })+ }+ }}+ groupTypes={[TaxonomicFilterGroupType.Persons]}+ placeholder="Search for a person by name, email, or ID..."+ allowClear+ fullWidth+ renderValue={() => {+ if (formData.distinct_id) {+ return (+ <span>+ {selectedPerson?.name ||+ selectedPerson?.distinct_ids?.[0] ||+ formData.distinct_id}+ </span>+ )+ }+ return null+ }}+ />+ </div><p className="text-xs text-muted">Search and select a person from your PostHog instance. You can search by name, email, ordistinct ID.</p>- {selectedPerson && (+ {formData.distinct_id && (<div className="text-xs text-muted space-y-1 p-2 bg-bg-3000 rounded"><div>- <strong>Person ID:</strong> {formData.person_id || 'Not available'}- </div>- <div>- <strong>Distinct IDs:</strong> {selectedPerson.distinct_ids.slice(0, 3).join(', ')}- {selectedPerson.distinct_ids.length > 3 &&- ` (+${selectedPerson.distinct_ids.length - 3} more)`}+ <strong>Distinct ID:</strong> {formData.distinct_id}</div></div>)}diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.tsindex 73fcca1e077d..495964405bf4 100644--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts@@ -201,6 +201,36 @@ describe('featureFlagTestingLogic', () => {})})+ describe('setSelectedPerson', () => {+ it.each([+ {+ description: 'stores a full person (from Persons tab)',+ person: { name: 'Jane Doe', uuid: 'uuid-abc', distinct_ids: ['user-123'] },+ expected: { name: 'Jane Doe', uuid: 'uuid-abc', distinct_ids: ['user-123'] },+ },+ {+ description: 'stores a partial person (from recent tab — name only, no uuid or distinct_ids)',+ person: { name: 'Jane Doe' },+ expected: { name: 'Jane Doe' },+ },+ ])('$description', async ({ person, expected }) => {+ await expectLogic(logic, () => {+ logic.actions.setSelectedPerson(person)+ }).toMatchValues({ selectedPerson: expected })+ })+ })++ describe('hasValidPerson selector', () => {+ it.each([+ { description: 'is true when distinct_id is set', formData: { distinct_id: 'user-123' }, expected: true },+ { description: 'is false when distinct_id is empty', formData: {}, expected: false },+ ])('$description', async ({ formData, expected }) => {+ await expectLogic(logic, () => {+ logic.actions.setTestFormData(formData)+ }).toMatchValues({ hasValidPerson: expected })+ })+ })+describe('errorDisplay selector', () => {const errorTestCases = [{@@ -258,6 +288,38 @@ describe('featureFlagTestingLogic', () => {})})+ describe('testFlagEvaluation person identifier', () => {+ it.each([+ {+ description: 'sends distinct_id when set',+ formData: { distinct_id: 'user-123', timestamp: '', groups: '' },+ expectedBody: { distinct_id: 'user-123' },+ },+ {+ description: 'omits distinct_id when empty',+ formData: { distinct_id: '', timestamp: '', groups: '' },+ expectedBody: {},+ },+ ])('$description', async ({ formData, expectedBody }) => {+ let capturedBody: Record<string, any> = {}+ useMocks({+ post: {+ '/api/projects/:team/feature_flags/1/test_evaluation': async (req) => {+ capturedBody = await req.json()+ return [200, {}]+ },+ },+ })++ await expectLogic(logic, () => {+ logic.actions.testFlagEvaluation({ flagId: 1, formData })+ }).toFinishAllListeners()++ expect(capturedBody).toMatchObject(expectedBody)+ expect(capturedBody).not.toHaveProperty('person_id')+ })+ })+describe('groups validation through testFlagEvaluation', () => {it.each([{ description: 'valid object succeeds', groups: '{"team": "backend"}', expectedError: null },@@ -279,7 +341,7 @@ describe('featureFlagTestingLogic', () => {await expectLogic(logic, () => {logic.actions.testFlagEvaluation({flagId: 1,- formData: { person_id: 'p1', timestamp: '', groups },+ formData: { distinct_id: 'p1', timestamp: '', groups },})}).toFinishAllListeners()diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.tsindex 7eb33fbd009d..162c5e8f08ee 100644--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts@@ -20,12 +20,12 @@ export type ConditionAnalysis = FeatureFlagConditionAnalysisApiexport type TestResult = FeatureFlagTestEvaluationResponseApiexport interface TestFormData {- person_id: string+ distinct_id: stringtimestamp: stringgroups: string}-const EMPTY_FORM: TestFormData = { person_id: '', timestamp: '', groups: '' }+const EMPTY_FORM: TestFormData = { distinct_id: '', timestamp: '', groups: '' }function validateAndParseGroups(groups: string): Record<string, any> {const trimmed = groups.trim()@@ -60,7 +60,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([setTestError: (error: string | null) => ({ error }),setDatePickerOpen: (open: boolean) => ({ open }),setDatePickerValue: (value: Dayjs | null) => ({ value }),- setSelectedPerson: (person: PersonType | null) => ({ person }),+ setSelectedPerson: (person: Partial<PersonType> | null) => ({ person }),setIncludeTime: (includeTime: boolean) => ({ includeTime }),clearTestForm: true,}),@@ -71,8 +71,8 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([testFlagEvaluation: async ({ flagId, formData }: { flagId: number; formData: TestFormData }) => {const data: FeatureFlagTestEvaluationRequestApi = {}- if (formData.person_id?.trim()) {- data.person_id = formData.person_id.trim()+ if (formData.distinct_id?.trim()) {+ data.distinct_id = formData.distinct_id.trim()}data.groups = validateAndParseGroups(formData.groups || '')@@ -157,7 +157,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([},],selectedPerson: [- null as PersonType | null,+ null as Partial<PersonType> | null,{setSelectedPerson: (_, { person }) => person,clearTestForm: () => null,@@ -232,7 +232,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([// Check if form has valid person selectedhasValidPerson: [(s) => [s.testFormData],- (formData: TestFormData): boolean => Boolean(formData.person_id?.trim()),+ (formData: TestFormData): boolean => Boolean(formData.distinct_id?.trim()),],// Get formatted error display informationerrorDisplay: [diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rsindex c6f92857ee22..e61011e11110 100644--- a/rust/feature-flags/src/api/types.rs+++ b/rust/feature-flags/src/api/types.rs@@ -1,7 +1,8 @@use crate::api::errors::FlagError;use crate::flags::flag_match_reason::FeatureFlagMatchReason;use crate::flags::flag_matching::FeatureFlagMatch;-use crate::flags::flag_models::FeatureFlag;+use crate::flags::flag_matching_utils::match_flag_value_to_flag_filter;+use crate::flags::flag_models::{FeatureFlag, FeatureFlagId};use crate::properties::property_matching::match_property;use crate::properties::property_models::OperatorType;use serde::{de, Deserialize, Deserializer, Serialize};@@ -455,6 +456,7 @@ pub trait FromFeatureAndMatch {flag_match: &FeatureFlagMatch,detailed_analysis: bool,property_values: Option<&HashMap<String, Value>>,+ flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,) -> Self;fn create_error(flag: &FeatureFlag, error: &FlagError, condition_index: Option<i32>) -> Self;fn get_reason_description(match_info: &FeatureFlagMatch) -> Option<String>;@@ -462,7 +464,7 @@ pub trait FromFeatureAndMatch {impl FromFeatureAndMatch for FlagDetails {fn create(flag: &FeatureFlag, flag_match: &FeatureFlagMatch) -> Self {- Self::create_with_analysis(flag, flag_match, false, None)+ Self::create_with_analysis(flag, flag_match, false, None, None)}fn create_with_analysis(@@ -470,6 +472,7 @@ impl FromFeatureAndMatch for FlagDetails {flag_match: &FeatureFlagMatch,detailed_analysis: bool,property_values: Option<&HashMap<String, Value>>,+ flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,) -> Self {FlagDetails {key: flag.key.clone(),@@ -492,6 +495,7 @@ impl FromFeatureAndMatch for FlagDetails {flag,flag_match,property_values,+ flag_evaluation_results,))} else {None@@ -553,6 +557,7 @@ impl FlagDetails {flag: &FeatureFlag,flag_match: &FeatureFlagMatch,property_values: Option<&HashMap<String, Value>>,+ flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,) -> Vec<ConditionAnalysis> {let mut analyses = Vec::new();@@ -589,6 +594,45 @@ impl FlagDetails {}.to_string();+ // Flag-dependency filters don't evaluate against person/group properties — they+ // resolve against the result of the flag they depend on. Running them through+ // match_property() (which rejects the FlagEvaluatesTo operator and returns Err)+ // would always report matched=false, contradicting the condition-level outcome.+ // Resolve them against the actual flag evaluation results instead.+ if property.depends_on_feature_flag() {+ let empty = HashMap::new();+ let property_matched = match_flag_value_to_flag_filter(+ property,+ flag_evaluation_results.unwrap_or(&empty),+ );+ // Do not expose the dependency flag's evaluated value here. The caller is+ // only authorized for the flag under test, not necessarily the dependency+ // flag, so serializing its raw value would leak it. `matched` reflects the+ // tested flag's own condition outcome, which the caller may already see.+ let expected = property.value.clone().unwrap_or(Value::Null);+ let explanation = if property_matched {+ format!(+ "Flag dependency '{}' satisfied the required value {}",+ property.key, expected+ )+ } else {+ format!(+ "Flag dependency '{}' did not satisfy the required value {}",+ property.key, expected+ )+ };+ property_analyses.push(PropertyAnalysis {+ key: property.key.clone(),+ operator: operator_str,+ value: expected,+ r#type: type_str,+ actual_value: None,+ matched: property_matched,+ explanation,+ });+ continue;+ }+// Generate explanation placeholder - will be updated after we know if property matchedlet explanation_placeholder = match property.operator {Some(OperatorType::IsSet) => ("is set", "is not set"),@@ -1191,7 +1235,7 @@ mod tests {// Build condition analysislet analysis =- FlagDetails::build_condition_analysis(&flag, &flag_match, Some(&property_values));+ FlagDetails::build_condition_analysis(&flag, &flag_match, Some(&property_values), None);// Verify we have analysis for both conditionsassert_eq!(analysis.len(), 2);@@ -1223,4 +1267,125 @@ mod tests {"Condition 1 should not be rollout_excluded");}++ #[test]+ fn test_condition_analysis_resolves_flag_dependencies_against_flag_results() {+ use crate::flags::flag_models::FeatureFlag;+ use std::collections::HashMap;++ // A flag with a single condition that depends on flag id 42 evaluating to true.+ let flag: FeatureFlag = serde_json::from_value(json!(+ {+ "id": 1,+ "team_id": 1,+ "name": "dependent-flag",+ "key": "dependent-flag",+ "active": true,+ "filters": {+ "groups": [+ {+ "properties": [+ {+ "key": "42",+ "value": true,+ "type": "flag",+ "operator": "flag_evaluates_to"+ }+ ],+ "rollout_percentage": 100+ }+ ]+ }+ }+ ))+ .unwrap();++ // Case 1: the dependency flag matched → the tested flag matched via condition 0.+ let flag_match = FeatureFlagMatch {+ matches: true,+ variant: None,+ reason: FeatureFlagMatchReason::ConditionMatch,+ condition_index: Some(0),+ payload: None,+ };+ let mut flag_results = HashMap::new();+ flag_results.insert(42, FlagValue::Boolean(true));++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&HashMap::new()),+ Some(&flag_results),+ );++ assert_eq!(analysis.len(), 1);+ assert!(analysis[0].matched, "Condition should be the winner");+ assert!(+ analysis[0].properties_matched,+ "Flag dependency matched, so properties_matched must be true"+ );+ assert!(+ analysis[0].properties[0].matched,+ "Flag dependency property must report matched=true"+ );+ // The dependency flag's evaluated value must not be disclosed.+ assert_eq!(analysis[0].properties[0].actual_value, None);++ // Case 2: the dependency flag did NOT match → the tested flag did not match.+ let flag_match = FeatureFlagMatch {+ matches: false,+ variant: None,+ reason: FeatureFlagMatchReason::NoConditionMatch,+ condition_index: None,+ payload: None,+ };+ let mut flag_results = HashMap::new();+ flag_results.insert(42, FlagValue::Boolean(false));++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&HashMap::new()),+ Some(&flag_results),+ );++ assert_eq!(analysis.len(), 1);+ assert!(!analysis[0].matched, "Condition should not be the winner");+ assert!(+ !analysis[0].properties_matched,+ "Flag dependency did not match, so properties_matched must be false"+ );+ assert!(+ !analysis[0].properties[0].matched,+ "Flag dependency property must report matched=false"+ );+ // The dependency flag's evaluated value must not be disclosed regardless of match outcome.+ assert_eq!(analysis[0].properties[0].actual_value, None);++ // Case 3: the dependency flag id is absent from flag_results (e.g. not yet evaluated).+ // match_flag_value_to_flag_filter returns false when the id is missing — the analysis+ // should reflect that rather than falling through to match_property() which rejects the+ // FlagEvaluatesTo operator entirely.+ let flag_match = FeatureFlagMatch {+ matches: false,+ variant: None,+ reason: FeatureFlagMatchReason::NoConditionMatch,+ condition_index: None,+ payload: None,+ };++ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&HashMap::new()),+ None, // empty — dependency flag 42 absent+ );++ assert_eq!(analysis.len(), 1);+ assert!(+ !analysis[0].properties[0].matched,+ "Absent dependency flag must report matched=false, not error"+ );+ assert_eq!(analysis[0].properties[0].actual_value, None);+ }}diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex e678b97b901a..94ed6271873c 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -1025,6 +1025,7 @@ impl FeatureFlagMatcher {flag_match,true,merged_person_props.as_ref(),+ Some(&self.flag_evaluation_state.flag_evaluation_results),)} else {FlagDetails::create(flag, flag_match)