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.

feat(flags): show person display name when targeting by distinct ID (#63057)

Gustavo H. Strassburger13c0f73be508
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
index 9ce3f8f66235..5f5a7c5c3f4c 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
@@ -47,9 +47,16 @@ import { featureFlagLogic } from './featureFlagLogic'
import {
FeatureFlagReleaseConditionsLogicProps,
featureFlagReleaseConditionsLogic,
+ isDistinctIdFilter,
} from './featureFlagReleaseConditionsLogic'
-function PropertyValueComponent({ property }: { property: AnyPropertyFilter }): JSX.Element {
+function PropertyValueComponent({
+ property,
+ getDistinctIdName,
+}: {
+ property: AnyPropertyFilter
+ getDistinctIdName: (distinctId: string) => string
+}): JSX.Element {
if (property.type === PropertyFilterType.Cohort) {
return (
<LemonButton type="secondary" size="xsmall" to={urls.cohort(property.value)} sideIcon={<IconOpenInNew />}>
@@ -62,12 +69,13 @@ function PropertyValueComponent({ property }: { property: AnyPropertyFilter }):
return <></>
}
const propertyValues = Array.isArray(property.value) ? property.value : [property.value]
+ const isDistinctId = isDistinctIdFilter(property)
return (
<>
{propertyValues.map((val, idx) => (
<LemonSnack key={idx}>
- {String(val)}
+ {isDistinctId ? getDistinctIdName(String(val)) : String(val)}
<span>
{isPropertyFilterWithOperator(property) &&
['is_date_before', 'is_date_after'].includes(property.operator) &&
@@ -125,6 +133,7 @@ export function FeatureFlagReleaseConditions({
aggregationTargetName,
properties,
filterGroups,
+ getDistinctIdName,
} = useValues(releaseConditionsLogic)
const {
@@ -343,7 +352,7 @@ export function FeatureFlagReleaseConditions({
<span>{allOperatorsToHumanName(property.operator)} </span>
) : null}
- <PropertyValueComponent property={property} />
+ <PropertyValueComponent property={property} getDistinctIdName={getDistinctIdName} />
</div>
))}
</>
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
index 685c9ae8dfe7..f01a3c71a651 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
@@ -81,6 +81,7 @@ import {
FeatureFlagReleaseConditionsLogicProps,
FeatureFlagGroupTypeWithSortKey,
featureFlagReleaseConditionsLogic,
+ isDistinctIdFilter,
} from './featureFlagReleaseConditionsLogic'
interface FeatureFlagReleaseConditionsCollapsibleProps extends FeatureFlagReleaseConditionsLogicProps {
@@ -109,7 +110,11 @@ type MatchByOption = {
learnMoreUrl?: string
}
-function summarizeProperties(properties: AnyPropertyFilter[], aggregationTargetName: string): string {
+function summarizeProperties(
+ properties: AnyPropertyFilter[],
+ aggregationTargetName: string,
+ getDistinctIdName: (distinctId: string) => string
+): string {
if (!properties || properties.length === 0) {
// Capitalize first letter of aggregation target name
const capitalizedTarget = aggregationTargetName.charAt(0).toUpperCase() + aggregationTargetName.slice(1)
@@ -130,22 +135,27 @@ function summarizeProperties(properties: AnyPropertyFilter[], aggregationTargetN
property.key === '$group_key' && property.type === PropertyFilterType.Group && 'group_key_names' in property
? ((property as any).group_key_names ?? {})
: {}
- const hasGroupKeyNames = Object.keys(groupKeyNames).length > 0
+ const isDistinctId = isDistinctIdFilter(property)
+ // Resolve a single raw value to its display name: server-provided group name,
+ // frontend-fetched person name, or the raw value as fallback.
+ const resolveValue = (raw: unknown): string => {
+ const strVal = String(raw)
+ if (isDistinctId) {
+ return getDistinctIdName(strVal)
+ }
+ return groupKeyNames[strVal] || strVal
+ }
let value: string | number
if (property.type === PropertyFilterType.Cohort) {
value = property.cohort_name || `ID ${property.value}`
} else if (Array.isArray(property.value)) {
- const displayValues = hasGroupKeyNames
- ? property.value.map((v) => groupKeyNames[String(v)] || String(v))
- : property.value.map(String)
+ const displayValues = property.value.map(resolveValue)
value = displayValues.slice(0, 2).join(', ') + (displayValues.length > 2 ? '...' : '')
} else if (property.value === null || property.value === undefined) {
value = ''
} else {
- value = hasGroupKeyNames
- ? groupKeyNames[String(property.value)] || String(property.value)
- : String(property.value)
+ value = resolveValue(property.value)
}
return `${key} ${operator} ${value}`
@@ -164,6 +174,7 @@ interface ConditionHeaderProps {
totalGroups: number
affectedCount: number | undefined
aggregationTargetName: string
+ getDistinctIdName: (distinctId: string) => string
onDuplicate: () => void
onRemove: () => void
}
@@ -174,11 +185,13 @@ function ConditionHeader({
totalGroups,
affectedCount,
aggregationTargetName,
+ getDistinctIdName,
onDuplicate,
onRemove,
}: ConditionHeaderProps): JSX.Element {
// Use description if available, otherwise summarize the filters
- const summary = group.description || summarizeProperties(group.properties || [], aggregationTargetName)
+ const summary =
+ group.description || summarizeProperties(group.properties || [], aggregationTargetName, getDistinctIdName)
const rollout = group.rollout_percentage ?? 100
const actualCount =
@@ -315,6 +328,7 @@ interface ConditionProps {
affectedCounts: Record<string, number | undefined>
totalCounts: Record<string, number | undefined>
aggregationTargetName: (conditionGroupTypeIndex?: number | null) => string
+ getDistinctIdName: (distinctId: string) => string
taxonomicGroupTypesForCondition: (conditionGroupTypeIndex: number | null | undefined) => TaxonomicFilterGroupType[]
groupTypes: Map<GroupTypeIndex, GroupType>
setConditionAggregation: (index: number, groupTypeIndex: number | null) => void
@@ -384,6 +398,7 @@ const ConditionContent = ({
affectedCounts,
totalCounts,
aggregationTargetName,
+ getDistinctIdName,
taxonomicGroupTypesForCondition,
groupTypes,
setConditionAggregation,
@@ -505,6 +520,7 @@ const ConditionContent = ({
totalGroups={totalGroups}
affectedCount={group.sort_key ? affectedCounts[group.sort_key] : undefined}
aggregationTargetName={aggregationTargetName(group.aggregation_group_type_index)}
+ getDistinctIdName={getDistinctIdName}
onDuplicate={onDuplicate}
onRemove={onRemove}
/>
@@ -807,6 +823,7 @@ export function FeatureFlagReleaseConditionsCollapsible({
affectedCounts,
totalCounts,
aggregationTargetName,
+ getDistinctIdName,
taxonomicGroupTypesForCondition,
filters: releaseFilters,
groupTypes,
@@ -912,7 +929,8 @@ export function FeatureFlagReleaseConditionsCollapsible({
group.description ||
summarizeProperties(
group.properties || [],
- aggregationTargetName(group.aggregation_group_type_index)
+ aggregationTargetName(group.aggregation_group_type_index),
+ getDistinctIdName
)
const rollout = group.rollout_percentage ?? 100
return (
@@ -1307,6 +1325,7 @@ export function FeatureFlagReleaseConditionsCollapsible({
affectedCounts={affectedCounts}
totalCounts={totalCounts}
aggregationTargetName={aggregationTargetName}
+ getDistinctIdName={getDistinctIdName}
taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}
groupTypes={groupTypes}
setConditionAggregation={setConditionAggregation}
@@ -1349,7 +1368,8 @@ export function FeatureFlagReleaseConditionsCollapsible({
draggedGroup.properties || [],
aggregationTargetName(
draggedGroup.aggregation_group_type_index
- )
+ ),
+ getDistinctIdName
)}
</span>
</div>
@@ -1381,6 +1401,7 @@ export function FeatureFlagReleaseConditionsCollapsible({
affectedCounts={affectedCounts}
totalCounts={totalCounts}
aggregationTargetName={aggregationTargetName}
+ getDistinctIdName={getDistinctIdName}
taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}
groupTypes={groupTypes}
setConditionAggregation={setConditionAggregation}
@@ -1431,6 +1452,7 @@ export function FeatureFlagReleaseConditionsCollapsible({
affectedCounts={affectedCounts}
totalCounts={totalCounts}
aggregationTargetName={aggregationTargetName}
+ getDistinctIdName={getDistinctIdName}
taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}
groupTypes={groupTypes}
setConditionAggregation={setConditionAggregation}
@@ -1463,6 +1485,7 @@ export function FeatureFlagReleaseConditionsCollapsible({
affectedCounts={affectedCounts}
totalCounts={totalCounts}
aggregationTargetName={aggregationTargetName}
+ getDistinctIdName={getDistinctIdName}
taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}
groupTypes={groupTypes}
setConditionAggregation={setConditionAggregation}
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx
index d8ecfb25078d..8d5fc35cd85f 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx
@@ -20,7 +20,7 @@ import {
import { EarlyExitIndicator } from './EarlyExitIndicator'
import { FeatureFlagConditionWarning } from './FeatureFlagConditionWarning'
-import { featureFlagReleaseConditionsLogic } from './featureFlagReleaseConditionsLogic'
+import { featureFlagReleaseConditionsLogic, isDistinctIdFilter } from './featureFlagReleaseConditionsLogic'
interface FeatureFlagReleaseConditionsReadonlyProps {
id: string
@@ -37,7 +37,13 @@ function getGroupKeyNames(property: AnyPropertyFilter): Record<string, string> {
return {}
}
-function PropertyValueDisplay({ property }: { property: AnyPropertyFilter }): JSX.Element {
+function PropertyValueDisplay({
+ property,
+ getDistinctIdName,
+}: {
+ property: AnyPropertyFilter
+ getDistinctIdName: (distinctId: string) => string
+}): JSX.Element {
if (property.type === PropertyFilterType.Cohort) {
return (
<LemonButton type="secondary" size="xsmall" to={urls.cohort(property.value)} sideIcon={<IconOpenInNew />}>
@@ -48,19 +54,28 @@ function PropertyValueDisplay({ property }: { property: AnyPropertyFilter }): JS
const propertyValues = Array.isArray(property.value) ? property.value : [property.value]
const groupKeyNames = property.key === '$group_key' ? getGroupKeyNames(property) : {}
+ const isDistinctId = isDistinctIdFilter(property)
return (
<>
{propertyValues.map((val, idx) => {
const strVal = String(val)
- const display = groupKeyNames[strVal] || strVal
+ const display = isDistinctId ? getDistinctIdName(strVal) : groupKeyNames[strVal] || strVal
return <LemonSnack key={idx}>{display}</LemonSnack>
})}
</>
)
}
-function PropertyFilterRow({ property, isFirst }: { property: AnyPropertyFilter; isFirst: boolean }): JSX.Element {
+function PropertyFilterRow({
+ property,
+ isFirst,
+ getDistinctIdName,
+}: {
+ property: AnyPropertyFilter
+ isFirst: boolean
+ getDistinctIdName: (distinctId: string) => string
+}): JSX.Element {
const propertyLabel =
property.type === PropertyFilterType.Cohort || property.type === PropertyFilterType.Flag
? null
@@ -90,7 +105,7 @@ function PropertyFilterRow({ property, isFirst }: { property: AnyPropertyFilter;
<LemonSnack>{property.type === PropertyFilterType.Cohort ? 'Cohort' : property.key}</LemonSnack>
)}
<span className="text-muted">{operator}</span>
- <PropertyValueDisplay property={property} />
+ <PropertyValueDisplay property={property} getDistinctIdName={getDistinctIdName} />
</div>
)
}
@@ -109,7 +124,7 @@ export function FeatureFlagReleaseConditionsReadonly({
filters,
})
- const { filterGroups, aggregationTargetName, properties } = useValues(releaseConditionsLogic)
+ const { filterGroups, aggregationTargetName, properties, getDistinctIdName } = useValues(releaseConditionsLogic)
return (
<div className="flex flex-col gap-2">
@@ -142,6 +157,7 @@ export function FeatureFlagReleaseConditionsReadonly({
group={group}
index={index}
aggregationTargetName={aggregationTargetName(group.aggregation_group_type_index)}
+ getDistinctIdName={getDistinctIdName}
/>
</div>
))}
@@ -158,9 +174,15 @@ interface ConditionSetCardProps {
group: FeatureFlagGroupType
index: number
aggregationTargetName: string
+ getDistinctIdName: (distinctId: string) => string
}
-function ConditionSetCard({ group, index, aggregationTargetName }: ConditionSetCardProps): JSX.Element {
+function ConditionSetCard({
+ group,
+ index,
+ aggregationTargetName,
+ getDistinctIdName,
+}: ConditionSetCardProps): JSX.Element {
const properties = group.properties || []
const rollout = group.rollout_percentage ?? 100
@@ -191,7 +213,12 @@ function ConditionSetCard({ group, index, aggregationTargetName }: ConditionSetC
{properties.length > 0 && (
<div className="mt-3 flex flex-col gap-1">
{properties.map((property, idx) => (
- <PropertyFilterRow key={idx} property={property} isFirst={idx === 0} />
+ <PropertyFilterRow
+ key={idx}
+ property={property}
+ isFirst={idx === 0}
+ getDistinctIdName={getDistinctIdName}
+ />
))}
</div>
)}
diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts
index 66f03c95cbd8..65429e30b23e 100644
--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts
@@ -1276,4 +1276,249 @@ describe('the feature flag release conditions logic', () => {
})
})
})
+
+ describe('distinct_id display names', () => {
+ function distinctIdFilters(value: string | string[]): FeatureFlagType['filters'] {
+ return generateFeatureFlagFilters([
+ {
+ properties: [
+ {
+ key: 'distinct_id',
+ type: PropertyFilterType.Person,
+ value,
+ operator: PropertyOperator.Exact,
+ },
+ ],
+ rollout_percentage: 100,
+ variant: null,
+ sort_key: 'A',
+ },
+ ])
+ }
+
+ it.each([
+ {
+ name: 'array value, falling back to the raw id for unmatched persons',
+ value: ['distinct-1', 'distinct-2'] as string | string[],
+ // distinct-2 has no matching person, so it's absent from results.
+ results: { 'distinct-1': { name: '[email protected]' } },
+ expectedDistinctIds: ['distinct-1', 'distinct-2'],
+ expectedCache: { 'distinct-1': '[email protected]', 'distinct-2': 'distinct-2' },
+ expectedLabels: {
+ 'distinct-1': 'distinct-1 ([email protected])',
+ // Unresolved ids and unknown ids both fall back to the raw distinct id.
+ 'distinct-2': 'distinct-2',
+ 'never-requested': 'never-requested',
+ },
+ },
+ {
+ name: 'scalar value',
+ value: 'distinct-1' as string | string[],
+ results: { 'distinct-1': { name: '[email protected]' } },
+ expectedDistinctIds: ['distinct-1'],
+ expectedCache: { 'distinct-1': '[email protected]' },
+ expectedLabels: { 'distinct-1': 'distinct-1 ([email protected])' },
+ },
+ ])(
+ 'resolves person names for distinct_id targeting ($name)',
+ async ({ value, results, expectedDistinctIds, expectedCache, expectedLabels }) => {
+ logic?.unmount()
+
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/user_blast_radius': () => [
+ 200,
+ { affected: 10, total: 100 },
+ ],
+ '/api/environments/:team/persons/batch_by_distinct_ids/': () => [200, { results }],
+ },
+ })
+
+ logic = featureFlagReleaseConditionsLogic({
+ id: 'distinct-id-names',
+ filters: distinctIdFilters(value),
+ })
+
+ await expectLogic(logic, () => {
+ logic.mount()
+ })
+ .toDispatchActions(['loadDistinctIdNames', 'setDistinctIdNames'])
+ .toMatchValues({ distinctIdNameCache: expectedCache })
+
+ expect(logic.values.distinctIds).toEqual(expectedDistinctIds)
+ for (const [id, label] of Object.entries(expectedLabels)) {
+ expect(logic.values.getDistinctIdName(id)).toBe(label)
+ }
+ }
+ )
+
+ it('falls back to raw ids without caching when the persons request fails', async () => {
+ logic?.unmount()
+
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 10, total: 100 }],
+ '/api/environments/:team/persons/batch_by_distinct_ids/': () => [500, {}],
+ },
+ })
+
+ logic = featureFlagReleaseConditionsLogic({
+ id: 'distinct-id-error',
+ filters: distinctIdFilters(['distinct-1', 'distinct-2']),
+ })
+
+ await expectLogic(logic, () => {
+ logic.mount()
+ })
+ .toDispatchActions(['loadDistinctIdNames'])
+ .toFinishAllListeners()
+ // Failed ids stay uncached so a later setFilters/updateConditionSet retries them.
+ .toMatchValues({ distinctIdNameCache: {} })
+
+ expect(logic.values.getDistinctIdName('distinct-1')).toBe('distinct-1')
+ })
+
+ it('preserves resolved names from earlier chunks when a later chunk fails', async () => {
+ logic?.unmount()
+
+ // More than one batch worth of ids so the request is chunked.
+ const ids = Array.from({ length: 250 }, (_, i) => `d-${i}`)
+ const firstChunkResults = Object.fromEntries(ids.slice(0, 200).map((id) => [id, { name: `name-${id}` }]))
+
+ let callCount = 0
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 10, total: 100 }],
+ '/api/environments/:team/persons/batch_by_distinct_ids/': () => {
+ callCount += 1
+ // First chunk resolves, second chunk fails.
+ return callCount === 1 ? [200, { results: firstChunkResults }] : [500, {}]
+ },
+ },
+ })
+
+ logic = featureFlagReleaseConditionsLogic({
+ id: 'distinct-id-chunked',
+ filters: distinctIdFilters(ids),
+ })
+
+ await expectLogic(logic, () => {
+ logic.mount()
+ })
+ .toDispatchActions(['loadDistinctIdNames', 'setDistinctIdNames'])
+ .toFinishAllListeners()
+
+ // First-chunk names survive; the failed second chunk stays uncached and renders raw.
+ expect(logic.values.getDistinctIdName('d-0')).toBe('d-0 (name-d-0)')
+ expect(logic.values.getDistinctIdName('d-200')).toBe('d-200')
+ })
+
+ it('resolves names when a distinct_id filter is added to a mounted flag', async () => {
+ logic?.unmount()
+
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 10, total: 100 }],
+ '/api/environments/:team/persons/batch_by_distinct_ids/': () => [
+ 200,
+ { results: { 'distinct-1': { name: '[email protected]' } } },
+ ],
+ },
+ })
+
+ logic = featureFlagReleaseConditionsLogic({
+ id: 'distinct-id-edit',
+ filters: generateFeatureFlagFilters([
+ { properties: [], rollout_percentage: 100, variant: null, sort_key: 'A' },
+ ]),
+ })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.updateConditionSet(0, undefined, [
+ {
+ key: 'distinct_id',
+ type: PropertyFilterType.Person,
+ value: ['distinct-1'],
+ operator: PropertyOperator.Exact,
+ },
+ ])
+ }).toDispatchActions(['loadDistinctIdNames', 'setDistinctIdNames'])
+
+ expect(logic.values.getDistinctIdName('distinct-1')).toBe('distinct-1 ([email protected])')
+ })
+
+ it('does not re-fetch names for ids already in the cache', async () => {
+ logic?.unmount()
+
+ let callCount = 0
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 10, total: 100 }],
+ '/api/environments/:team/persons/batch_by_distinct_ids/': () => {
+ callCount += 1
+ return [200, { results: { 'distinct-1': { name: '[email protected]' } } }]
+ },
+ },
+ })
+
+ logic = featureFlagReleaseConditionsLogic({
+ id: 'distinct-id-no-refetch',
+ filters: distinctIdFilters(['distinct-1']),
+ })
+
+ await expectLogic(logic, () => {
+ logic.mount()
+ })
+ .toDispatchActions(['loadDistinctIdNames', 'setDistinctIdNames'])
+ .toFinishAllListeners()
+
+ expect(callCount).toBe(1)
+
+ // Re-adding the same id re-triggers resolution, but the cache filter should skip the fetch.
+ await expectLogic(logic, () => {
+ logic.actions.updateConditionSet(0, undefined, [
+ {
+ key: 'distinct_id',
+ type: PropertyFilterType.Person,
+ value: ['distinct-1'],
+ operator: PropertyOperator.Exact,
+ },
+ ])
+ })
+ .toDispatchActions(['loadDistinctIdNames'])
+ .toFinishAllListeners()
+
+ expect(callCount).toBe(1)
+ })
+
+ it('does not fetch names when there are no distinct_id filters', async () => {
+ logic?.unmount()
+
+ logic = featureFlagReleaseConditionsLogic({
+ id: 'no-distinct-id',
+ filters: generateFeatureFlagFilters([
+ {
+ properties: [
+ {
+ key: 'email',
+ type: PropertyFilterType.Person,
+ value: '[email protected]',
+ operator: PropertyOperator.Exact,
+ },
+ ],
+ rollout_percentage: 100,
+ variant: null,
+ sort_key: 'A',
+ },
+ ]),
+ })
+
+ await expectLogic(logic, () => {
+ logic.mount()
+ }).toNotHaveDispatchedActions(['loadDistinctIdNames'])
+
+ expect(logic.values.distinctIds).toEqual([])
+ })
+ })
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts
index c1a07ae92b71..cd6f04e463ad 100644
--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts
@@ -36,6 +36,14 @@ import {
import type { featureFlagReleaseConditionsLogicType } from './featureFlagReleaseConditionsLogicType'
+// A property filter targets people by their raw distinct id.
+export function isDistinctIdFilter(property: AnyPropertyFilter): boolean {
+ return property.type === PropertyFilterType.Person && property.key === 'distinct_id'
+}
+
+// Server caps batch_by_distinct_ids per request; chunk client-side so every id resolves.
+const DISTINCT_ID_BATCH_SIZE = 200
+
// Helper function to move a condition set to a new index
function moveConditionSet<T>(groups: T[], index: number, newIndex: number): T[] {
const updatedGroups = [...groups]
@@ -131,6 +139,8 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition
loadAllFlagKeys: (flagIds: string[]) => ({ flagIds }),
setFlagKeys: (flagKeys: Record<string, string>) => ({ flagKeys }),
setFlagKeysLoading: (isLoading: boolean) => ({ isLoading }),
+ loadDistinctIdNames: (distinctIds: string[]) => ({ distinctIds }),
+ setDistinctIdNames: (distinctIdNames: Record<string, string>) => ({ distinctIdNames }),
setOpenConditions: (openConditions: string[]) => ({ openConditions }),
openCondition: (sortKey: string) => ({ sortKey }),
setIsMixedTargeting: (isMixedTargeting: boolean) => ({ isMixedTargeting }),
@@ -377,6 +387,15 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition
setFlagKeysLoading: (_, { isLoading }) => isLoading,
},
],
+ distinctIdNameCache: [
+ {} as Record<string, string>,
+ {
+ setDistinctIdNames: (state, { distinctIdNames }) => ({
+ ...state,
+ ...distinctIdNames,
+ }),
+ },
+ ],
openConditions: [
[] as string[],
{
@@ -413,10 +432,13 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition
})),
listeners(({ actions, values, props }) => ({
setFilters: async () => {
- const { flagIds } = values
+ const { flagIds, distinctIds } = values
if (flagIds.length > 0) {
await actions.loadAllFlagKeys(flagIds)
}
+ if (distinctIds.length > 0) {
+ actions.loadDistinctIdNames(distinctIds)
+ }
// Recalculate blast radius when filters change (e.g., from template application)
if (!props.readOnly) {
actions.calculateBlastRadius()
@@ -455,6 +477,11 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition
if (allFlagIds.length > 0) {
await actions.loadAllFlagKeys(allFlagIds)
}
+
+ // Resolve display names for any distinct_id targeting in the updated properties.
+ if (values.distinctIds.length > 0) {
+ actions.loadDistinctIdNames(values.distinctIds)
+ }
}
if (!newProperties || newProperties.some(isEmptyProperty)) {
@@ -628,6 +655,45 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition
actions.setFlagKeysLoading(false)
}
},
+ loadDistinctIdNames: async ({ distinctIds }) => {
+ if (!distinctIds || distinctIds.length === 0) {
+ return
+ }
+
+ // Only fetch ids we haven't resolved yet. Failed lookups stay uncached so they
+ // retry on a later setFilters/updateConditionSet rather than pinning to the raw id.
+ const uncachedIds = [...new Set(distinctIds)].filter((id) => !(id in values.distinctIdNameCache))
+ if (uncachedIds.length === 0) {
+ return
+ }
+
+ // Resolve a chunk to its display-name mapping, keeping the raw id when no
+ // meaningful name resolved.
+ const toMapping = (
+ chunk: string[],
+ personsByDistinctId: Record<string, { name?: string }>
+ ): Record<string, string> =>
+ Object.fromEntries(
+ chunk.map((id) => {
+ const name = personsByDistinctId[id]?.name
+ return [id, name && name !== id ? name : id]
+ })
+ )
+
+ // Commit each chunk as it resolves so a later-chunk failure doesn't discard
+ // already-resolved names.
+ for (let i = 0; i < uncachedIds.length; i += DISTINCT_ID_BATCH_SIZE) {
+ const chunk = uncachedIds.slice(i, i + DISTINCT_ID_BATCH_SIZE)
+ try {
+ const personsByDistinctId = await api.persons.getByDistinctIds(chunk)
+ actions.setDistinctIdNames(toMapping(chunk, personsByDistinctId))
+ } catch (error) {
+ // Leave failed ids uncached so a later setFilters/updateConditionSet retries
+ // them; getDistinctIdName already renders the raw id while unresolved.
+ console.error('Error loading distinct ID names:', error)
+ }
+ }
+ },
})),
selectors({
filterGroups: [(s) => [s.filters], (filters: FeatureFlagFilters) => filters.groups || []],
@@ -779,6 +845,32 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition
) || []
) || [],
],
+ distinctIds: [
+ (s) => [s.filterGroups],
+ (filterGroups: FeatureFlagGroupType[]): string[] =>
+ filterGroups?.flatMap(
+ (group: FeatureFlagGroupType) =>
+ group.properties?.flatMap((property: AnyPropertyFilter) => {
+ if (!isDistinctIdFilter(property)) {
+ return []
+ }
+ if (Array.isArray(property.value)) {
+ return property.value.map((v) => String(v))
+ }
+ return property.value !== null && property.value !== undefined
+ ? [String(property.value)]
+ : []
+ }) || []
+ ) || [],
+ ],
+ getDistinctIdName: [
+ (s) => [s.distinctIdNameCache],
+ (distinctIdNameCache: Record<string, string>) =>
+ (distinctId: string): string => {
+ const name = distinctIdNameCache[distinctId]
+ return name && name !== distinctId ? `${distinctId} (${name})` : distinctId
+ },
+ ],
properties: [
(s) => [s.filterGroups],
(filterGroups: FeatureFlagGroupType[]) => {
@@ -823,10 +915,13 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition
afterMount(({ props, actions, values }) => {
// Load flag keys on mount if there are flag dependencies
if (props.filters) {
- const { flagIds } = values
+ const { flagIds, distinctIds } = values
if (flagIds.length > 0) {
actions.loadAllFlagKeys(flagIds)
}
+ if (distinctIds.length > 0) {
+ actions.loadDistinctIdNames(distinctIds)
+ }
}
if (!props.readOnly) {