: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(feature-flags): surface bucketing distinct ID in test evaluation (#63141)
Gustavo H. Strassburger4ed31c6a8087
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsxindex ae5560f0ee69..ec8ed2e3b5b3 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonBanner, LemonLabel, LemonCalendarSelectInput } from '@posthog/lemon-ui'+import { LemonButton, LemonBanner, LemonLabel, LemonCalendarSelectInput, LemonSelect } from '@posthog/lemon-ui'import { PropertiesTable } from 'lib/components/PropertiesTable/PropertiesTable'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'@@ -48,6 +48,9 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFlaenrichedConditions,hasValidPerson,errorDisplay,+ personDistinctIds,+ hasMultipleDistinctIds,+ bucketingDistinctId,} = useValues(logic)const {@@ -95,7 +98,7 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla// 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)+ setSelectedPerson((person as Partial<PersonType>) ?? null, distinctId)setTestFormData({ distinct_id: distinctId })} else {setSelectedPerson(null)@@ -106,15 +109,10 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFlaplaceholder="Search for a person by name, email, or ID..."allowClearfullWidth+ truncaterenderValue={() => {if (formData.distinct_id) {- return (- <span>- {selectedPerson?.name ||- selectedPerson?.distinct_ids?.[0] ||- formData.distinct_id}- </span>- )+ return <span>{selectedPerson?.name || formData.distinct_id}</span>}return null}}@@ -125,13 +123,43 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFladistinct ID.</p>- {formData.distinct_id && (- <div className="text-xs text-muted space-y-1 p-2 bg-bg-3000 rounded">- <div>- <strong>Distinct ID:</strong> {formData.distinct_id}+ {formData.distinct_id &&+ (hasMultipleDistinctIds ? (+ <div className="space-y-2">+ <LemonLabel>Distinct ID for bucketing</LemonLabel>+ <LemonSelect+ fullWidth+ aria-label="Distinct ID for bucketing"+ truncateText={{ maxWidthClass: 'max-w-full' }}+ value={formData.distinct_id}+ onChange={(distinctId) => {+ if (distinctId) {+ setTestFormData({ distinct_id: distinctId })+ }+ }}+ options={personDistinctIds.map((id) => ({+ value: id,+ label: id,+ tooltip: id,+ }))}+ />+ <LemonBanner type="warning">+ <div className="text-sm">+ This person has {personDistinctIds.length} merged distinct IDs. Rollout and+ variant assignment are computed by hashing the distinct ID, so the result+ can differ depending on which one you pick. At runtime PostHog buckets using+ the distinct ID from the incoming request, which may not be the one selected+ here.+ </div>+ </LemonBanner></div>- </div>- )}+ ) : (+ <div className="text-xs text-muted space-y-1 p-2 bg-bg-3000 rounded">+ <div>+ <strong>Distinct ID:</strong> {formData.distinct_id}+ </div>+ </div>+ ))}</div>{/* Optional Timestamp */}@@ -254,6 +282,19 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla</div></div>+ {/* Distinct ID used for rollout/variant bucketing. Only shown when the+ backend echoes an explicit value — it returns null when a different ID+ was actually bucketed against, and falling back to the requested ID+ here would mislabel which ID drove the result. */}+ {bucketingDistinctId && (+ <div className="space-y-2">+ <LemonLabel>Bucketed using distinct ID</LemonLabel>+ <div className="px-3 py-2 rounded text-sm font-mono bg-bg-light break-all">+ {bucketingDistinctId}+ </div>+ </div>+ )}+{/* Timestamp Warning */}{formData.timestamp && (<LemonBanner type="info" className="mb-4">diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.tsindex 495964405bf4..7bbf11e0185f 100644--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts@@ -220,6 +220,130 @@ describe('featureFlagTestingLogic', () => {})})+ describe('distinct ID bucketing selectors', () => {+ it.each([+ {+ description: 'full person with multiple merged IDs flags as having multiple',+ person: { name: 'Jane Doe', uuid: 'uuid-abc', distinct_ids: ['user-123', 'user-456'] },+ expectedDistinctIds: ['user-123', 'user-456'],+ expectedHasMultiple: true,+ },+ {+ description: 'full person with a single ID does not flag as having multiple',+ person: { name: 'Jane Doe', uuid: 'uuid-abc', distinct_ids: ['user-123'] },+ expectedDistinctIds: ['user-123'],+ expectedHasMultiple: false,+ },+ {+ description: 'partial person (no distinct_ids) yields an empty list before async resolve',+ person: { name: 'Jane Doe' },+ expectedDistinctIds: [],+ expectedHasMultiple: false,+ },+ {+ description: 'no selected person yields an empty list',+ person: null,+ expectedDistinctIds: [],+ expectedHasMultiple: false,+ },+ ])('$description', async ({ person, expectedDistinctIds, expectedHasMultiple }) => {+ await expectLogic(logic, () => {+ logic.actions.setSelectedPerson(person)+ }).toMatchValues({+ personDistinctIds: expectedDistinctIds,+ hasMultipleDistinctIds: expectedHasMultiple,+ })+ })++ it('resolves distinct IDs for a partial person (recent tab) via the persons API', async () => {+ useMocks({+ get: {+ '/api/environments/:team/persons/': () => [+ 200,+ { results: [{ distinct_ids: ['user-123', 'user-456'] }], count: 1 },+ ],+ },+ })++ await expectLogic(logic, () => {+ logic.actions.setSelectedPerson({ name: 'Jane Doe' }, 'user-123')+ })+ .toFinishAllListeners()+ .toMatchValues({+ personDistinctIds: ['user-123', 'user-456'],+ hasMultipleDistinctIds: true,+ })+ })++ it('clears resolved distinct IDs when a new person is selected', async () => {+ useMocks({+ get: {+ '/api/environments/:team/persons/': () => [+ 200,+ { results: [{ distinct_ids: ['user-123', 'user-456'] }], count: 1 },+ ],+ },+ })++ await expectLogic(logic, () => {+ logic.actions.setSelectedPerson({ name: 'Jane Doe' }, 'user-123')+ }).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setSelectedPerson(null)+ }).toMatchValues({ personDistinctIds: [], hasMultipleDistinctIds: false })+ })+ })++ describe('bucketingDistinctId selector', () => {+ const baseResult: Omit<FeatureFlagTestEvaluationResponseApi, 'evaluation_distinct_id'> = {+ flag_key: 'test-flag',+ result: true,+ reason: 'condition_match',+ condition_index: 0,+ payload: null,+ person_properties: {},+ conditions: [],+ }++ it('is null before any evaluation has run', () => {+ expect(logic.values.bucketingDistinctId).toBeNull()+ })++ it.each([+ {+ description: 'returns the backend-reported ID when present',+ evaluation_distinct_id: 'user-123',+ expected: 'user-123',+ },+ {+ description: 'is null when the backend withholds it (a different ID was used)',+ evaluation_distinct_id: null,+ expected: null,+ },+ ])('$description', async ({ evaluation_distinct_id, expected }) => {+ await expectLogic(logic, () => {+ logic.actions.testFlagEvaluationSuccess({+ ...baseResult,+ evaluation_distinct_id,+ })+ }).toMatchValues({ bucketingDistinctId: expected })+ })++ it('resets to null when setTestFormData is dispatched after a successful evaluation', async () => {+ await expectLogic(logic, () => {+ logic.actions.testFlagEvaluationSuccess({+ ...baseResult,+ evaluation_distinct_id: 'user-123',+ })+ }).toMatchValues({ bucketingDistinctId: 'user-123' })++ await expectLogic(logic, () => {+ logic.actions.setTestFormData({ distinct_id: 'user-456' })+ }).toMatchValues({ bucketingDistinctId: null })+ })+ })+describe('hasValidPerson selector', () => {it.each([{ description: 'is true when distinct_id is set', formData: { distinct_id: 'user-123' }, expected: true },diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.tsindex 162c5e8f08ee..bed29330469c 100644--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts@@ -1,7 +1,7 @@-import { actions, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { ApiError } from 'lib/api'+import api, { ApiError } from 'lib/api'import { dayjs, Dayjs } from 'lib/dayjs'import { projectLogic } from 'scenes/projectLogic'@@ -60,11 +60,22 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([setTestError: (error: string | null) => ({ error }),setDatePickerOpen: (open: boolean) => ({ open }),setDatePickerValue: (value: Dayjs | null) => ({ value }),- setSelectedPerson: (person: Partial<PersonType> | null) => ({ person }),+ setSelectedPerson: (person: Partial<PersonType> | null, distinctId?: string) => ({ person, distinctId }),setIncludeTime: (includeTime: boolean) => ({ includeTime }),clearTestForm: true,}),loaders(({ values }) => ({+ resolvedPersonDistinctIds: [+ null as string[] | null,+ {+ resolvePersonDistinctIds: async (distinctId: string) => {+ const response = await api.persons.list({ distinct_id: distinctId })+ return response.results[0]?.distinct_ids ?? []+ },+ setSelectedPerson: () => null,+ clearTestForm: () => null,+ },+ ],testEvaluation: [null as TestResult | null,{@@ -159,7 +170,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([selectedPerson: [null as Partial<PersonType> | null,{- setSelectedPerson: (_, { person }) => person,+ setSelectedPerson: (_, { person }) => person ?? null,clearTestForm: () => null,},],@@ -170,6 +181,18 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([},],}),+ listeners(({ actions, values }) => ({+ setSelectedPerson: ({ person, distinctId }) => {+ // Persons from the recent tab arrive without distinct_ids. Fetch the full+ // person so hasMultipleDistinctIds and the bucketing picker work correctly.+ if (person && !person.distinct_ids?.length) {+ const id = distinctId ?? values.testFormData.distinct_id+ if (id) {+ actions.resolvePersonDistinctIds(id)+ }+ }+ },+ })),selectors({// Get the set of properties used in any conditionusedProperties: [@@ -234,6 +257,30 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([(s) => [s.testFormData],(formData: TestFormData): boolean => Boolean(formData.distinct_id?.trim()),],+ // The distinct IDs known for the selected person. For persons from the Persons+ // tab distinct_ids comes directly from the picker. For partial persons (e.g. the+ // recent tab, which carries name + distinct_id only) we fall back to the async+ // lookup in resolvedPersonDistinctIds, which is null while loading and [] when the+ // person turns out to have only one ID.+ personDistinctIds: [+ (s) => [s.selectedPerson, s.resolvedPersonDistinctIds],+ (person: Partial<PersonType> | null, resolved: string[] | null): string[] =>+ person?.distinct_ids ?? resolved ?? [],+ ],+ // A person merged from multiple distinct IDs can bucket into a different+ // rollout/variant depending on which ID is hashed, so the test result may not+ // match what runtime evaluation produces for the same person.+ hasMultipleDistinctIds: [+ (s) => [s.personDistinctIds],+ (distinctIds: string[]): boolean => distinctIds.length > 1,+ ],+ // The distinct ID the backend reports it bucketed against. Null when the API+ // withholds it to avoid leaking distinct IDs to feature_flag:read-only tokens —+ // we must not fall back to the requested ID, which would mislabel the result.+ bucketingDistinctId: [+ (s) => [s.testResult],+ (result: TestResult | null): string | null => result?.evaluation_distinct_id ?? null,+ ],// Get formatted error display informationerrorDisplay: [(s) => [s.testError],