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): test all merged distinct IDs at once (#69961)

posthog[bot]cac7971da95b
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
index 89299c98b4c2..d7279818ce97 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
@@ -1,17 +1,18 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonBanner, LemonLabel, LemonCalendarSelectInput, LemonSelect } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonCalendarSelectInput, LemonLabel, Tooltip } from '@posthog/lemon-ui'
import { PropertiesTable } from 'lib/components/PropertiesTable/PropertiesTable'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
import type { Dayjs } from 'lib/dayjs'
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { CodeEditor } from 'lib/monaco/CodeEditor'
import type { FeatureFlagType, PersonType } from '~/types'
import { PropertyDefinitionType } from '~/types'
-import type { ConditionAnalysis } from './featureFlagTestingLogic'
+import type { ConditionAnalysis, TestResult } from './featureFlagTestingLogic'
import { featureFlagTestingLogic } from './featureFlagTestingLogic'
const CONDITION_DISPLAY_STYLES = {
@@ -33,16 +34,40 @@ const CONDITION_DISPLAY_STYLES = {
},
} as const
+function formatFlagResult(value: TestResult['result']): string {
+ return String(value)
+}
+
+// A flag outcome as a colored pill: success when the flag is on / a variant was
+// assigned, danger when it evaluated falsy. Used in both the per-ID results table
+// and the single-result detail view so the two read consistently.
+function FlagResultValue({ value }: { value: TestResult['result'] }): JSX.Element {
+ const isEnabled = value !== false && value != null && value !== ''
+ return (
+ <span
+ className={`px-2 py-1 rounded text-sm font-mono ${
+ isEnabled ? 'bg-success-highlight text-success' : 'bg-danger-highlight text-danger'
+ }`}
+ >
+ {formatFlagResult(value)}
+ </span>
+ )
+}
+
export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Element {
const logic = featureFlagTestingLogic({ flagId: featureFlag.id! })
const {
testFormData: formData,
includeTime,
- testResult: result,
+ activeResult: result,
datePickerOpen,
datePickerValue,
- testEvaluationLoading: isLoading,
+ testEvaluationLoading,
+ allEvaluations,
+ allEvaluationsLoading,
+ resultsDiverge,
+ selectedResultDistinctId,
selectedPerson,
usedProperties,
enrichedConditions,
@@ -59,15 +84,31 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla
setDatePickerValue,
setSelectedPerson,
setIncludeTime,
+ setSelectedResultDistinctId,
clearTestForm,
testFlagEvaluation,
+ testAllDistinctIds,
} = useActions(logic)
+ const isLoading = testEvaluationLoading || allEvaluationsLoading
+
const handleSubmit = (): void => {
- testFlagEvaluation({ flagId: featureFlag.id!, formData })
+ if (hasMultipleDistinctIds) {
+ // Evaluate every merged distinct ID in one go so their variants can be
+ // compared side by side, rather than re-running the tool per ID.
+ testAllDistinctIds({ flagId: featureFlag.id!, distinctIds: personDistinctIds, formData })
+ } else {
+ testFlagEvaluation({ flagId: featureFlag.id!, formData })
+ }
}
const hasConditions = !!result?.conditions?.length
+ // The batch row whose detail is currently expanded — the explicit selection, or
+ // the first row when nothing has been clicked yet (matches the activeResult selector).
+ const activeDistinctId = selectedResultDistinctId ?? allEvaluations?.[0]?.distinctId ?? null
+ // The active row's failure reason, when it has one — used to explain why the detail
+ // panel below has nothing to show instead of silently rendering blank.
+ const activeError = allEvaluations?.find((evaluation) => evaluation.distinctId === activeDistinctId)?.error ?? null
return (
<div className="space-y-6">
@@ -127,34 +168,15 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla
{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>
+ <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 is used. Testing evaluates all{' '}
+ {personDistinctIds.length} at once so you can compare them side by side. At
+ runtime PostHog buckets using the distinct ID from the incoming request.
+ </div>
+ </LemonBanner>
) : (
<div className="text-xs text-muted space-y-1 p-2 bg-bg-3000 rounded">
<div>
@@ -236,7 +258,9 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla
onClick={handleSubmit}
disabledReason={!hasValidPerson ? 'Please select a person' : undefined}
>
- Test evaluation
+ {hasMultipleDistinctIds
+ ? `Test all ${personDistinctIds.length} distinct IDs`
+ : 'Test evaluation'}
</LemonButton>
<LemonButton onClick={clearTestForm} disabled={isLoading}>
Clear
@@ -261,149 +285,216 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla
{/* Right Panel - Analysis and Properties */}
<div
- className={`flex-1 bg-bg-light p-6 rounded-lg border ${result ? 'flex flex-col' : 'content-center'}`}
+ className={`flex-1 bg-bg-light p-6 rounded-lg border ${
+ result || allEvaluations ? 'flex flex-col' : 'content-center'
+ }`}
>
- {result ? (
+ {result || allEvaluations ? (
<div className="space-y-6 flex-1 flex flex-col min-h-0">
- {/* Evaluation Result */}
- <div className="space-y-3">
- <h5 className="font-semibold">Evaluation result</h5>
-
- <div className="space-y-2">
- <LemonLabel>Flag result</LemonLabel>
- <div
- className={`px-3 py-2 rounded text-sm font-mono ${
- result.result
- ? 'bg-success-highlight text-success'
- : 'bg-danger-highlight text-danger'
- }`}
- >
- {typeof result.result === 'boolean'
- ? result.result
- ? 'true'
- : 'false'
- : String(result.result)}
- </div>
+ {/* Per-ID results table — shown when a person's merged distinct IDs were
+ evaluated as a batch. Every ID's outcome is visible at once, so
+ divergence between them is obvious without cycling one at a time.
+ Rendered independently of `result`: an errored active row must not
+ hide the successful rows sitting right next to it. */}
+ {allEvaluations && (
+ <div className="space-y-3">
+ <h5 className="font-semibold">Results by distinct ID</h5>
+ {resultsDiverge && (
+ <LemonBanner type="warning">
+ <div className="text-sm">
+ These merged distinct IDs bucket to <strong>different results</strong>.
+ At runtime PostHog buckets using the distinct ID from the incoming
+ request, so which one is used determines the outcome — front-end and
+ back-end calls can land on different variants for the same person.
+ </div>
+ </LemonBanner>
+ )}
+ <LemonTable
+ dataSource={allEvaluations}
+ rowKey="distinctId"
+ size="small"
+ onRow={(record) => ({
+ onClick: () => setSelectedResultDistinctId(record.distinctId),
+ className: 'cursor-pointer',
+ })}
+ rowClassName={(record) =>
+ record.distinctId === activeDistinctId
+ ? 'bg-accent-highlight-secondary'
+ : null
+ }
+ columns={[
+ {
+ title: 'Distinct ID',
+ key: 'distinctId',
+ render: (_, record) => (
+ <span className="font-mono text-xs break-all">
+ {record.distinctId}
+ </span>
+ ),
+ },
+ {
+ title: 'Flag result',
+ key: 'result',
+ render: (_, record) =>
+ record.result ? (
+ <FlagResultValue value={record.result.result} />
+ ) : (
+ <Tooltip title={record.error ?? 'Evaluation failed'}>
+ <span className="text-danger text-xs">
+ Evaluation failed
+ </span>
+ </Tooltip>
+ ),
+ },
+ ]}
+ />
</div>
+ )}
+
+ {result ? (
+ <>
+ {/* Evaluation Result */}
+ <div className="space-y-3">
+ <h5 className="font-semibold">
+ {allEvaluations ? 'Details for selected distinct ID' : 'Evaluation result'}
+ </h5>
- {/* 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 className="space-y-2">
+ <LemonLabel>Flag result</LemonLabel>
+ <div>
+ <FlagResultValue value={result.result} />
+ </div>
</div>
- </div>
- )}
- {/* Timestamp Warning */}
- {formData.timestamp && (
- <LemonBanner type="info" className="mb-4">
- <strong>Historical evaluation:</strong> Both flag conditions and person
- properties reflect their state at the specified timestamp, not current values.
- </LemonBanner>
- )}
+ {/* 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>
+ )}
- {result.payload != null && (
- <div className="space-y-2">
- <LemonLabel>Payload</LemonLabel>
- <div className="px-3 py-2 rounded text-sm font-mono bg-bg-light">
- {JSON.stringify(result.payload, null, 2)}
- </div>
+ {/* Timestamp Warning */}
+ {formData.timestamp && (
+ <LemonBanner type="info" className="mb-4">
+ <strong>Historical evaluation:</strong> Both flag conditions and person
+ properties reflect their state at the specified timestamp, not current
+ values.
+ </LemonBanner>
+ )}
+
+ {result.payload != null && (
+ <div className="space-y-2">
+ <LemonLabel>Payload</LemonLabel>
+ <div className="px-3 py-2 rounded text-sm font-mono bg-bg-light">
+ {JSON.stringify(result.payload, null, 2)}
+ </div>
+ </div>
+ )}
</div>
- )}
- </div>
- {/* Two Column Layout: Conditions and Properties */}
- <div className="grid grid-cols-1 xl:grid-cols-5 gap-6 flex-1 min-h-0">
- {/* Left Column - Condition Analysis */}
- {hasConditions && (
- <div className="space-y-3 xl:col-span-2 flex flex-col min-h-0">
- <LemonLabel>Condition analysis</LemonLabel>
-
- <div className="flex-1 space-y-3 overflow-auto">
- {enrichedConditions.map((condition) => {
- const styles = CONDITION_DISPLAY_STYLES[condition.display.tone]
-
- return (
- <div
- key={condition.index}
- className={`border rounded-lg p-3 break-words ${styles.card}`}
- >
- <div className="flex items-center gap-2 mb-2">
- <h6 className="font-medium text-sm">
- Condition #{condition.index}
- </h6>
- {condition.display.label && (
- <span
- className={`px-2 py-1 rounded text-xs font-mono ${styles.badge}`}
- >
- {condition.display.label}
- </span>
- )}
- {condition.rollout_percentage < 100 && (
- <span className="px-2 py-1 rounded text-xs bg-bg-light text-muted font-mono">
- {condition.rollout_percentage}%
- </span>
- )}
- </div>
-
- <div className="mb-2 text-xs text-muted">
- {condition.explanation}
- </div>
-
- {condition.properties.length > 0 && (
- <div className="space-y-1">
- {condition.properties.map(
- (
- property: ConditionAnalysis['properties'][number],
- idx: number
- ) => (
- <div
- key={`${property.key}-${idx}`}
- className="text-xs text-muted pl-2"
+ {/* Two Column Layout: Conditions and Properties */}
+ <div className="grid grid-cols-1 xl:grid-cols-5 gap-6 flex-1 min-h-0">
+ {/* Left Column - Condition Analysis */}
+ {hasConditions && (
+ <div className="space-y-3 xl:col-span-2 flex flex-col min-h-0">
+ <LemonLabel>Condition analysis</LemonLabel>
+
+ <div className="flex-1 space-y-3 overflow-auto">
+ {enrichedConditions.map((condition) => {
+ const styles = CONDITION_DISPLAY_STYLES[condition.display.tone]
+
+ return (
+ <div
+ key={condition.index}
+ className={`border rounded-lg p-3 break-words ${styles.card}`}
+ >
+ <div className="flex items-center gap-2 mb-2">
+ <h6 className="font-medium text-sm">
+ Condition #{condition.index}
+ </h6>
+ {condition.display.label && (
+ <span
+ className={`px-2 py-1 rounded text-xs font-mono ${styles.badge}`}
>
- • {property.explanation}
- </div>
- )
+ {condition.display.label}
+ </span>
+ )}
+ {condition.rollout_percentage < 100 && (
+ <span className="px-2 py-1 rounded text-xs bg-bg-light text-muted font-mono">
+ {condition.rollout_percentage}%
+ </span>
+ )}
+ </div>
+
+ <div className="mb-2 text-xs text-muted">
+ {condition.explanation}
+ </div>
+
+ {condition.properties.length > 0 && (
+ <div className="space-y-1">
+ {condition.properties.map(
+ (
+ property: ConditionAnalysis['properties'][number],
+ idx: number
+ ) => (
+ <div
+ key={`${property.key}-${idx}`}
+ className="text-xs text-muted pl-2"
+ >
+ • {property.explanation}
+ </div>
+ )
+ )}
+ </div>
)}
</div>
- )}
- </div>
- )
- })}
- </div>
- </div>
- )}
+ )
+ })}
+ </div>
+ </div>
+ )}
- {/* Right Column - Person Properties */}
- <div
- className={`space-y-3 ${
- hasConditions ? 'xl:col-span-3' : 'xl:col-span-5'
- } flex flex-col min-h-0`}
- >
- <div>
- <LemonLabel>
- Person properties {formData.timestamp ? 'at evaluation time' : '(current)'}
- </LemonLabel>
- </div>
+ {/* Right Column - Person Properties */}
+ <div
+ className={`space-y-3 ${
+ hasConditions ? 'xl:col-span-3' : 'xl:col-span-5'
+ } flex flex-col min-h-0`}
+ >
+ <div>
+ <LemonLabel>
+ Person properties{' '}
+ {formData.timestamp ? 'at evaluation time' : '(current)'}
+ </LemonLabel>
+ </div>
- <div className="flex-1 overflow-auto">
- <PropertiesTable
- properties={result.person_properties}
- type={PropertyDefinitionType.Person}
- searchable={true}
- sortProperties={true}
- highlightedKeys={Array.from(usedProperties)}
- highlightVariant="subtle"
- embedded={true}
- />
+ <div className="flex-1 overflow-auto">
+ <PropertiesTable
+ properties={result.person_properties}
+ type={PropertyDefinitionType.Person}
+ searchable={true}
+ sortProperties={true}
+ highlightedKeys={Array.from(usedProperties)}
+ highlightVariant="subtle"
+ embedded={true}
+ />
+ </div>
+ </div>
</div>
- </div>
- </div>
+ </>
+ ) : (
+ <LemonBanner type="error">
+ <div className="text-sm">
+ This distinct ID's evaluation failed{activeError ? `: ${activeError}` : '.'}{' '}
+ Select another row above to see its analysis.
+ </div>
+ </LemonBanner>
+ )}
</div>
) : (
<div className="flex-grow flex items-center justify-center h-64">
diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
index f9a03d2ea330..2969bd9af60a 100644
--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
@@ -477,4 +477,104 @@ describe('featureFlagTestingLogic', () => {
expect(logic.values.testError).toBe(expectedError)
})
})
+
+ describe('batch evaluation across merged distinct IDs', () => {
+ const resultRow = (distinctId: string, result: unknown): FeatureFlagTestEvaluationResponseApi => ({
+ flag_key: 'test-flag',
+ result,
+ reason: 'condition_match',
+ condition_index: 0,
+ payload: null,
+ person_properties: {},
+ evaluation_distinct_id: distinctId,
+ conditions: [],
+ })
+
+ it('evaluates every distinct ID as its own row and isolates a single failing ID', async () => {
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/1/test_evaluation': async ({ request }) => {
+ const body = (await request.json()) as { distinct_id: string }
+ if (body.distinct_id === 'user-bad') {
+ return [404, { detail: 'Person not found for distinct_id: user-bad' }]
+ }
+ return [200, resultRow(body.distinct_id, body.distinct_id === 'user-123' ? 'control' : 'test')]
+ },
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.testAllDistinctIds({
+ flagId: 1,
+ distinctIds: ['user-123', 'user-456', 'user-bad'],
+ formData: { distinct_id: 'user-123', timestamp: '', groups: '' },
+ })
+ }).toDispatchActions(['testAllDistinctIdsSuccess'])
+
+ const rows = logic.values.allEvaluations!
+ expect(rows.map((r) => r.distinctId)).toEqual(['user-123', 'user-456', 'user-bad'])
+ expect(rows[0].result?.result).toBe('control')
+ expect(rows[1].result?.result).toBe('test')
+ // A per-ID API error is captured on its own row rather than failing the whole batch.
+ expect(rows[2].result).toBeNull()
+ expect(rows[2].error).toBeTruthy()
+ expect(logic.values.testError).toBeNull()
+ })
+
+ describe('resultsDiverge selector', () => {
+ it.each([
+ {
+ description: 'true when merged IDs bucket to different results',
+ rows: [resultRow('user-1', 'control'), resultRow('user-2', 'test')],
+ expected: true,
+ },
+ {
+ description: 'false when every ID agrees',
+ rows: [resultRow('user-1', 'control'), resultRow('user-2', 'control')],
+ expected: false,
+ },
+ ])('$description', async ({ rows, expected }) => {
+ await expectLogic(logic, () => {
+ logic.actions.testAllDistinctIdsSuccess(
+ rows.map((result) => ({ distinctId: result.evaluation_distinct_id!, result, error: null }))
+ )
+ }).toMatchValues({ resultsDiverge: expected })
+ })
+
+ it('ignores errored rows so a single failure does not read as divergence', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.testAllDistinctIdsSuccess([
+ { distinctId: 'user-1', result: resultRow('user-1', 'control'), error: null },
+ { distinctId: 'user-2', result: null, error: 'Person not found' },
+ ])
+ }).toMatchValues({ resultsDiverge: false })
+ })
+ })
+
+ describe('activeResult selector', () => {
+ const batchRows = [
+ { distinctId: 'user-1', result: resultRow('user-1', 'control'), error: null },
+ { distinctId: 'user-2', result: resultRow('user-2', 'test'), error: null },
+ ]
+
+ it('falls back to the first batch row before any row is selected', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.testAllDistinctIdsSuccess(batchRows)
+ }).toMatchValues({ activeResult: expect.objectContaining({ result: 'control' }) })
+ })
+
+ it('returns the selected batch row once one is picked', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.testAllDistinctIdsSuccess(batchRows)
+ logic.actions.setSelectedResultDistinctId('user-2')
+ }).toMatchValues({ activeResult: expect.objectContaining({ result: 'test' }) })
+ })
+
+ it('uses the single-ID result when no batch has run', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.testFlagEvaluationSuccess(resultRow('user-1', 'control'))
+ }).toMatchValues({ activeResult: expect.objectContaining({ result: 'control' }) })
+ })
+ })
+ })
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts
index bed29330469c..ad16b0812ee5 100644
--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts
@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'
import api, { ApiError } from 'lib/api'
import { dayjs, Dayjs } from 'lib/dayjs'
+import { ConcurrencyController } from 'lib/utils/concurrencyController'
import { projectLogic } from 'scenes/projectLogic'
import { PersonType } from '~/types'
@@ -25,8 +26,80 @@ export interface TestFormData {
groups: string
}
+// One row of a batch evaluation — how the flag bucketed for a single one of the
+// person's merged distinct IDs. `error` is set (and `result` null) when that ID's
+// individual evaluation failed, so one bad ID doesn't blank the whole table.
+export interface PerDistinctIdEvaluation {
+ distinctId: string
+ result: TestResult | null
+ error: string | null
+}
+
const EMPTY_FORM: TestFormData = { distinct_id: '', timestamp: '', groups: '' }
+// Caps how many merged distinct IDs are evaluated concurrently. test_evaluation is
+// ClickHouse-backed and throttle-gated, so a person with many merged IDs shouldn't
+// turn one button click into an unbounded burst of concurrent requests.
+const TEST_EVALUATION_CONCURRENCY_LIMIT = 6
+const testEvaluationConcurrencyController = new ConcurrencyController(TEST_EVALUATION_CONCURRENCY_LIMIT)
+
+// Build the request body for a single evaluation. Shared by the single-ID and
+// batch paths so groups/timestamp are parsed and validated identically. Throws on
+// invalid groups or timestamp — callers let that fail the loader so the error
+// surfaces once via testError rather than per distinct ID.
+function buildEvaluationRequest(formData: TestFormData, distinctId: string): FeatureFlagTestEvaluationRequestApi {
+ const data: FeatureFlagTestEvaluationRequestApi = {}
+
+ const trimmedDistinctId = distinctId.trim()
+ if (trimmedDistinctId) {
+ data.distinct_id = trimmedDistinctId
+ }
+
+ data.groups = validateAndParseGroups(formData.groups || '')
+
+ if (formData.timestamp?.trim()) {
+ data.timestamp = formData.timestamp.trim()
+
+ // Validate ISO string format with strict parsing
+ const parsedTimestamp = dayjs(data.timestamp, 'YYYY-MM-DDTHH:mm:ss.SSS[Z]', true)
+ if (!parsedTimestamp.isValid()) {
+ throw new Error('Invalid timestamp format')
+ }
+ }
+
+ return data
+}
+
+// Map an evaluation failure to the user-facing message. Shared by the single-ID
+// and batch failure handlers so both surface the same friendly rewrites.
+function evaluationErrorMessage(error: string, errorObject?: unknown): string {
+ const apiError = errorObject as ApiError
+ if (apiError?.detail) {
+ const errorDetail = apiError.detail
+
+ if (errorDetail.includes('Failed to build person properties at specified timestamp')) {
+ return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'
+ }
+
+ if (errorDetail.includes('person') && errorDetail.includes('not found')) {
+ return 'Person not found. This person may not have existed at the selected timestamp.'
+ }
+
+ if (errorDetail.includes('timestamp') || errorDetail.toLowerCase() === 'invalid timestamp') {
+ return 'Invalid timestamp. Please select a valid date and time.'
+ }
+
+ return errorDetail
+ }
+
+ const errorMessage = apiError?.message || error || ''
+ if (errorMessage.includes('Failed to build person properties at specified timestamp')) {
+ return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'
+ }
+
+ return errorMessage || 'An unexpected error occurred while testing the feature flag'
+}
+
function validateAndParseGroups(groups: string): Record<string, any> {
const trimmed = groups.trim()
if (!trimmed) {
@@ -62,6 +135,8 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
setDatePickerValue: (value: Dayjs | null) => ({ value }),
setSelectedPerson: (person: Partial<PersonType> | null, distinctId?: string) => ({ person, distinctId }),
setIncludeTime: (includeTime: boolean) => ({ includeTime }),
+ setSelectedResultDistinctId: (distinctId: string | null) => ({ distinctId }),
+ clearBatchEvaluations: true,
clearTestForm: true,
}),
loaders(({ values }) => ({
@@ -80,28 +155,58 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
null as TestResult | null,
{
testFlagEvaluation: async ({ flagId, formData }: { flagId: number; formData: TestFormData }) => {
- const data: FeatureFlagTestEvaluationRequestApi = {}
-
- if (formData.distinct_id?.trim()) {
- data.distinct_id = formData.distinct_id.trim()
- }
-
- data.groups = validateAndParseGroups(formData.groups || '')
-
- if (formData.timestamp?.trim()) {
- data.timestamp = formData.timestamp.trim()
-
- // Validate ISO string format with strict parsing
- const parsedTimestamp = dayjs(data.timestamp, 'YYYY-MM-DDTHH:mm:ss.SSS[Z]', true)
- if (!parsedTimestamp.isValid()) {
- throw new Error('Invalid timestamp format')
- }
- }
-
+ const data = buildEvaluationRequest(formData, formData.distinct_id || '')
return await featureFlagsTestEvaluationCreate(String(values.currentProjectId), flagId, data)
},
},
],
+ // Batch counterpart to testEvaluation: evaluate every one of a person's merged
+ // distinct IDs in one action so their variants can be shown side by side, instead
+ // of forcing the user to re-run the single-ID path once per ID.
+ allEvaluations: [
+ null as PerDistinctIdEvaluation[] | null,
+ {
+ testAllDistinctIds: async ({
+ flagId,
+ distinctIds,
+ formData,
+ }: {
+ flagId: number
+ distinctIds: string[]
+ formData: TestFormData
+ }) => {
+ // Parse groups/timestamp once up front. A malformed form throws here and
+ // fails the whole batch loudly (one testError) rather than N identical times.
+ const baseData = buildEvaluationRequest(formData, '')
+
+ return await Promise.all(
+ distinctIds.map(async (distinctId): Promise<PerDistinctIdEvaluation> => {
+ try {
+ const result = await testEvaluationConcurrencyController.run({
+ debugTag: `feature-flag-test-evaluation-${distinctId}`,
+ fn: () =>
+ featureFlagsTestEvaluationCreate(String(values.currentProjectId), flagId, {
+ ...baseData,
+ distinct_id: distinctId,
+ }),
+ })
+ return { distinctId, result, error: null }
+ } catch (e) {
+ return { distinctId, result: null, error: evaluationErrorMessage('', e) }
+ }
+ })
+ )
+ },
+ // Reset via a dedicated action rather than reusing other actions as keys.
+ // Every key in a loader map registers a listener that dispatches
+ // `${key}Success`, so listing an action another loader already owns
+ // (setSelectedPerson/clearTestForm) or another loader's trigger
+ // (testFlagEvaluation) would double-dispatch its success action and corrupt
+ // that loader's value. A unique action keeps the reset isolated; listeners
+ // dispatch it on person/form changes.
+ clearBatchEvaluations: () => null,
+ },
+ ],
})),
reducers({
testFormData: [
@@ -116,44 +221,38 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
{
setTestError: (_, { error }: { error: string | null }) => error,
testFlagEvaluation: () => null,
+ testAllDistinctIds: () => null,
clearTestForm: () => null,
- testFlagEvaluationFailure: (_, { error, errorObject }: { error: string; errorObject?: unknown }) => {
- const apiError = errorObject as ApiError
- if (apiError?.detail) {
- const errorDetail = apiError.detail
-
- if (errorDetail.includes('Failed to build person properties at specified timestamp')) {
- return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'
- }
-
- if (errorDetail.includes('person') && errorDetail.includes('not found')) {
- return 'Person not found. This person may not have existed at the selected timestamp.'
- }
-
- if (errorDetail.includes('timestamp') || errorDetail.toLowerCase() === 'invalid timestamp') {
- return 'Invalid timestamp. Please select a valid date and time.'
- }
-
- return errorDetail
- }
-
- const errorMessage = apiError?.message || error || ''
- if (errorMessage.includes('Failed to build person properties at specified timestamp')) {
- return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'
- }
-
- return errorMessage || 'An unexpected error occurred while testing the feature flag'
- },
+ testFlagEvaluationFailure: (_, { error, errorObject }: { error: string; errorObject?: unknown }) =>
+ evaluationErrorMessage(error, errorObject),
+ // A batch failure means the shared form (groups/timestamp) was invalid — the
+ // per-ID API errors are caught inside the loader and shown in the table.
+ testAllDistinctIdsFailure: (_, { error, errorObject }: { error: string; errorObject?: unknown }) =>
+ evaluationErrorMessage(error, errorObject),
},
],
testResult: [
null as TestResult | null,
{
testFlagEvaluationSuccess: (_, { testEvaluation }) => testEvaluation,
+ testAllDistinctIds: () => null,
clearTestForm: () => null,
setTestFormData: () => null,
},
],
+ // Which batch row's detailed condition analysis is expanded in the right panel.
+ // Null falls back to the first row so a batch run always shows some detail.
+ selectedResultDistinctId: [
+ null as string | null,
+ {
+ setSelectedResultDistinctId: (_, { distinctId }) => distinctId,
+ testAllDistinctIds: () => null,
+ testFlagEvaluation: () => null,
+ setTestFormData: () => null,
+ clearTestForm: () => null,
+ setSelectedPerson: () => null,
+ },
+ ],
datePickerOpen: [
false,
{
@@ -183,6 +282,8 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
}),
listeners(({ actions, values }) => ({
setSelectedPerson: ({ person, distinctId }) => {
+ // A different person invalidates any batch table from the previous one.
+ actions.clearBatchEvaluations()
// 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) {
@@ -192,11 +293,51 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
}
}
},
+ // Editing distinct_id/timestamp/groups invalidates prior results, matching how
+ // testResult resets on the same action.
+ setTestFormData: () => {
+ actions.clearBatchEvaluations()
+ },
+ clearTestForm: () => {
+ actions.clearBatchEvaluations()
+ },
})),
selectors({
+ // The result currently driving the detail panel (condition analysis + person
+ // properties). In batch mode it's the selected row (or the first, if none picked);
+ // otherwise it's the single-ID evaluation.
+ activeResult: [
+ (s) => [s.testResult, s.allEvaluations, s.selectedResultDistinctId],
+ (
+ single: TestResult | null,
+ all: PerDistinctIdEvaluation[] | null,
+ selectedId: string | null
+ ): TestResult | null => {
+ if (all?.length) {
+ const selected = selectedId ? all.find((e) => e.distinctId === selectedId) : undefined
+ return (selected ?? all[0]).result
+ }
+ return single
+ },
+ ],
+ // True when the person's merged distinct IDs don't all bucket to the same result —
+ // the exact divergence that makes runtime evaluation ambiguous. Errored rows are
+ // ignored so a single failed ID doesn't read as a disagreement.
+ resultsDiverge: [
+ (s) => [s.allEvaluations],
+ (all: PerDistinctIdEvaluation[] | null): boolean => {
+ if (!all?.length) {
+ return false
+ }
+ const outcomes = new Set(
+ all.filter((e) => e.result).map((e) => JSON.stringify(e.result?.result ?? null))
+ )
+ return outcomes.size > 1
+ },
+ ],
// Get the set of properties used in any condition
usedProperties: [
- (s) => [s.testResult],
+ (s) => [s.activeResult],
(result: TestResult | null): Set<string> => {
const used = new Set<string>()
if (result?.conditions) {
@@ -211,7 +352,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
],
// Get enriched conditions with derived flags for UI rendering
enrichedConditions: [
- (s) => [s.testResult],
+ (s) => [s.activeResult],
(result: TestResult | null) => {
if (!result?.conditions) {
return []
@@ -278,7 +419,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
// 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],
+ (s) => [s.activeResult],
(result: TestResult | null): string | null => result?.evaluation_distinct_id ?? null,
],
// Get formatted error display information