: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
feat(experiments): move metrics between primary and secondary (#62645)
Anders199bf3d1a442
diff --git a/frontend/jest.setup.ts b/frontend/jest.setup.tsindex 8f6ffc490cc9..7a61e6f9e222 100644--- a/frontend/jest.setup.ts+++ b/frontend/jest.setup.ts@@ -3,6 +3,7 @@ import 'whatwg-fetch'import { configure } from '@testing-library/react'import { TextDecoder, TextEncoder } from 'util'+import { deserialize, serialize } from 'v8'// Jest/JSDom don't know about TextEncoder but the browsers we support do// https://github.com/jsdom/jsdom/issues/2524@@ -64,6 +65,11 @@ if (typeof localStorage === 'undefined') {;(global as any).localStorage = localStorageStub}+// jsdom does not implement structuredClone — polyfill via Node's v8 serializer+if (typeof globalThis.structuredClone !== 'function') {+ globalThis.structuredClone = <T>(value: T): T => deserialize(serialize(value))+}+// jsdom does not implement AbortSignal.timeout — polyfill for testsif (typeof AbortSignal.timeout !== 'function') {AbortSignal.timeout = (ms: number): AbortSignal => {diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 82184dcb3ae1..7fb06d010fab 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4811,9 +4811,9 @@ snapshots:scenes-app-experiments--draft-experiment--light:hash: v1.k794b7964.70dc18be765207610c6040e3f2c831c2c5ebaa1726a330e293fa8c00d49a5cd9.rPoZm0K5sQEKk_6Br3PLSxWDdh9BKzhs7EHtpqP54KMscenes-app-experiments--experiment-asymmetric-intervals--dark:- hash: v1.k794b7964.cba7d55aa1a7d4b310d210118cb9a9d644c97a522cd855e08014cb8ea20de373.DRZgKpNgQ9kDl9NwVIrDfa29EUAo8hkhgNMR3PWX204+ hash: v1.k794b7964.16714efab3de01b2493cb8a6b54c57ebc8a35c794f9a3de128031c3a5f53b086.fsBLZMEaO-B8vm419k-olm5zmSJxatxWS7dV0uKycC8scenes-app-experiments--experiment-asymmetric-intervals--light:- hash: v1.k794b7964.10a29cbd091d468255f6f9daaea63c562fbe79b6898a4036d1ef6aa84447f5d5.bDwdfY2wuzA1aTOs3L2icCegZbZu9fiTVbIxXJSGCl8+ hash: v1.k794b7964.fce1cce1ac8905e25fff816ea028c9b9446fc6aff025a246db7009700192b697.8WGowBmtZO2lG-3xIKK9P7eD3MYNjTRHGCBTxn1nog0scenes-app-experiments--experiment-frequentist-five-variants--dark:hash: v1.k794b7964.09d23fd44208249b4fd1555fcbdb941118bc2825dc7142bd6ba96335c9cb8f32.AipSypBKnQguXtQO9tkCsdO9IVj-_0bHqjCnFe0BE-Uscenes-app-experiments--experiment-frequentist-five-variants--light:@@ -4825,7 +4825,7 @@ snapshots:scenes-app-experiments--experiment-with-funnel-metric--dark:hash: v1.k794b7964.a6b8d933157f59f997c8e85e81316b2f1c57667880fc6184c8a0b5ebac8acf76.K_vAMn8GGLpJ0_ZzlpEiPeb98TwI8iWauzAZ6KjUYBMscenes-app-experiments--experiment-with-funnel-metric--light:- hash: v1.k794b7964.f305aeb1f57f2b5067d6ae0b812f75a63f88cf5c40d15caa863bc805664d5375.mY8pmFLkdB5pzrPDozUDx4CgAHJa6pFcvQH41UDz_FE+ hash: v1.k794b7964.052d9c26d1a9fdd501f1c1c70747733af00910fd869fffd84bd6f395b08a41ed.6ytL6IZuCRWo69vUBJJmtHXviUcl1Twtt-cB0dAVxYwscenes-app-experiments--experiment-with-legacy-funnels-query--dark:hash: v1.k794b7964.5d2468e37868c1f7eb92bd6194d06bb4c58ec1e67eb97f2381bb554b6a50c25c.A-5pOsMFnOdqWaayNMR2WpehMVHF6c-PZ4aGq6L4Gvgscenes-app-experiments--experiment-with-legacy-funnels-query--light:diff --git a/frontend/src/scenes/experiments/MetricsView/MetricsReorderModal.tsx b/frontend/src/scenes/experiments/MetricsView/MetricsReorderModal.tsxindex e2c092e3a3b0..cb8e2fb17904 100644--- a/frontend/src/scenes/experiments/MetricsView/MetricsReorderModal.tsx+++ b/frontend/src/scenes/experiments/MetricsView/MetricsReorderModal.tsx@@ -20,21 +20,28 @@ const MetricItem = ({metric,order,isRemoved,- canRemove,+ isMoved,+ canLeave,+ moveTargetLabel,onRemove,+ onMove,onRestore,}: {metric: ExperimentMetric & { sharedMetricId?: number; isSharedMetric?: boolean }order: numberisRemoved: boolean- canRemove: boolean+ isMoved: boolean+ canLeave: boolean+ moveTargetLabel: stringonRemove: () => void+ onMove: () => voidonRestore: () => void}): JSX.Element => {const uuid = metric.uuid || (metric as any).query?.uuid+ const isStaged = isRemoved || isMovedconst { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({id: uuid,- disabled: isRemoved,+ disabled: isStaged,})return (@@ -51,13 +58,19 @@ const MetricItem = ({{...attributes}><div- className={clsx('flex-shrink-0', isRemoved ? 'cursor-default' : 'cursor-move')}- {...(isRemoved ? {} : listeners)}+ className={clsx('flex-shrink-0', isStaged ? 'cursor-default' : 'cursor-move')}+ {...(isStaged ? {} : listeners)}>- <IconDrag className={clsx('text-lg', isRemoved ? 'text-muted' : 'text-orange-500')} />+ <IconDrag className={clsx('text-lg', isStaged ? 'text-muted' : 'text-orange-500')} /></div><LemonBadge.Number count={order + 1} maxDigits={3} status="muted" />- <div className={clsx('flex-1 min-w-0 flex flex-col gap-1', isRemoved && 'line-through opacity-50')}>+ <div+ className={clsx(+ 'flex-1 min-w-0 flex flex-col gap-1',+ isRemoved && 'line-through opacity-50',+ isMoved && 'opacity-50'+ )}+ ><div className="font-semibold"><MetricTitle metric={metric} /></div>@@ -72,20 +85,37 @@ const MetricItem = ({)}</div></div>- {isRemoved ? (- <LemonButton size="small" type="secondary" onClick={onRestore}>- Restore- </LemonButton>+ {isStaged ? (+ <>+ {isMoved && (+ <LemonTag type="highlight" size="small">+ Moving to {moveTargetLabel}+ </LemonTag>+ )}+ <LemonButton size="small" type="secondary" onClick={onRestore}>+ Restore+ </LemonButton>+ </>) : (- <LemonButton- size="small"- status="danger"- type="secondary"- onClick={onRemove}- disabledReason={!canRemove ? 'At least one metric is required' : undefined}- >- Remove- </LemonButton>+ <>+ <LemonButton+ size="small"+ type="secondary"+ onClick={onMove}+ disabledReason={!canLeave ? 'At least one metric is required' : undefined}+ >+ Move to {moveTargetLabel}+ </LemonButton>+ <LemonButton+ size="small"+ status="danger"+ type="secondary"+ onClick={onRemove}+ disabledReason={!canLeave ? 'At least one metric is required' : undefined}+ >+ Remove+ </LemonButton>+ </>)}</div>)@@ -98,11 +128,14 @@ export function MetricsReorderModal({ isSecondary = false }: { isSecondary?: booconst isOpen = isSecondary ? isSecondaryMetricsReorderModalOpen : isPrimaryMetricsReorderModalOpenconst closeModal = isSecondary ? closeSecondaryMetricsReorderModal : closePrimaryMetricsReorderModal- const { experiment, getOrderedMetricsWithResults } = useValues(experimentLogic)- const { updateExperiment } = useActions(experimentLogic)+ const { experiment, getOrderedMetricsWithResults, experimentUpdateLoading } = useValues(experimentLogic)+ const { saveMetricsReorder } = useActions(experimentLogic)++ const moveTargetLabel = isSecondary ? 'primary' : 'secondary'const [orderedUuids, setOrderedUuids] = useState<string[]>([])const [removedUuids, setRemovedUuids] = useState<Set<string>>(new Set())+ const [movedUuids, setMovedUuids] = useState<Set<string>>(new Set())useEffect(() => {if (isOpen && experiment) {@@ -110,11 +143,11 @@ export function MetricsReorderModal({ isSecondary = false }: { isSecondary?: boo? (experiment.secondary_metrics_ordered_uuids ?? []): (experiment.primary_metrics_ordered_uuids ?? [])setOrderedUuids([...currentOrder])- setRemovedUuids(new Set())} else {setOrderedUuids([])- setRemovedUuids(new Set())}+ setRemovedUuids(new Set())+ setMovedUuids(new Set())}, [isOpen,isSecondary,@@ -142,8 +175,10 @@ export function MetricsReorderModal({ isSecondary = false }: { isSecondary?: booreturn orderedUuids.map((uuid) => metricsMap.get(uuid)).filter(Boolean)})()- const activeCount = orderedUuids.length - removedUuids.size- const canRemoveMore = isSecondary || activeCount > 1+ // Moved metrics leave the section just like removed ones, so both count+ // against the at-least-one-primary-metric requirement.+ const activeCount = orderedUuids.length - removedUuids.size - movedUuids.size+ const canLeaveMore = isSecondary || activeCount > 1const handleDragEnd = ({ active, over }: DragEndEvent): void => {if (active.id && over && active.id !== over.id) {@@ -157,66 +192,10 @@ export function MetricsReorderModal({ isSecondary = false }: { isSecondary?: boo}}- const handleSave = async (): Promise<void> => {- const hasRemovals = removedUuids.size > 0-- if (!hasRemovals) {- // No removals — just update ordering (existing behavior)- if (isSecondary) {- experiment!.secondary_metrics_ordered_uuids = orderedUuids- } else {- experiment!.primary_metrics_ordered_uuids = orderedUuids- }-- await updateExperiment({- primary_metrics_ordered_uuids: experiment?.primary_metrics_ordered_uuids,- secondary_metrics_ordered_uuids: experiment?.secondary_metrics_ordered_uuids,- })-- closeModal()- return- }-- // Build the update payload with removals- const filteredOrderedUuids = orderedUuids.filter((uuid) => !removedUuids.has(uuid))-- // Determine which removed metrics are shared vs inline- const metricsWithResults = getOrderedMetricsWithResults(isSecondary)- const allMetrics = metricsWithResults.map(({ metric }: { metric: any }) => metric)- const removedSharedMetricIds = new Set<number>()- allMetrics.forEach((metric: any) => {- const uuid = metric.uuid || metric.query?.uuid- if (uuid && removedUuids.has(uuid) && metric.isSharedMetric && metric.sharedMetricId) {- removedSharedMetricIds.add(metric.sharedMetricId)- }- })-- const metricsField = isSecondary ? 'metrics_secondary' : 'metrics'- const orderingField = isSecondary ? 'secondary_metrics_ordered_uuids' : 'primary_metrics_ordered_uuids'-- // Filter inline metrics to remove the deleted ones- const currentInlineMetrics = (experiment?.[metricsField] || []) as ExperimentMetric[]- const filteredInlineMetrics = currentInlineMetrics.filter((m) => !removedUuids.has(m.uuid!))-- const updatePayload: Record<string, any> = {- [metricsField]: filteredInlineMetrics,- [orderingField]: filteredOrderedUuids,- }-- // If shared metrics were removed, update saved_metrics_ids- if (removedSharedMetricIds.size > 0) {- const filteredSavedMetrics = (experiment?.saved_metrics || [])- .filter((sm) => !removedSharedMetricIds.has(sm.saved_metric))- .map((sm) => ({- id: sm.saved_metric,- metadata: sm.metadata,- }))- updatePayload.saved_metrics_ids = filteredSavedMetrics- }-- await updateExperiment(updatePayload)-- closeModal()+ const handleSave = (): void => {+ // The listener persists everything in one update, realigns results, and+ // closes the modal on completion.+ saveMetricsReorder(isSecondary, orderedUuids, Array.from(removedUuids), Array.from(movedUuids))}return (@@ -225,13 +204,18 @@ export function MetricsReorderModal({ isSecondary = false }: { isSecondary?: booisOpen={isOpen}width={600}title={`Reorder ${isSecondary ? 'secondary' : 'primary'} metrics`}- description={<p>Drag and drop to reorder, or remove metrics you no longer need.</p>}+ description={+ <p>+ Drag and drop to reorder, move metrics to the {moveTargetLabel} section, or remove metrics you no+ longer need.+ </p>+ }footer={<><LemonButton type="secondary" onClick={closeModal}>Cancel</LemonButton>- <LemonButton type="primary" onClick={handleSave}>+ <LemonButton type="primary" onClick={handleSave} loading={experimentUpdateLoading}>Save</LemonButton></>@@ -248,26 +232,35 @@ export function MetricsReorderModal({ isSecondary = false }: { isSecondary?: boo{displayMetrics.map((metric, index) => {const uuid = metric.uuid || (metric as any).query?.uuidconst isRemoved = removedUuids.has(uuid)+ const isMoved = movedUuids.has(uuid)const effectiveIndex =displayMetrics.slice(0, index + 1).filter((m) => {const id = m.uuid || (m as any).query?.uuid- return !removedUuids.has(id)+ return !removedUuids.has(id) && !movedUuids.has(id)}).length - 1return (<MetricItemkey={uuid}metric={metric}- order={isRemoved ? index : effectiveIndex}+ order={isRemoved || isMoved ? index : effectiveIndex}isRemoved={isRemoved}- canRemove={canRemoveMore}+ isMoved={isMoved}+ canLeave={canLeaveMore}+ moveTargetLabel={moveTargetLabel}onRemove={() => setRemovedUuids((prev) => new Set([...prev, uuid]))}- onRestore={() =>+ onMove={() => setMovedUuids((prev) => new Set([...prev, uuid]))}+ onRestore={() => {setRemovedUuids((prev) => {const next = new Set(prev)next.delete(uuid)return next})- }+ setMovedUuids((prev) => {+ const next = new Set(prev)+ next.delete(uuid)+ return next+ })+ }}/>)})}diff --git a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsxindex 7b8ea9482417..35962462d676 100644--- a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx@@ -81,19 +81,17 @@ export function Metrics({ isSecondary }: { isSecondary?: boolean }): JSX.Element<AddMetricButtonmetricContext={isSecondary ? METRIC_CONTEXTS.secondary : METRIC_CONTEXTS.primary}/>- {metrics.length > 1 && (- <LemonButton- type="secondary"- size="xsmall"- onClick={() =>- isSecondary- ? openSecondaryMetricsReorderModal()- : openPrimaryMetricsReorderModal()- }- icon={<IconList />}- tooltip="Reorder metrics"- />- )}+ <LemonButton+ type="secondary"+ size="xsmall"+ onClick={() =>+ isSecondary+ ? openSecondaryMetricsReorderModal()+ : openPrimaryMetricsReorderModal()+ }+ icon={<IconList />}+ tooltip="Reorder, move or remove metrics"+ /></div>)}</div>diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 88e46459d9aa..48c9f4946bd3 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -9,7 +9,13 @@ import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launcheimport experimentMetricResultsErrorJson from '~/mocks/fixtures/api/experiments/_experiment_metric_results_error.json'import experimentMetricResultsSuccessJson from '~/mocks/fixtures/api/experiments/_experiment_metric_results_success.json'import { useMocks } from '~/mocks/jest'-import { Breakdown, ExperimentMetric, ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'+import {+ Breakdown,+ CachedNewExperimentQueryResponse,+ ExperimentMetric,+ ExperimentMetricType,+ NodeKind,+} from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { Experiment, MultivariateFlagVariant } from '~/types'@@ -434,6 +440,322 @@ describe('experimentLogic', () => {)})})+ describe('saveMetricsReorder', () => {+ const primaryMetric = {+ kind: 'ExperimentMetric',+ uuid: 'primary-metric-uuid',+ name: 'Primary metric',+ } as unknown as ExperimentMetric+ const otherPrimaryMetric = {+ kind: 'ExperimentMetric',+ uuid: 'other-primary-uuid',+ name: 'Other primary metric',+ } as unknown as ExperimentMetric+ const thirdPrimaryMetric = {+ kind: 'ExperimentMetric',+ uuid: 'third-primary-uuid',+ name: 'Third primary metric',+ } as unknown as ExperimentMetric+ const secondaryMetric = {+ kind: 'ExperimentMetric',+ uuid: 'secondary-metric-uuid',+ name: 'Secondary metric',+ } as unknown as ExperimentMetric++ const primaryMetricResult = {+ baseline: { key: 'control' },+ metric_uuid: 'primary-metric-uuid',+ } as unknown as CachedNewExperimentQueryResponse+ const otherPrimaryMetricResult = {+ baseline: { key: 'control' },+ metric_uuid: 'other-primary-uuid',+ } as unknown as CachedNewExperimentQueryResponse+ const thirdPrimaryMetricResult = {+ baseline: { key: 'control' },+ metric_uuid: 'third-primary-uuid',+ } as unknown as CachedNewExperimentQueryResponse+ const secondaryMetricResult = {+ baseline: { key: 'control' },+ metric_uuid: 'secondary-metric-uuid',+ } as unknown as CachedNewExperimentQueryResponse++ beforeEach(() => {+ jest.spyOn(api, 'update')+ api.update.mockClear()+ })++ it('persists a pure reorder without touching metric arrays or results', async () => {+ const testExperiment = {+ ...experiment,+ saved_metrics: [],+ metrics: [primaryMetric, otherPrimaryMetric],+ metrics_secondary: [],+ primary_metrics_ordered_uuids: ['primary-metric-uuid', 'other-primary-uuid'],+ } as unknown as Experiment++ logic.actions.setExperiment(testExperiment)+ logic.actions.setPrimaryMetricsResults([primaryMetricResult, otherPrimaryMetricResult])+ api.update.mockResolvedValue({+ ...testExperiment,+ primary_metrics_ordered_uuids: ['other-primary-uuid', 'primary-metric-uuid'],+ })++ await expectLogic(logic, () => {+ logic.actions.saveMetricsReorder(false, ['other-primary-uuid', 'primary-metric-uuid'], [], [])+ })+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['refreshExperimentResults', 'loadPrimaryMetricsResults'])++ expect(api.update).toHaveBeenCalledWith(expect.stringContaining('/experiments/'), {+ primary_metrics_ordered_uuids: ['other-primary-uuid', 'primary-metric-uuid'],+ update_feature_flag_params: false,+ })+ expect(logic.values.primaryMetricsResults).toEqual([primaryMetricResult, otherPrimaryMetricResult])+ })++ it('moves an inline metric to secondary and reuses existing results', async () => {+ const testExperiment = {+ ...experiment,+ saved_metrics: [],+ metrics: [primaryMetric, otherPrimaryMetric],+ metrics_secondary: [secondaryMetric],+ primary_metrics_ordered_uuids: ['primary-metric-uuid', 'other-primary-uuid'],+ } as unknown as Experiment++ logic.actions.setExperiment(testExperiment)+ logic.actions.setPrimaryMetricsResults([primaryMetricResult, otherPrimaryMetricResult])+ logic.actions.setSecondaryMetricsResults([secondaryMetricResult])+ api.update.mockResolvedValue({+ ...testExperiment,+ metrics: [otherPrimaryMetric],+ metrics_secondary: [secondaryMetric, primaryMetric],+ primary_metrics_ordered_uuids: ['other-primary-uuid'],+ })++ await expectLogic(logic, () => {+ logic.actions.saveMetricsReorder(+ false,+ ['primary-metric-uuid', 'other-primary-uuid'],+ [],+ ['primary-metric-uuid']+ )+ })+ .toFinishAllListeners()+ .toNotHaveDispatchedActions([+ 'refreshExperimentResults',+ 'loadPrimaryMetricsResults',+ 'loadSecondaryMetricsResults',+ 'loadExperiment',+ 'retryPrimaryMetric',+ 'retrySecondaryMetric',+ ])++ expect(api.update).toHaveBeenCalledWith(+ expect.stringContaining('/experiments/'),+ expect.objectContaining({+ metrics: [otherPrimaryMetric],+ metrics_secondary: [secondaryMetric, primaryMetric],+ primary_metrics_ordered_uuids: ['other-primary-uuid'],+ })+ )+ expect(api.update).toHaveBeenCalledWith(+ expect.stringContaining('/experiments/'),+ expect.not.objectContaining({ saved_metrics_ids: expect.anything() })+ )+ expect(logic.values.primaryMetricsResults).toEqual([otherPrimaryMetricResult])+ expect(logic.values.secondaryMetricsResults).toEqual([secondaryMetricResult, primaryMetricResult])+ expect(logic.values.primaryMetricsResultsErrors).toEqual([null])+ expect(logic.values.secondaryMetricsResultsErrors).toEqual([null, null])+ })++ it('applies a combined move and removal in a single update', async () => {+ const testExperiment = {+ ...experiment,+ saved_metrics: [],+ metrics: [primaryMetric, otherPrimaryMetric, thirdPrimaryMetric],+ metrics_secondary: [],+ primary_metrics_ordered_uuids: ['primary-metric-uuid', 'other-primary-uuid', 'third-primary-uuid'],+ } as unknown as Experiment++ logic.actions.setExperiment(testExperiment)+ logic.actions.setPrimaryMetricsResults([+ primaryMetricResult,+ otherPrimaryMetricResult,+ thirdPrimaryMetricResult,+ ])+ api.update.mockResolvedValue({+ ...testExperiment,+ metrics: [thirdPrimaryMetric],+ metrics_secondary: [primaryMetric],+ primary_metrics_ordered_uuids: ['third-primary-uuid'],+ })++ await expectLogic(logic, () => {+ logic.actions.saveMetricsReorder(+ false,+ ['primary-metric-uuid', 'other-primary-uuid', 'third-primary-uuid'],+ ['other-primary-uuid'],+ ['primary-metric-uuid']+ )+ })+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['refreshExperimentResults'])++ expect(api.update).toHaveBeenCalledWith(+ expect.stringContaining('/experiments/'),+ expect.objectContaining({+ metrics: [thirdPrimaryMetric],+ metrics_secondary: [primaryMetric],+ primary_metrics_ordered_uuids: ['third-primary-uuid'],+ })+ )+ expect(logic.values.primaryMetricsResults).toEqual([thirdPrimaryMetricResult])+ expect(logic.values.secondaryMetricsResults).toEqual([primaryMetricResult])+ })++ it('moves a shared metric by flipping its saved-metric link type', async () => {+ const sharedMetricId = 123+ const sharedSavedMetric = {+ id: 1,+ experiment: experiment.id as number,+ saved_metric: sharedMetricId,+ name: 'Shared metric',+ query: {+ uuid: 'shared-metric-uuid',+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ },+ metadata: { type: 'primary' },+ created_at: '2024-01-01T00:00:00Z',+ } satisfies ExperimentSavedMetric+ const sharedMetricResult = {+ baseline: { key: 'control' },+ metric_uuid: 'shared-metric-uuid',+ } as unknown as CachedNewExperimentQueryResponse+ const testExperiment = {+ ...experiment,+ metrics: [],+ metrics_secondary: [],+ saved_metrics: [sharedSavedMetric],+ primary_metrics_ordered_uuids: ['shared-metric-uuid'],+ } as unknown as Experiment++ logic.actions.setExperiment(testExperiment)+ logic.actions.setPrimaryMetricsResults([sharedMetricResult])+ api.update.mockResolvedValue({+ ...testExperiment,+ saved_metrics: [{ ...sharedSavedMetric, metadata: { type: 'secondary' } }],+ primary_metrics_ordered_uuids: [],+ })++ await expectLogic(logic, () => {+ logic.actions.saveMetricsReorder(false, ['shared-metric-uuid'], [], ['shared-metric-uuid'])+ })+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['refreshExperimentResults', 'loadExperiment'])++ expect(api.update).toHaveBeenCalledWith(+ expect.stringContaining('/experiments/'),+ expect.objectContaining({+ saved_metrics_ids: [{ id: sharedMetricId, metadata: { type: 'secondary' } }],+ })+ )+ expect(logic.values.primaryMetricsResults).toEqual([])+ expect(logic.values.secondaryMetricsResults).toEqual([sharedMetricResult])+ })++ it('loads only the moved metric when it has no result yet', async () => {+ const fetchedResult = { baseline: { key: 'control' }, variant_results: [] }+ useMocks({+ post: {+ '/api/environments/:team/query/:kind': () => [+ 200,+ {+ cache_key: 'cache_key',+ query_status: {+ ...experimentMetricResultsSuccessJson.query_status,+ results: fetchedResult,+ },+ },+ ],+ },+ get: {+ '/api/environments/:team/query/:id': () => [+ 200,+ {+ query_status: {+ ...experimentMetricResultsSuccessJson.query_status,+ results: fetchedResult,+ },+ },+ ],+ },+ })++ const testExperiment = {+ ...experiment,+ saved_metrics: [],+ metrics: [],+ metrics_secondary: [secondaryMetric],+ secondary_metrics_ordered_uuids: ['secondary-metric-uuid'],+ } as unknown as Experiment++ logic.actions.setExperiment(testExperiment)+ api.update.mockResolvedValue({+ ...testExperiment,+ metrics: [secondaryMetric],+ metrics_secondary: [],+ secondary_metrics_ordered_uuids: [],+ })++ await expectLogic(logic, () => {+ logic.actions.saveMetricsReorder(true, ['secondary-metric-uuid'], [], ['secondary-metric-uuid'])+ })+ .toDispatchActions(['updateExperimentSuccess', 'retryPrimaryMetric'])+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['refreshExperimentResults', 'loadPrimaryMetricsResults'])++ expect(logic.values.primaryMetricsResults).toEqual([expect.objectContaining(fetchedResult)])+ })++ it('falls back to a full refresh when results are already loading', async () => {+ useMocks({+ post: {+ '/api/environments/:team/query/:kind': () => [+ 200,+ { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },+ ],+ },+ get: {+ '/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],+ },+ })++ const testExperiment = {+ ...experiment,+ saved_metrics: [],+ metrics: [primaryMetric],+ metrics_secondary: [],+ primary_metrics_ordered_uuids: ['primary-metric-uuid'],+ } as unknown as Experiment++ logic.actions.setExperiment(testExperiment)+ logic.actions.setPrimaryMetricsResultsLoading(true)+ api.update.mockResolvedValue({+ ...testExperiment,+ metrics: [],+ metrics_secondary: [primaryMetric],+ primary_metrics_ordered_uuids: [],+ })++ await expectLogic(logic, () => {+ logic.actions.saveMetricsReorder(false, ['primary-metric-uuid'], [], ['primary-metric-uuid'])+ })+ .toDispatchActions(['updateExperiment', 'refreshExperimentResults'])+ .toFinishAllListeners()+ })+ })describe('breakdown management', () => {it('should add breakdown to inline metric', () => {const breakdown: Breakdown = { property: '$browser', type: 'event' }diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 7efc5c7f04d0..c846533f2866 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -385,6 +385,19 @@ export function getDisplayOrderedIndices(return ordered}+/**+ * Positional uuid list for one section's results arrays: inline metrics first,+ * then shared metrics of that type — mirroring how loadPrimaryMetricsResults /+ * loadSecondaryMetricsResults build their query lists.+ */+export function getSectionMetricUuids(experiment: Experiment, isSecondary: boolean): (string | undefined)[] {+ const inlineMetrics = (isSecondary ? experiment.metrics_secondary : experiment.metrics) || []+ const sharedMetrics = ((experiment.saved_metrics || []) as ExperimentSavedMetric[]).filter(+ ({ metadata }) => metadata?.type === (isSecondary ? 'secondary' : 'primary')+ )+ return [...inlineMetrics.map((metric) => metric.uuid), ...sharedMetrics.map(({ query }) => query?.uuid)]+}+// 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.@@ -625,6 +638,8 @@ export const experimentLogic = kea<experimentLogicType>(['closeResumeExperimentModal','closeFinishExperimentModal','openReleaseConditionsModal',+ 'closePrimaryMetricsReorderModal',+ 'closeSecondaryMetricsReorderModal',],],})),@@ -771,6 +786,12 @@ export const experimentLogic = kea<experimentLogicType>([}),// Semantic metric actions - each controls its own reload behaviorremoveMetric: (uuid: string, context: 'primary' | 'secondary') => ({ uuid, context }),+ saveMetricsReorder: (+ isSecondary: boolean,+ orderedUuids: string[],+ removedUuids: string[],+ movedUuids: string[]+ ) => ({ isSecondary, orderedUuids, removedUuids, movedUuids }),updateMetricBreakdown: (uuid: string, breakdown: Breakdown) => ({ uuid, breakdown }),removeMetricBreakdown: (uuid: string, index: number, breakdown: Breakdown) => ({ uuid, index, breakdown }),// METRICS RESULTS@@ -2166,6 +2187,131 @@ export const experimentLogic = kea<experimentLogicType>([update_feature_flag_params: false,})},+ saveMetricsReorder: async ({ isSecondary, orderedUuids, removedUuids, movedUuids }) => {+ const removed = new Set(removedUuids)+ const moved = new Set(movedUuids)+ const orderingField = isSecondary ? 'secondary_metrics_ordered_uuids' : 'primary_metrics_ordered_uuids'+ const closeModal = isSecondary+ ? actions.closeSecondaryMetricsReorderModal+ : actions.closePrimaryMetricsReorderModal++ // Pure reorder: only the ordering array changes, so the positional+ // results arrays stay aligned and nothing needs reloading.+ if (removed.size === 0 && moved.size === 0) {+ await asyncActions.updateExperiment({+ [orderingField]: orderedUuids,+ update_feature_flag_params: false,+ })+ closeModal()+ return+ }++ // Moves and removals don't change any metric's definition, so existing+ // results stay valid — they only need realigning to the new positional+ // layout. That's unsafe while a load is writing positional results+ // concurrently.+ const canReuseResults = !values.primaryMetricsResultsLoading && !values.secondaryMetricsResultsLoading++ // Snapshot results/errors by uuid before the update changes the layout.+ const resultsByUuid = new Map<string, CachedNewExperimentQueryResponse | undefined>()+ const errorsByUuid = new Map<string, any>()+ for (const section of [false, true]) {+ const uuids = getSectionMetricUuids(values.experiment, section)+ const results = section ? values.secondaryMetricsResults : values.primaryMetricsResults+ const errors = section ? values.secondaryMetricsResultsErrors : values.primaryMetricsResultsErrors+ uuids.forEach((uuid, index) => {+ if (uuid) {+ resultsByUuid.set(uuid, results[index])+ errorsByUuid.set(uuid, errors[index])+ }+ })+ }++ const sourceField = isSecondary ? 'metrics_secondary' : 'metrics'+ const targetField = isSecondary ? 'metrics' : 'metrics_secondary'+ const sourceInlineMetrics = values.experiment[sourceField] || []+ const movedInlineMetrics = sourceInlineMetrics.filter((m) => m.uuid && moved.has(m.uuid))+ const remainingInlineMetrics = sourceInlineMetrics.filter(+ (m) => !(m.uuid && (moved.has(m.uuid) || removed.has(m.uuid)))+ )++ // The backend appends moved metrics to the target section's ordering+ // from the metric list changes, so only the source ordering is sent.+ const update: Partial<Experiment> & { update_feature_flag_params?: boolean } = {+ [sourceField]: remainingInlineMetrics,+ [orderingField]: orderedUuids.filter((uuid) => !removed.has(uuid) && !moved.has(uuid)),+ update_feature_flag_params: false,+ }+ if (movedInlineMetrics.length > 0) {+ update[targetField] = [...(values.experiment[targetField] || []), ...movedInlineMetrics]+ }++ // Shared metrics live in saved_metrics: removing one drops its link,+ // moving one flips the link type. Only send the links when affected.+ const savedMetrics = (values.experiment.saved_metrics || []) as ExperimentSavedMetric[]+ const sharedAffected = savedMetrics.some(({ query }) => {+ const uuid = query?.uuid+ return !!uuid && (removed.has(uuid) || moved.has(uuid))+ })+ if (sharedAffected) {+ const targetType = isSecondary ? 'primary' : 'secondary'+ update.saved_metrics_ids = savedMetrics+ .filter(({ query }) => !(query?.uuid && removed.has(query.uuid)))+ .map(({ saved_metric, metadata, query }) => ({+ id: saved_metric,+ metadata: query?.uuid && moved.has(query.uuid) ? { ...metadata, type: targetType } : metadata,+ }))+ }++ await asyncActions.updateExperiment(update)+ closeModal()++ if (!canReuseResults) {+ actions.refreshExperimentResults(true, 'config_change')+ return+ }++ const newPrimaryUuids = getSectionMetricUuids(values.experiment, false)+ const newSecondaryUuids = getSectionMetricUuids(values.experiment, true)+ actions.setPrimaryMetricsResults(+ newPrimaryUuids.map((uuid) =>+ uuid ? resultsByUuid.get(uuid) : undefined+ ) as CachedNewExperimentQueryResponse[]+ )+ actions.setPrimaryMetricsResultsErrors(+ newPrimaryUuids.map((uuid) => (uuid ? (errorsByUuid.get(uuid) ?? null) : null))+ )+ actions.setSecondaryMetricsResults(+ newSecondaryUuids.map((uuid) =>+ uuid ? resultsByUuid.get(uuid) : undefined+ ) as CachedNewExperimentQueryResponse[]+ )+ actions.setSecondaryMetricsResultsErrors(+ newSecondaryUuids.map((uuid) => (uuid ? (errorsByUuid.get(uuid) ?? null) : null))+ )++ // A moved metric without a result or error would be stuck rendering as+ // loading in its new section — fetch just those. Sequentially, because+ // the retry actions write back the whole positional array and would+ // stomp each other's results if run concurrently.+ if (isLaunched(values.experiment)) {+ const targetUuids = isSecondary ? newPrimaryUuids : newSecondaryUuids+ for (const uuid of movedUuids) {+ if (resultsByUuid.get(uuid) || errorsByUuid.get(uuid)) {+ continue+ }+ const newIndex = targetUuids.indexOf(uuid)+ if (newIndex === -1) {+ continue+ }+ if (isSecondary) {+ await asyncActions.retryPrimaryMetric(newIndex)+ } else {+ await asyncActions.retrySecondaryMetric(newIndex)+ }+ }+ }+ },updateMetricBreakdown: async ({ uuid, breakdown }) => {const isPrimary = values.experiment.metrics.some((m) => m.uuid === uuid)