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(experiments): metric breakdown ui persist limit change (#85122)

Rodrigo Ilorob31e863184f5
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
index 761ca28f0e9e..0c1483e81e79 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
@@ -87,6 +87,7 @@ interface CollapsibleBreakdownSectionProps {
colors: ReturnType<typeof useChartColors>
scale: ReturnType<typeof useAxisScale>
onRemoveBreakdown: (index: number) => void
+ onBreakdownLimitChange: (breakdownLimit: number) => void
onRetry: () => void
query?: Record<string, any>
handleTooltipMouseEnter: (e: React.MouseEvent, variantResult: ExperimentVariantResult) => void
@@ -106,6 +107,7 @@ function CollapsibleBreakdownSection({
colors,
scale,
onRemoveBreakdown,
+ onBreakdownLimitChange,
onRetry,
query,
handleTooltipMouseEnter,
@@ -170,7 +172,7 @@ function CollapsibleBreakdownSection({
metric={metric}
onRemoveBreakdown={onRemoveBreakdown}
onAttributionChange={() => {}}
- onBreakdownLimitChange={() => {}}
+ onBreakdownLimitChange={onBreakdownLimitChange}
/>
</div>
),
@@ -525,6 +527,7 @@ interface MetricRowGroupProps {
onDeleteMetric?: () => void
onBreakdownChange: (breakdown: Breakdown) => void
onRemoveBreakdown: (index: number) => void
+ onBreakdownLimitChange: (breakdownLimit: number) => void
error?: any
isLoading?: boolean
exposuresLoading?: boolean
@@ -548,6 +551,7 @@ export function MetricRowGroup({
onDeleteMetric,
onBreakdownChange,
onRemoveBreakdown,
+ onBreakdownLimitChange,
error,
isLoading,
exposuresLoading = false,
@@ -899,7 +903,7 @@ export function MetricRowGroup({
isAlternatingRow={isAlternatingRow}
onRemoveBreakdown={onRemoveBreakdown}
onAttributionChange={() => {}}
- onBreakdownLimitChange={() => {}}
+ onBreakdownLimitChange={onBreakdownLimitChange}
/>
)}
</>
@@ -1232,6 +1236,7 @@ export function MetricRowGroup({
colors={colors}
scale={scale}
onRemoveBreakdown={onRemoveBreakdown}
+ onBreakdownLimitChange={onBreakdownLimitChange}
onRetry={handleRetry}
query={debugQuery}
handleTooltipMouseEnter={handleTooltipMouseEnter}
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
index 12940fe30740..d11380f0db8d 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
@@ -67,6 +67,7 @@ export function MetricsTable({
duplicateSharedMetricAsInlineMetric,
updateExperimentMetrics,
updateMetricBreakdown,
+ updateMetricBreakdownLimit,
removeMetricBreakdown,
removeMetric,
removeSharedMetricFromExperiment,
@@ -278,6 +279,13 @@ export function MetricsTable({
removeMetricBreakdown(metric.uuid, index, breakdown)
}}
+ onBreakdownLimitChange={(breakdownLimit) => {
+ if (!metric.uuid) {
+ return
+ }
+
+ updateMetricBreakdownLimit(metric.uuid, breakdownLimit)
+ }}
error={error}
isLoading={isLoading}
exposuresLoading={exposuresLoading}
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 102c791c5f21..627f0238337e 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -1342,6 +1342,54 @@ describe('experimentLogic', () => {
{ property: '$os', type: 'event' },
])
})
+
+ it('should update breakdown limit on inline metric', () => {
+ const testExperiment: Experiment = {
+ ...experiment,
+ metrics: [
+ {
+ uuid: 'test-metric-uuid',
+ metric_type: ExperimentMetricType.MEAN,
+ source: { kind: NodeKind.EventsNode, event: '$pageview' },
+ breakdownFilter: { breakdowns: [{ property: '$browser', type: 'event' }] },
+ },
+ ] as unknown as ExperimentMetric[],
+ }
+
+ logic.actions.setExperiment(testExperiment)
+ logic.actions.updateMetricBreakdownLimit('test-metric-uuid', 10)
+
+ const updatedMetric = logic.values.experiment.metrics[0] as ExperimentMetric
+ expect(updatedMetric.breakdownFilter?.breakdown_limit).toEqual(10)
+ })
+
+ it('should update breakdown limit on shared metric metadata', () => {
+ const testExperiment: Experiment = {
+ ...experiment,
+ saved_metrics: [
+ {
+ id: 1,
+ experiment: experiment.id as number,
+ saved_metric: 123,
+ name: 'Shared Metric',
+ query: {
+ uuid: 'shared-metric-uuid',
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ source: { kind: NodeKind.EventsNode, event: '$pageview' },
+ },
+ metadata: { type: 'primary', breakdowns: [{ property: '$browser', type: 'event' }] },
+ created_at: '2024-01-01T00:00:00Z',
+ } satisfies ExperimentSavedMetric,
+ ],
+ metrics: [],
+ }
+
+ logic.actions.setExperiment(testExperiment)
+ logic.actions.updateMetricBreakdownLimit('shared-metric-uuid', 10)
+
+ expect(logic.values.experiment.saved_metrics[0].metadata.breakdown_limit).toEqual(10)
+ })
})
describe('launchExperiment', () => {
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 84f736484eb8..ccce7aef7900 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -337,7 +337,7 @@ const loadMetrics = async ({
onSetErrors,
}: MetricLoadingConfig): Promise<MetricLoadingSummary> => {
const results: CachedNewExperimentQueryResponse[] = []
- const currentErrors = new Array(metrics.length).fill(null)
+ const currentErrors = Array.from({ length: metrics.length }).fill(null)
let successfulCount = 0
let erroredCount = 0
@@ -468,6 +468,7 @@ const sharedMetricsToExperimentMetrics = (
breakdownFilter: {
...query?.breakdownFilter,
breakdowns: metadata?.breakdowns || [],
+ ...(metadata?.breakdown_limit !== undefined && { breakdown_limit: metadata.breakdown_limit }),
},
}))
@@ -482,6 +483,7 @@ export type ExperimentSavedMetric = {
metadata: {
type: 'primary' | 'secondary'
breakdowns?: Breakdown[]
+ breakdown_limit?: number
}
created_at: string
query: ExperimentMetric
@@ -1313,6 +1315,13 @@ export interface experimentLogicActions {
breakdown: Breakdown
uuid: string
}
+ updateMetricBreakdownLimit: (
+ uuid: string,
+ breakdownLimit: number
+ ) => {
+ breakdownLimit: number
+ uuid: string
+ }
validateFeatureFlag: (featureFlagKey: string) => {
featureFlagKey: string
}
@@ -1709,6 +1718,7 @@ export const experimentLogic = kea<experimentLogicType>([
) => ({ isSecondary, orderedUuids, removedUuids, movedUuids }),
updateMetricBreakdown: (uuid: string, breakdown: Breakdown) => ({ uuid, breakdown }),
removeMetricBreakdown: (uuid: string, index: number, breakdown: Breakdown) => ({ uuid, index, breakdown }),
+ updateMetricBreakdownLimit: (uuid: string, breakdownLimit: number) => ({ uuid, breakdownLimit }),
// METRICS RESULTS
clearMetricsResults: true,
setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),
@@ -2068,6 +2078,79 @@ export const experimentLogic = kea<experimentLogicType>([
[metricsKey]: metrics,
}
},
+ updateMetricBreakdownLimit: (state, { uuid, breakdownLimit }) => {
+ /**
+ * if the uuid is a shared metric, update saved_metrics metadata of the many to many
+ * relationship, so the breakdown limit is exclusive to this experiment
+ */
+ const savedMetrics: ExperimentSavedMetric[] = [...(state?.saved_metrics || [])]
+ const savedMetricIndex = savedMetrics.findIndex(
+ ({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid
+ )
+
+ /**
+ * if saved metric found...
+ */
+ if (savedMetricIndex !== -1) {
+ /**
+ * rebuild the saved metrics with the updated breakdown limit
+ */
+ const savedMetric = savedMetrics[savedMetricIndex]
+ savedMetrics[savedMetricIndex] = {
+ ...savedMetric,
+ metadata: {
+ ...savedMetric.metadata,
+ breakdown_limit: breakdownLimit,
+ },
+ }
+
+ /**
+ * return the experiment state with the updated saved metrics.
+ */
+ return {
+ ...state,
+ saved_metrics: savedMetrics,
+ }
+ }
+
+ /**
+ * figure out if it's a primary or secondary metric
+ */
+ const metricsKey =
+ (state?.metrics || ([] as ExperimentMetric[])).findIndex((m) => m.uuid === uuid) > -1
+ ? 'metrics'
+ : 'metrics_secondary'
+
+ /**
+ * get the metrics group and find the metric index by uuid.
+ * bail if not found
+ */
+ const metrics = [...(state?.[metricsKey] || [])]
+ const targetIndex = metrics.findIndex((m) => m.uuid === uuid)
+ if (targetIndex === -1) {
+ return state
+ }
+
+ /**
+ * reconstruct the metric with the updated breakdown limit
+ */
+ const metric = metrics[targetIndex] as ExperimentMetric
+ metrics[targetIndex] = {
+ ...metric,
+ breakdownFilter: {
+ ...metric.breakdownFilter,
+ breakdown_limit: breakdownLimit,
+ },
+ } as ExperimentMetric
+
+ /**
+ * return the updated experiment state
+ */
+ return {
+ ...state,
+ [metricsKey]: metrics,
+ }
+ },
},
],
experimentMissing: [
@@ -2409,6 +2492,7 @@ export const experimentLogic = kea<experimentLogicType>([
},
loadExperimentSuccess: async ({ experiment, payload }) => {
const duration = experiment?.start_date ? dayjs().diff(experiment.start_date, 'second') : null
+ // eslint-disable-next-line no-unused-expressions
experiment && actions.reportExperimentViewed(experiment, duration)
// Load metrics for launched experiments (will set up auto-refresh after load completes).
@@ -2451,11 +2535,13 @@ export const experimentLogic = kea<experimentLogicType>([
},
changeExperimentStartDate: async ({ startDate }) => {
await asyncActions.updateExperiment({ start_date: startDate, update_feature_flag_params: false })
+ // eslint-disable-next-line no-unused-expressions
values.experiment && eventUsageLogic.actions.reportExperimentStartDateChange(values.experiment, startDate)
actions.refreshExperimentResults(true, 'config_change')
},
changeExperimentEndDate: async ({ endDate }) => {
await asyncActions.updateExperiment({ end_date: endDate, update_feature_flag_params: false })
+ // eslint-disable-next-line no-unused-expressions
values.experiment && eventUsageLogic.actions.reportExperimentEndDateChange(values.experiment, endDate)
actions.refreshExperimentResults(true, 'config_change')
},
@@ -3590,6 +3676,52 @@ export const experimentLogic = kea<experimentLogicType>([
actions.loadSecondaryMetricsResults(true)
}
},
+ updateMetricBreakdownLimit: async ({ uuid }) => {
+ const savedMetrics: ExperimentSavedMetric[] = [...(values.experiment.saved_metrics || [])]
+ const sharedMetric = savedMetrics.find(({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid)
+
+ /**
+ * find if the updated metris is primary
+ */
+ const isPrimary = sharedMetric
+ ? sharedMetric.metadata.type === 'primary'
+ : values.experiment.metrics.some((m) => m.uuid === uuid)
+
+ /**
+ * build the update payload with all experiment metrics
+ */
+ const updatePayload: Partial<Experiment> & { update_feature_flag_params?: boolean } = {
+ metrics: values.experiment.metrics,
+ metrics_secondary: values.experiment.metrics_secondary,
+ update_feature_flag_params: false,
+ }
+
+ /**
+ * for shared metrics, we save the breakdown limit on the many to many relationship metadata
+ */
+ if (sharedMetric) {
+ updatePayload.saved_metrics_ids = savedMetrics.map(({ saved_metric, metadata }) => ({
+ id: saved_metric,
+ metadata,
+ }))
+ }
+
+ /**
+ * guard against failed persist calling recalculations by awaiting the experiment save
+ */
+ await asyncActions.updateExperiment(updatePayload)
+
+ /**
+ * updating a breakdown limit triggers a recalculation.
+ */
+ if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
+ actions.refreshExperimentResults(true, 'config_change')
+ } else if (isPrimary) {
+ actions.loadPrimaryMetricsResults(true)
+ } else {
+ actions.loadSecondaryMetricsResults(true)
+ }
+ },
setVariantExcluded: async ({ variantKey, excluded }, _breakpoint) => {
const current = values.excludedVariants
const next = excluded
@@ -3618,6 +3750,7 @@ export const experimentLogic = kea<experimentLogicType>([
// Re-fetch results since the variant set changed. On the recalculation flow this means a
// fresh recalc; on the legacy flow it's the per-metric loaders. Exposures refresh either way.
if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
+ // eslint-disable-next-line no-unused-expressions
values.experiment &&
experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(
'config_change'
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 2c517bdfa94d..b22f1a0cd525 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -144,7 +144,7 @@ export function ensureIsPercent(value: string | number | undefined): number {
export function percentageDistribution(variantCount: number): number[] {
const basePercentage = Math.floor(100 / variantCount)
- const percentages = new Array(variantCount).fill(basePercentage)
+ const percentages = Array.from<number>({ length: variantCount }).fill(basePercentage)
let remaining = 100 - basePercentage * variantCount
for (let i = 0; remaining > 0; i++, remaining--) {
// try to equally distribute `remaining` across variants
@@ -1202,6 +1202,9 @@ export function getOrderedMetricsWithResults(
breakdownFilter: {
...sharedMetric.query?.breakdownFilter,
breakdowns: sharedMetric.metadata?.breakdowns || [],
+ ...(sharedMetric.metadata?.breakdown_limit !== undefined && {
+ breakdown_limit: sharedMetric.metadata.breakdown_limit,
+ }),
},
})) as ExperimentMetric[]
@@ -1408,6 +1411,9 @@ export const metricResults =
breakdownFilter: {
...sharedMetric.query?.breakdownFilter,
breakdowns: sharedMetric.metadata?.breakdowns || [],
+ ...(sharedMetric.metadata?.breakdown_limit !== undefined && {
+ breakdown_limit: sharedMetric.metadata.breakdown_limit,
+ }),
},
})) as ExperimentMetric[]