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.

fix(experiments): render metrics the ordering array does not list (#107211)

Anders0b3195516648
diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx
index ed8ade40cbd6..4adef7139cd2 100644
--- a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx
@@ -9,7 +9,7 @@ import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { experimentLogic } from 'scenes/experiments/experimentLogic'
+import { experimentLogic, getSectionMetricUuids } from 'scenes/experiments/experimentLogic'
import { experimentMetricsLogic } from 'scenes/experiments/experimentMetricsLogic'
import { isMetricThresholdCueVisible } from 'scenes/experiments/ExperimentMetricThreshold'
import {
@@ -237,8 +237,9 @@ export const MetricHeader = ({
const metricUuid = metric.uuid
const sectionUuids =
(isPrimaryMetric ? experiment.primary_metrics_ordered_uuids : experiment.secondary_metrics_ordered_uuids) ?? []
- // An experiment still has to measure something, so the last primary metric can't leave.
- const isLastPrimaryMetric = isPrimaryMetric && sectionUuids.length <= 1
+ // An experiment still has to measure something, so the last primary metric can't leave. Counted
+ // from the metrics themselves, because the ordering array is a display hint that can hold stale uuids.
+ const isLastPrimaryMetric = isPrimaryMetric && getSectionMetricUuids(experiment, false).length <= 1
const handleMoveSection = (): void => {
// The menu item only renders when the metric has a uuid.
diff --git a/frontend/src/scenes/experiments/activity-descriptions/experimentChangeDescription.tsx b/frontend/src/scenes/experiments/activity-descriptions/experimentChangeDescription.tsx
index 5b2680d3f959..1d4b54d5c198 100644
--- a/frontend/src/scenes/experiments/activity-descriptions/experimentChangeDescription.tsx
+++ b/frontend/src/scenes/experiments/activity-descriptions/experimentChangeDescription.tsx
@@ -108,17 +108,19 @@ function describeExcludedVariantsChange(before: string[] | undefined, after: str
}
/**
- * Detect a pure metric reorder. Returns the description only when the two
- * arrays contain the same set of UUIDs in a different order — additions,
- * removals, and swaps are described by the `metrics` field matcher instead.
+ * Detect a metric reorder. The ordering array is a display hint, so an add or remove can leave it
+ * out of sync with the metrics, and the next drag rewrites it from the metrics on screen. Without a
+ * move, that rewrite keeps the surviving uuids in their old relative order and appends the newly
+ * listed ones, so a diff of that shape is left to the `metrics` field matcher. Repeats are ignored
+ * because display order ignores them too.
*/
const describeMetricReorder = (before: unknown, after: unknown, description: string): string | null => {
- const b = (before as string[] | null) ?? []
- const a = (after as string[] | null) ?? []
- if (equal(b, a) || !equal([...b].sort(), [...a].sort())) {
- return null
- }
- return description
+ const b = [...new Set((before as string[] | null) ?? [])]
+ const a = [...new Set((after as string[] | null) ?? [])]
+ const bSet = new Set(b)
+ const aSet = new Set(a)
+ const membershipOnlyRewrite = [...b.filter((uuid) => aSet.has(uuid)), ...a.filter((uuid) => !bSet.has(uuid))]
+ return equal(membershipOnlyRewrite, a) ? null : description
}
export const getExperimentChangeDescription = (
diff --git a/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsx b/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsx
index e6ead855df1b..b63993d51eec 100644
--- a/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsx
+++ b/frontend/src/scenes/experiments/experimentActivityDescriber.test.tsx
@@ -121,7 +121,44 @@ describe('experimentActivityDescriber', () => {
expect(text).not.toContain('shared metric')
})
- it('does not describe a reorder when the same UUIDs are passed as before/after', () => {
+ it.each([
+ {
+ name: 'the same order',
+ before: ['uuid-a', 'uuid-b'],
+ after: ['uuid-a', 'uuid-b'],
+ described: false,
+ },
+ {
+ name: 'a metric removed without moving the rest',
+ before: ['uuid-a', 'uuid-b', 'uuid-c'],
+ after: ['uuid-a', 'uuid-b'],
+ described: false,
+ },
+ {
+ name: 'a metric added without moving the rest',
+ before: ['uuid-a', 'uuid-b'],
+ after: ['uuid-a', 'uuid-b', 'uuid-c'],
+ described: false,
+ },
+ {
+ name: 'a reorder whose before value still lists a removed metric',
+ before: ['uuid-a', 'uuid-b', 'uuid-c'],
+ after: ['uuid-b', 'uuid-a'],
+ described: true,
+ },
+ {
+ name: 'a metric the array never listed dragged ahead of a listed one',
+ before: ['uuid-a'],
+ after: ['uuid-b', 'uuid-a'],
+ described: true,
+ },
+ {
+ name: 'repeated entries dropped without moving anything',
+ before: ['uuid-a', 'uuid-a', 'uuid-b'],
+ after: ['uuid-a', 'uuid-b'],
+ described: false,
+ },
+ ])('$name: reorder described=$described', ({ before, after, described }) => {
const result = experimentActivityDescriber(
baseLogItem({
activity: 'updated',
@@ -132,8 +169,8 @@ describe('experimentActivityDescriber', () => {
type: ActivityScope.EXPERIMENT,
action: 'changed',
field: 'primary_metrics_ordered_uuids',
- before: ['uuid-a', 'uuid-b'],
- after: ['uuid-a', 'uuid-b'],
+ before,
+ after,
},
],
merge: null,
@@ -141,7 +178,7 @@ describe('experimentActivityDescriber', () => {
},
})
)
- expect(textOf(result)).not.toContain('reordered')
+ expect(textOf(result).includes('reordered')).toBe(described)
})
})
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 8aa434b5e933..3a3df934fdbc 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -22,7 +22,7 @@ import {
import { initKeaTests } from '~/test/init'
import { Experiment, MultivariateFlagVariant } from '~/types'
-import { ExperimentSavedMetric, ExperimentWarning, experimentLogic, getDisplayOrderedIndices } from './experimentLogic'
+import { ExperimentSavedMetric, ExperimentWarning, experimentLogic } from './experimentLogic'
jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
lemonToast: {
@@ -2535,30 +2535,6 @@ describe('experimentLogic', () => {
})
})
- describe('getDisplayOrderedIndices', () => {
- it.each([
- ['null orderedUuids — identity order', [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }], null, [0, 1, 2]],
- ['undefined orderedUuids — identity order', [{ uuid: 'a' }, { uuid: 'b' }], undefined, [0, 1]],
- ['empty orderedUuids — identity order', [{ uuid: 'a' }, { uuid: 'b' }], [], [0, 1]],
- ['reorders by orderedUuids', [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }], ['c', 'a', 'b'], [2, 0, 1]],
- [
- 'appends missing metrics at end',
- [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }, { uuid: 'd' }],
- ['c', 'a'],
- [2, 0, 1, 3],
- ],
- ['ignores uuids not in metrics', [{ uuid: 'a' }, { uuid: 'b' }], ['x', 'b', 'y', 'a'], [1, 0]],
- ['handles metrics without uuids', [{ uuid: 'a' }, {}, { uuid: 'c' }], ['c', 'a'], [2, 0, 1]],
- ])('%s', (_desc, metrics, orderedUuids, expected) => {
- expect(getDisplayOrderedIndices(metrics, orderedUuids)).toEqual(expected)
- })
-
- it('returns all indices exactly once', () => {
- const metrics = [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }, { uuid: 'd' }, { uuid: 'e' }]
- expect(getDisplayOrderedIndices(metrics, ['d', 'b']).sort()).toEqual([0, 1, 2, 3, 4])
- })
- })
-
describe('excluded variants', () => {
it('excludedVariants selector reads the excluded_variants column', async () => {
await expectLogic(logic, () => {
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 3c37226f8fd8..82fbedb58301 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -127,6 +127,7 @@ import { SharedMetric } from './SharedMetrics/sharedMetricLogic'
import { sharedMetricsLogic } from './SharedMetrics/sharedMetricsLogic'
import {
type ExperimentUpdatePayload,
+ getDisplayOrderedIndices,
getExperimentVariants,
getOrderedMetricsWithResults,
initializeMetricOrdering,
@@ -265,48 +266,6 @@ function parseMetricErrorDetail(error: any): { detail: any; hasDiagnostics: bool
}
}
-/**
- * Returns metric indices in display order. Metrics whose UUID appears in
- * orderedUuids come first (in that order), followed by any remaining metrics
- * in their original array position. Each entry is the original index into the
- * metrics array so callers can write results to the correct positional slot.
- */
-export function getDisplayOrderedIndices(
- metrics: { uuid?: string }[],
- orderedUuids: string[] | null | undefined
-): number[] {
- if (!orderedUuids || orderedUuids.length === 0) {
- return metrics.map((_, i) => i)
- }
-
- const uuidToIndex = new Map<string, number>()
- for (let i = 0; i < metrics.length; i++) {
- const uuid = metrics[i].uuid
- if (uuid) {
- uuidToIndex.set(uuid, i)
- }
- }
-
- const ordered: number[] = []
- const seen = new Set<number>()
-
- for (const uuid of orderedUuids) {
- const idx = uuidToIndex.get(uuid)
- if (idx !== undefined && !seen.has(idx)) {
- ordered.push(idx)
- seen.add(idx)
- }
- }
-
- for (let i = 0; i < metrics.length; i++) {
- if (!seen.has(i)) {
- ordered.push(i)
- }
- }
-
- return ordered
-}
-
/**
* Positional uuid list for one section's results arrays: inline metrics first,
* then shared metrics of that type — mirroring how loadPrimaryMetricsResults /
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index b3c154c0905b..ac3de993af64 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -29,6 +29,7 @@ import {
featureFlagEligibleForExperiment,
filterToExposureConfig,
getBaselineVariantKey,
+ getDisplayOrderedIndices,
getEventCountQuery,
getFunnelDropoffReason,
getOrderedMetricsWithResults,
@@ -1096,6 +1097,30 @@ describe('getOrderedMetricsWithResults', () => {
})
})
+describe('getDisplayOrderedIndices', () => {
+ it.each([
+ ['null orderedUuids — identity order', [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }], null, [0, 1, 2]],
+ ['undefined orderedUuids — identity order', [{ uuid: 'a' }, { uuid: 'b' }], undefined, [0, 1]],
+ ['empty orderedUuids — identity order', [{ uuid: 'a' }, { uuid: 'b' }], [], [0, 1]],
+ ['reorders by orderedUuids', [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }], ['c', 'a', 'b'], [2, 0, 1]],
+ [
+ 'appends missing metrics at end',
+ [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }, { uuid: 'd' }],
+ ['c', 'a'],
+ [2, 0, 1, 3],
+ ],
+ ['ignores uuids not in metrics', [{ uuid: 'a' }, { uuid: 'b' }], ['x', 'b', 'y', 'a'], [1, 0]],
+ ['handles metrics without uuids', [{ uuid: 'a' }, {}, { uuid: 'c' }], ['c', 'a'], [2, 0, 1]],
+ ])('%s', (_desc, metrics, orderedUuids, expected) => {
+ expect(getDisplayOrderedIndices(metrics, orderedUuids)).toEqual(expected)
+ })
+
+ it('returns all indices exactly once', () => {
+ const metrics = [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'c' }, { uuid: 'd' }, { uuid: 'e' }]
+ expect(getDisplayOrderedIndices(metrics, ['d', 'b']).sort()).toEqual([0, 1, 2, 3, 4])
+ })
+})
+
describe('metricResults', () => {
const baseExperiment = {
...experimentJson,
@@ -1121,14 +1146,34 @@ describe('metricResults', () => {
expect(metricResults(baseExperiment)([], [], 'primary')).toEqual([])
})
- it('returns an empty array when no ordered uuids reference existing metrics', () => {
+ it.each([
+ {
+ name: 'a null ordering renders the stored order',
+ ordering: null,
+ expectedIndexes: [0, 1, 2],
+ },
+ {
+ name: 'an ordering with a stale uuid and a missing metric renders the listed metric first, the rest after',
+ ordering: ['metric-3', 'stale-uuid'],
+ expectedIndexes: [2, 0, 1],
+ },
+ ])('$name', ({ ordering, expectedIndexes }) => {
const experiment = {
...baseExperiment,
- metrics: [inlineMetric('metric-1', 'test')],
- // ordered uuids point at a metric that no longer exists
- primary_metrics_ordered_uuids: ['stale-uuid'],
+ metrics: [inlineMetric('metric-1', 'a'), inlineMetric('metric-2', 'b'), inlineMetric('metric-3', 'c')],
+ primary_metrics_ordered_uuids: ordering,
}
- expect(metricResults(experiment)([mockResult({ result: 'data' })], [null], 'primary')).toEqual([])
+ const results = [
+ mockResult({ result: 'data1' }),
+ mockResult({ result: 'data2' }),
+ mockResult({ result: 'data3' }),
+ ]
+
+ const ordered = metricResults(experiment)(results, [null, null, null], 'primary')
+
+ expect(ordered.map((o) => o.metricIndex)).toEqual(expectedIndexes)
+ // Results stay paired with their metric by original position, whatever the display order.
+ expect(ordered.map((o) => o.result)).toEqual(expectedIndexes.map((index) => results[index]))
})
it('zips inline metrics with their results and errors', () => {
@@ -1228,7 +1273,7 @@ describe('metricResults', () => {
expect(zip([mockResult({ r: 2 })], [null], 'secondary').map((o) => o.metric.uuid)).toEqual(['s-uuid'])
})
- it('drops metrics that have no uuid', () => {
+ it('keeps a metric without a uuid, after the ordered ones', () => {
const experiment = {
...baseExperiment,
metrics: [
@@ -1244,11 +1289,9 @@ describe('metricResults', () => {
'primary'
)
- expect(ordered).toHaveLength(1)
- expect(ordered[0].metric.uuid).toBe('metric-2')
- // metric-2 is at original index 1, so it picks results[1]
- expect(ordered[0].result).toEqual({ result: 'data2' })
- expect(ordered[0].metricIndex).toBe(1)
+ expect(ordered.map((o) => o.metric.uuid)).toEqual(['metric-2', undefined])
+ expect(ordered.map((o) => o.result)).toEqual([{ result: 'data2' }, { result: 'data1' }])
+ expect(ordered.map((o) => o.metricIndex)).toEqual([1, 0])
})
it('yields undefined result/error when the arrays are shorter than the metric list', () => {
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 25bef557fccd..d5a58de5211e 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -1005,6 +1005,52 @@ export function initializeMetricOrdering(experiment: Experiment): Experiment {
return newExperiment
}
+/**
+ * Returns metric indices in display order. Metrics whose UUID appears in
+ * orderedUuids come first (in that order), followed by any remaining metrics
+ * in their original array position. Each entry is the original index into the
+ * metrics array so callers can write results to the correct positional slot.
+ *
+ * The ordering array is a display hint, not a membership list. An entry that matches no
+ * metric is ignored, and a metric the array does not list still renders after the listed
+ * ones. Filtering by the array instead would hide any metric whose uuid never reached it.
+ */
+export function getDisplayOrderedIndices(
+ metrics: { uuid?: string }[],
+ orderedUuids: string[] | null | undefined
+): number[] {
+ if (!orderedUuids || orderedUuids.length === 0) {
+ return metrics.map((_, i) => i)
+ }
+
+ const uuidToIndex = new Map<string, number>()
+ for (let i = 0; i < metrics.length; i++) {
+ const uuid = metrics[i].uuid
+ if (uuid) {
+ uuidToIndex.set(uuid, i)
+ }
+ }
+
+ const ordered: number[] = []
+ const seen = new Set<number>()
+
+ for (const uuid of orderedUuids) {
+ const idx = uuidToIndex.get(uuid)
+ if (idx !== undefined && !seen.has(idx)) {
+ ordered.push(idx)
+ seen.add(idx)
+ }
+ }
+
+ for (let i = 0; i < metrics.length; i++) {
+ if (!seen.has(i)) {
+ ordered.push(i)
+ }
+ }
+
+ return ordered
+}
+
/**
* Reshape a saved/shared metric into the inline ExperimentMetric shape, merging the
* per-experiment link metadata (breakdown attribution, breakdowns) into the query.
@@ -1029,75 +1075,6 @@ function enrichSharedMetric(sharedMetric: Experiment['saved_metrics'][number]):
} as ExperimentMetric
}
-/**
- * Maps metrics to their results and errors in the correct display order
- * This handles the complex logic of:
- * 1. Mapping results by index to original metrics array (including shared metrics)
- * 2. Enriching shared metrics with metadata, including breakdowns
- * 3. Reordering everything according to the ordered UUIDs
- */
-export function getOrderedMetricsWithResults(
- experiment: Experiment,
- primaryMetricsResults: CachedNewExperimentQueryResponse[],
- primaryMetricsResultsErrors: any[],
- secondaryMetricsResults: CachedNewExperimentQueryResponse[],
- secondaryMetricsResultsErrors: any[],
- isSecondary: boolean
-): Array<{
- metric: ExperimentMetric
- result: any
- error: any
- displayIndex: number
- metricIndex: number
-}> {
- const metricType = isSecondary ? 'secondary' : 'primary'
- const results = isSecondary ? secondaryMetricsResults : primaryMetricsResults
- const errors = isSecondary ? secondaryMetricsResultsErrors : primaryMetricsResultsErrors
-
- // Build enriched metrics in original order (same order as results arrays)
- const regularMetrics = isSecondary
- ? ((experiment.metrics_secondary || []) as ExperimentMetric[])
- : ((experiment.metrics || []) as ExperimentMetric[])
-
- const enrichedSharedMetrics = (experiment.saved_metrics || [])
- .filter((sharedMetric) => sharedMetric.metadata?.type === metricType)
- .map(enrichSharedMetric)
-
- const allMetrics = [...regularMetrics, ...enrichedSharedMetrics]
-
- // Create UUID maps in one pass
- const resultsMap = new Map()
- const errorsMap = new Map()
- const metricsMap = new Map()
- const originalIndexMap = new Map()
-
- allMetrics.forEach((metric: any, index) => {
- const uuid = metric.uuid || metric.query?.uuid
- if (uuid) {
- resultsMap.set(uuid, results[index])
- errorsMap.set(uuid, errors[index])
- metricsMap.set(uuid, metric)
- originalIndexMap.set(uuid, index) // Track original position for retry
- }
- })
-
- // Get display order and map to final result
- const orderedUuids = isSecondary
- ? experiment.secondary_metrics_ordered_uuids || []
- : experiment.primary_metrics_ordered_uuids || []
-
- return orderedUuids
- .map((uuid) => metricsMap.get(uuid))
- .filter(Boolean)
- .map((metric: ExperimentMetric, index: number) => ({
- metric,
- result: resultsMap.get(metric.uuid),
- error: errorsMap.get(metric.uuid),
- displayIndex: index,
- metricIndex: originalIndexMap.get(metric.uuid) ?? index, // Original position for retry
- }))
-}
-
export type MetricWithResult = {
metric: ExperimentMetric
result: CachedNewExperimentQueryResponse | undefined
@@ -1251,14 +1228,14 @@ export function toExperimentWritePayload<T extends Pick<Experiment, 'feature_fla
/**
* Pure zip of one metric type (`primary` | `secondary`) with its results and errors, in display order.
- * Same shaping as {@link getOrderedMetricsWithResults} but curried over the experiment, so a caller can
- * bind it once per experiment instance and reuse it for both primary and secondary:
+ * Curried over the experiment, so a caller can bind it once per experiment instance and reuse it for
+ * both primary and secondary:
*
* const zip = metricResults(experiment)
* const primary = zip(primaryResults, primaryErrors, 'primary')
* const secondary = zip(secondaryResults, secondaryErrors, 'secondary')
*
- * Used by the recalculation flow; the legacy per-metric path keeps using getOrderedMetricsWithResults.
+ * Results and errors are positional over `[...inline, ...shared]`, the layout the loaders write to.
*/
export const metricResults =
(experiment: Experiment) =>
@@ -1275,32 +1252,38 @@ export const metricResults =
.filter((sharedMetric) => sharedMetric.metadata?.type === type)
.map(enrichSharedMetric)
- /**
- * Merge inline + shared metrics, dropping any without a uuid (defensive). One entry per metric
- * carries everything the output row needs, keyed by uuid for the ordering pass below.
- */
- const byUuid = new Map(
- [...regularMetrics, ...sharedMetrics]
- .map((metric, index) => ({ metric, result: results[index], error: errors[index], index }))
- .filter((entry): entry is { metric: ExperimentMetric & { uuid: string } } & typeof entry =>
- Boolean(entry.metric.uuid)
- )
- .map((entry) => [entry.metric.uuid, entry])
- )
-
+ const allMetrics = [...regularMetrics, ...sharedMetrics]
const orderedUuids =
- type === 'secondary'
- ? experiment.secondary_metrics_ordered_uuids || []
- : experiment.primary_metrics_ordered_uuids || []
-
- return orderedUuids
- .map((uuid) => byUuid.get(uuid))
- .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry))
- .map(({ metric, result, error, index }, displayIndex) => ({
- metric,
- result,
- error,
- displayIndex,
- metricIndex: index,
- }))
+ type === 'secondary' ? experiment.secondary_metrics_ordered_uuids : experiment.primary_metrics_ordered_uuids
+
+ return getDisplayOrderedIndices(allMetrics, orderedUuids).map((index, displayIndex) => ({
+ metric: allMetrics[index],
+ result: results[index],
+ error: errors[index],
+ displayIndex,
+ metricIndex: index,
+ }))
}
+
+/**
+ * {@link metricResults} over both sections' arrays, picking one. Kept for the legacy per-metric
+ * results path and its selectors.
+ */
+export function getOrderedMetricsWithResults(
+ experiment: Experiment,
+ primaryMetricsResults: CachedNewExperimentQueryResponse[],
+ primaryMetricsResultsErrors: any[],
+ secondaryMetricsResults: CachedNewExperimentQueryResponse[],
+ secondaryMetricsResultsErrors: any[],
+ isSecondary: boolean
+): Array<{
+ metric: ExperimentMetric
+ result: any
+ error: any
+ displayIndex: number
+ metricIndex: number
+}> {
+ return isSecondary
+ ? metricResults(experiment)(secondaryMetricsResults, secondaryMetricsResultsErrors, 'secondary')
+ : metricResults(experiment)(primaryMetricsResults, primaryMetricsResultsErrors, 'primary')
+}
diff --git a/products/experiments/backend/experiment_summary_data_service.py b/products/experiments/backend/experiment_summary_data_service.py
index 8f41b7e7d44f..26576ba401b4 100644
--- a/products/experiments/backend/experiment_summary_data_service.py
+++ b/products/experiments/backend/experiment_summary_data_service.py
@@ -37,7 +37,7 @@ from products.experiments.backend.hogql_queries.experiment_exposures_query_runne
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
from products.experiments.backend.metric_utils import get_default_metric_title
-from products.experiments.backend.models.experiment import Experiment, get_experiment_rule
+from products.experiments.backend.models.experiment import Experiment, get_experiment_rule, metric_display_rank
@dataclass
@@ -131,18 +131,6 @@ def is_incomplete_response(result: Any) -> TypeIs[CacheMissResponse | QueryStatu
return isinstance(result, (CacheMissResponse, QueryStatusResponse))
-def order_metrics_by_uuid(metrics: list[dict], ordered_uuids: list | None) -> list[dict]:
- """
- Apply the UI's display order so metric numbering in the AI summary matches the
- metrics list in the app. Metrics missing from the ordering keep their relative
- position at the end.
- """
- if not ordered_uuids:
- return metrics
- position = {uuid: index for index, uuid in enumerate(ordered_uuids)}
- return sorted(metrics, key=lambda metric: position.get(metric.get("uuid"), len(position)))
-
-
class ExperimentSummaryDataService:
def __init__(self, team, user):
self._team = team
@@ -304,8 +292,11 @@ class ExperimentSummaryDataService:
else:
secondary_metrics.append(query)
- primary_metrics = order_metrics_by_uuid(primary_metrics, experiment.primary_metrics_ordered_uuids)
- secondary_metrics = order_metrics_by_uuid(secondary_metrics, experiment.secondary_metrics_ordered_uuids)
+ # Number metrics in the UI's display order so "Metric 2" in the summary is the second row in the app.
+ primary_rank = metric_display_rank(experiment.primary_metrics_ordered_uuids)
+ secondary_rank = metric_display_rank(experiment.secondary_metrics_ordered_uuids)
+ primary_metrics.sort(key=lambda metric: primary_rank(metric.get("uuid", "")))
+ secondary_metrics.sort(key=lambda metric: secondary_rank(metric.get("uuid", "")))
omitted_metric_count = max(0, len(primary_metrics) - MAX_METRICS_TO_SUMMARIZE) + max(
0, len(secondary_metrics) - MAX_METRICS_TO_SUMMARIZE
diff --git a/products/experiments/backend/setup_context.py b/products/experiments/backend/setup_context.py
index 21087a99e8c3..bb70b6a7f6d7 100644
--- a/products/experiments/backend/setup_context.py
+++ b/products/experiments/backend/setup_context.py
@@ -65,6 +65,7 @@ from products.experiments.backend.models.experiment import (
ExperimentMetricResult,
ExperimentSavedMetric,
ExperimentToSavedMetric,
+ metric_display_rank,
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.temporal.metric_resolution import is_scheduled_metric
@@ -1062,9 +1063,9 @@ def _outcome_metric(experiment: Experiment) -> OutcomeMetric | None:
]
if is_scheduled_metric(metric)
]
- position = {uuid: index for index, uuid in enumerate(experiment.primary_metrics_ordered_uuids or [])}
+ rank = metric_display_rank(experiment.primary_metrics_ordered_uuids)
# Stable, so a metric the experiment does not order keeps its declared place behind the ordered ones.
- ordered = sorted(candidates, key=lambda candidate: position.get(candidate.uuid, len(position)))
+ ordered = sorted(candidates, key=lambda candidate: rank(candidate.uuid))
for candidate in ordered:
if candidate.metric_type in EXPOSURE_SHAPED_METRIC_TYPES:
return candidate
diff --git a/products/experiments/backend/test/test_experiment_summary_tool.py b/products/experiments/backend/test/test_experiment_summary_tool.py
index abfeaf23ce9f..d8a4a8589e41 100644
--- a/products/experiments/backend/test/test_experiment_summary_tool.py
+++ b/products/experiments/backend/test/test_experiment_summary_tool.py
@@ -449,8 +449,9 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):
"name": "Signup conversion",
}
]
- # UI display order puts the saved primary metric first
- experiment.primary_metrics_ordered_uuids = ["saved-primary-uuid", "inline-primary-uuid"]
+ # UI display order puts the saved primary metric first. The inline metric is left out on
+ # purpose: the ordering is a display hint, and an unlisted metric is still summarized, last.
+ experiment.primary_metrics_ordered_uuids = ["saved-primary-uuid"]
await experiment.asave(update_fields=["metrics", "metrics_secondary", "primary_metrics_ordered_uuids"])
# Add 1 saved primary + 1 saved secondary
diff --git a/products/experiments/backend/test/test_setup_context.py b/products/experiments/backend/test/test_setup_context.py
index 929456a0424c..060222b3db53 100644
--- a/products/experiments/backend/test/test_setup_context.py
+++ b/products/experiments/backend/test/test_setup_context.py
@@ -1011,12 +1011,13 @@ class TestPostgresSections(APIBaseTest):
def test_the_outcome_describes_a_primary_metric_whose_samples_are_exposures(self) -> None:
now = timezone.now()
- # Declared metric-z first, but ordered so the results page leads with metric-a.
+ # Declared metric-z first, but ordered so the results page leads with metric-a. metric-z is
+ # left out of the ordering on purpose: an unlisted metric ranks last, it does not disappear.
ordered = self._experiment(
"ordered",
start_date=now - timedelta(days=10),
metrics=[_mean_metric("metric-z"), _mean_metric("metric-a")],
- primary_metrics_ordered_uuids=["metric-a", "metric-z"],
+ primary_metrics_ordered_uuids=["metric-a"],
days_ago=1,
)
# A second experiment whose first primary is metric-z, so metric-z rows for `ordered` come
diff --git a/products/experiments/frontend/legacy/legacyExperimentLogic.tsx b/products/experiments/frontend/legacy/legacyExperimentLogic.tsx
index 781fb4a43f52..3d4524797b01 100644
--- a/products/experiments/frontend/legacy/legacyExperimentLogic.tsx
+++ b/products/experiments/frontend/legacy/legacyExperimentLogic.tsx
@@ -4,7 +4,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { runWithLimit } from 'scenes/dashboard/dashboardUtils'
import { modalsLogic } from 'scenes/experiments/modalsLogic'
-import { isLegacyExperimentQuery, isLegacySharedMetric } from 'scenes/experiments/utils'
+import { getDisplayOrderedIndices, isLegacyExperimentQuery, isLegacySharedMetric } from 'scenes/experiments/utils'
import { teamLogic } from 'scenes/teamLogic'
import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
@@ -114,48 +114,6 @@ function parseMetricErrorDetail(error: any): { detail: any; hasDiagnostics: bool
}
}
-/**
- * Returns metric indices in display order. Metrics whose UUID appears in
- * orderedUuids come first (in that order), followed by any remaining metrics
- * in their original array position. Each entry is the original index into the
- * metrics array so callers can write results to the correct positional slot.
- */
-export function getDisplayOrderedIndices(
- metrics: { uuid?: string }[],
- orderedUuids: string[] | null | undefined
-): number[] {
- if (!orderedUuids || orderedUuids.length === 0) {
- return metrics.map((_, i) => i)
- }
-
- const uuidToIndex = new Map<string, number>()
- for (let i = 0; i < metrics.length; i++) {
- const uuid = metrics[i].uuid
- if (uuid) {
- uuidToIndex.set(uuid, i)
- }
- }
-
- const ordered: number[] = []
- const seen = new Set<number>()
-
- for (const uuid of orderedUuids) {
- const idx = uuidToIndex.get(uuid)
- if (idx !== undefined && !seen.has(idx)) {
- ordered.push(idx)
- seen.add(idx)
- }
- }
-
- for (let i = 0; i < metrics.length; i++) {
- if (!seen.has(i)) {
- ordered.push(i)
- }
- }
-
- return ordered
-}
-
// Max concurrent metric queries to avoid overwhelming the celery queue's
// per-team concurrency limit (10). Using runWithLimit instead of Promise.all
// prevents mass rejections and retry churn when experiments have many metrics.