:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(experiments): share metric config save path and skip no-op saves (#113756)
Anders43444632d87b
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 16dd563c5dd5..6df33a362405 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -23,6 +23,7 @@ import {} from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {+ BreakdownAttributionType,Experiment,ExperimentStatus,FeatureFlagBasicType,@@ -1498,84 +1499,41 @@ describe('experimentLogic', () => {})})describe('breakdown management', () => {- it('should add breakdown to inline metric', () => {- const breakdown: Breakdown = { property: '$browser', type: 'event' }- const testExperiment: Experiment = {- ...experiment,- metrics: [- {- uuid: 'test-metric-uuid',- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: '$pageview' },- breakdownFilter: { breakdowns: [] },- },- ] as unknown as ExperimentMetric[],- }-- logic.actions.setExperiment(testExperiment)- logic.actions.updateMetricBreakdown('test-metric-uuid', breakdown)-- const updatedMetric = logic.values.experiment.metrics[0] as ExperimentMetric- expect(updatedMetric.breakdownFilter?.breakdowns).toEqual([breakdown])- })-- it('should add breakdown to shared metric metadata', () => {- const breakdown: Breakdown = { property: '$browser', type: 'event' }- 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' },- created_at: '2024-01-01T00:00:00Z',- } satisfies ExperimentSavedMetric,- ],- metrics: [],- }-- logic.actions.setExperiment(testExperiment)- logic.actions.updateMetricBreakdown('shared-metric-uuid', breakdown)-- expect(logic.values.experiment.saved_metrics[0].metadata.breakdowns).toEqual([breakdown])- })-- it('should remove breakdown from 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' },- { property: '$os', type: 'event' },- ],- },- },- ] as unknown as ExperimentMetric[],- }-- logic.actions.setExperiment(testExperiment)- const breakdownToRemove: Breakdown = { property: '$browser', type: 'event' }- logic.actions.removeMetricBreakdown('test-metric-uuid', 0, breakdownToRemove)-- const updatedMetric = logic.values.experiment.metrics[0] as ExperimentMetric- expect(updatedMetric.breakdownFilter?.breakdowns).toEqual([{ property: '$os', type: 'event' }])- })-const browserBreakdown: Breakdown = { property: '$browser', type: 'event' }const osBreakdown: Breakdown = { property: '$os', type: 'event' }+ const deviceBreakdown: Breakdown = { property: '$device_type', type: 'event' }++ const configMetric = (uuid: string): ExperimentMetric => ({+ kind: NodeKind.ExperimentMetric,+ uuid,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown] },+ })+ const configLink = (+ savedMetricId: number,+ uuid: string,+ type: 'primary' | 'secondary'+ ): ExperimentSavedMetric => ({+ id: savedMetricId,+ experiment: experiment.id as number,+ saved_metric: savedMetricId,+ name: 'Shared Metric',+ query: {+ uuid,+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ },+ metadata: { type, breakdowns: [browserBreakdown, osBreakdown] },+ created_at: '2024-01-01T00:00:00Z',+ })+ const metricConfigExperiment: Experiment = {+ ...experiment,+ metrics: [configMetric('inline-primary')],+ metrics_secondary: [configMetric('inline-secondary')],+ saved_metrics: [configLink(1, 'shared-primary', 'primary'), configLink(2, 'shared-secondary', 'secondary')],+ }it.each([['the shown breakdown', [browserBreakdown, osBreakdown], 0, browserBreakdown, [osBreakdown]],@@ -1696,44 +1654,6 @@ describe('experimentLogic', () => {expect(logic.values.experiment.saved_metrics[0].metadata.breakdowns).toEqual([breakdown])})- it('should remove breakdown from secondary shared metric metadata', () => {- const testExperiment: Experiment = {- ...experiment,- saved_metrics: [- {- id: 1,- experiment: experiment.id as number,- saved_metric: 123,- name: 'Secondary Shared Metric',- query: {- uuid: 'secondary-metric-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: '$pageview' },- },- metadata: {- type: 'secondary',- breakdowns: [- { property: '$browser', type: 'event' } satisfies Breakdown,- { property: '$os', type: 'event' } satisfies Breakdown,- ],- },- created_at: '2024-01-01T00:00:00Z',- } satisfies ExperimentSavedMetric,- ],- metrics: [],- metrics_secondary: [],- }-- logic.actions.setExperiment(testExperiment)- const breakdownToRemove: Breakdown = { property: '$browser', type: 'event' }- logic.actions.removeMetricBreakdown('secondary-metric-uuid', 0, breakdownToRemove)-- expect(logic.values.experiment.saved_metrics[0].metadata.breakdowns).toEqual([- { property: '$os', type: 'event' },- ])- })-it('should include breakdowns when preparing secondary shared metrics for loading', () => {const testExperiment: Experiment = {...experiment,@@ -1784,103 +1704,208 @@ describe('experimentLogic', () => {])})- it('should update breakdown limit on inline metric', () => {- const testExperiment: Experiment = {- ...experiment,- metrics: [+ describe.each([+ {+ name: 'adding a breakdown',+ action: 'updateMetricBreakdown',+ change: (uuid: string) => logic.actions.updateMetricBreakdown(uuid, deviceBreakdown),+ inlineEdit: { breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown, deviceBreakdown] } },+ sharedEdit: { breakdowns: [browserBreakdown, osBreakdown, deviceBreakdown] },+ event: ['experiment metric breakdown added', { breakdown_property: '$device_type' }] as const,+ noOpEdits: [],+ },+ {+ name: 'removing a breakdown',+ action: 'removeMetricBreakdown',+ change: (uuid: string) => logic.actions.removeMetricBreakdown(uuid, 0, browserBreakdown),+ inlineEdit: { breakdownFilter: { breakdowns: [osBreakdown] } },+ sharedEdit: { breakdowns: [osBreakdown] },+ event: [+ 'experiment metric breakdown removed',+ { breakdown_property: '$browser', breakdown_index: 0 },+ ] as const,+ noOpEdits: [{- uuid: 'test-metric-uuid',- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: '$pageview' },- breakdownFilter: { breakdowns: [{ property: '$browser', type: 'event' }] },+ edit: 'a shown breakdown that the link metadata does not hold',+ run: () => logic.actions.removeMetricBreakdown('shared-primary', 2, deviceBreakdown),},- ] as unknown as ExperimentMetric[],- }-- logic.actions.setExperiment(testExperiment)- logic.actions.updateMetricBreakdownLimit('test-metric-uuid', 10)+ ],+ },+ {+ name: 'changing the breakdown limit',+ action: 'updateMetricBreakdownLimit',+ change: (uuid: string) => logic.actions.updateMetricBreakdownLimit(uuid, 10),+ inlineEdit: { breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown], breakdown_limit: 10 } },+ sharedEdit: { breakdown_limit: 10 },+ event: null,+ noOpEdits: [],+ },+ {+ name: 'changing the breakdown attribution',+ action: 'updateMetricBreakdownAttribution',+ change: (uuid: string) =>+ logic.actions.updateMetricBreakdownAttribution(uuid, BreakdownAttributionType.Step, 1),+ inlineEdit: { breakdownAttributionType: BreakdownAttributionType.Step, breakdownAttributionValue: 1 },+ sharedEdit: { breakdownAttributionType: BreakdownAttributionType.Step, breakdownAttributionValue: 1 },+ event: null,+ noOpEdits: [],+ },+ ])('$name', ({ action, change, inlineEdit, sharedEdit, event, noOpEdits }) => {+ const legacyReloads = ['loadPrimaryMetricsResults', 'loadSecondaryMetricsResults']+ let captureSpy: jest.SpyInstance+ let updateSpy: jest.SpyInstance++ const breakdownEvents = (): any[] =>+ captureSpy.mock.calls+ .filter(([name]) => String(name).startsWith('experiment metric breakdown'))+ .map(([name, properties]) => [name, properties])++ const expectedBreakdownEvents = (uuid: string, isPrimary: boolean): any[] =>+ event+ ? [+ [+ event[0],+ expect.objectContaining({ ...event[1], metric_uuid: uuid, is_primary_metric: isPrimary }),+ ],+ ]+ : []++ beforeEach(() => {+ useMocks({+ post: {+ '/api/environments/:team/query': () => [+ 200,+ { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },+ ],+ },+ get: {+ '/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],+ },+ })+ captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ updateSpy = jest.spyOn(api, 'update').mockResolvedValue(metricConfigExperiment)+ logic.actions.setExperiment(metricConfigExperiment)+ })++ afterEach(() => {+ // clearMocks resets the calls but keeps the implementations, so a spy left in place would answer+ // every later test in this file.+ updateSpy.mockRestore()+ captureSpy.mockRestore()+ })++ it.each([+ { location: 'an inline primary metric', uuid: 'inline-primary', isPrimary: true },+ { location: 'an inline secondary metric', uuid: 'inline-secondary', isPrimary: false },+ { location: 'a shared primary metric', uuid: 'shared-primary', isPrimary: true },+ { location: 'a shared secondary metric', uuid: 'shared-secondary', isPrimary: false },+ ])('on $location saves the edit and reloads its section', async ({ uuid, isPrimary }) => {+ const reload = isPrimary ? 'loadPrimaryMetricsResults' : 'loadSecondaryMetricsResults'++ // toNotHaveDispatchedActions searches only the history after the last match. The earlier tests in+ // this block do not wait for their saves, so a late save can dispatch a reload into this test.+ // Match the change first to skip that, and check the absent actions before matching the reload.+ await expectLogic(logic, () => {+ change(uuid)+ })+ .toDispatchActions([action])+ .toFinishAllListeners()+ .toNotHaveDispatchedActions([+ ...legacyReloads.filter((reloadAction) => reloadAction !== reload),+ 'refreshExperimentResults',+ ])+ .toDispatchActions([reload])++ const editInline = (metric: ExperimentMetric): ExperimentMetric =>+ metric.uuid === uuid ? ({ ...metric, ...inlineEdit } as ExperimentMetric) : metric+ const isShared = uuid.startsWith('shared')+ expect(updateSpy).toHaveBeenCalledTimes(1)+ expect(updateSpy).toHaveBeenCalledWith(expect.any(String), {+ metrics: (metricConfigExperiment.metrics as ExperimentMetric[]).map(editInline),+ metrics_secondary: (metricConfigExperiment.metrics_secondary as ExperimentMetric[]).map(editInline),+ update_feature_flag_params: false,+ ...(isShared && {+ saved_metrics_ids: (metricConfigExperiment.saved_metrics as ExperimentSavedMetric[]).map(+ ({ saved_metric, query, metadata }) => ({+ id: saved_metric,+ metadata: query.uuid === uuid ? { ...metadata, ...sharedEdit } : metadata,+ })+ ),+ }),+ })+ expect(breakdownEvents()).toEqual(expectedBreakdownEvents(uuid, isPrimary))+ })- const updatedMetric = logic.values.experiment.metrics[0] as ExperimentMetric- expect(updatedMetric.breakdownFilter?.breakdown_limit).toEqual(10)- })+ it.each([+ { edit: 'a metric the experiment does not have', run: () => change('missing-metric') },+ ...noOpEdits,+ ])('skips the save, the reload and the event for $edit', async ({ run }) => {+ await expectLogic(logic, () => {+ run()+ })+ .toDispatchActions([action])+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['updateExperiment', ...legacyReloads, 'refreshExperimentResults'])- 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: [],- }+ expect(breakdownEvents()).toEqual([])+ })- logic.actions.setExperiment(testExperiment)- logic.actions.updateMetricBreakdownLimit('shared-metric-uuid', 10)+ it('refreshes results on the recalculation flow', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {+ [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,+ })- expect(logic.values.experiment.saved_metrics[0].metadata.breakdown_limit).toEqual(10)- })+ await expectLogic(logic, () => {+ change('inline-secondary')+ })+ .toDispatchActions([action])+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(legacyReloads)+ .toDispatchActions([+ (dispatched) =>+ dispatched.type === logic.actionTypes.refreshExperimentResults &&+ dispatched.payload.forceRefresh === true &&+ dispatched.payload.triggeredBy === 'metric_config_change',+ ])+ })++ it('skips the reload when the save fails', async () => {+ updateSpy.mockRejectedValue(new Error('network down'))++ await expectLogic(logic, () => {+ change('shared-primary')+ })+ .toDispatchActions([action])+ .toFinishAllListeners()+ .toNotHaveDispatchedActions([...legacyReloads, 'refreshExperimentResults'])+ .toDispatchActions(['updateExperimentFailure'])- it.each([- ['reloads the section of a shared primary metric', true, ['loadPrimaryMetricsResults']],- ['skips the reload when the save fails', false, []],- ])('adding a breakdown %s', async (_name, saveSucceeds, reloaded) => {- useMocks({- post: {- '/api/environments/:team/query': () => [- 200,- { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },- ],- },- get: {- '/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],- },+ // The event reports the user action, so it fires before the save and does not wait for it.+ expect(breakdownEvents()).toEqual(expectedBreakdownEvents('shared-primary', true))})- 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' },- created_at: '2024-01-01T00:00:00Z',- } satisfies ExperimentSavedMetric,- ],- metrics: [],- }- logic.actions.setExperiment(testExperiment)- if (saveSucceeds) {- jest.spyOn(api, 'update').mockResolvedValue(testExperiment)- } else {- jest.spyOn(api, 'update').mockRejectedValue(new Error('network down'))- }- const reloads = ['loadPrimaryMetricsResults', 'loadSecondaryMetricsResults', 'refreshExperimentResults']- await expectLogic(logic, () => {- logic.actions.updateMetricBreakdown('shared-metric-uuid', browserBreakdown)+ it('finishes a save that outlives the page', async () => {+ let saveStarted: () => void = () => {}+ const started = new Promise<void>((resolve) => {+ saveStarted = resolve+ })+ let finishSave: () => void = () => {}+ updateSpy.mockImplementation(+ () =>+ new Promise((resolve) => {+ finishSave = () => resolve(metricConfigExperiment)+ saveStarted()+ })+ )++ change('inline-primary')+ await started+ logic.unmount()+ finishSave()++ // A `values` read after the save would throw "[KEA] Can not find path" into the listener.+ await expectLogic(logic).toFinishAllListeners()})- .toDispatchActions(reloaded)- .toFinishAllListeners()- .toNotHaveDispatchedActions(reloads.filter((action) => !reloaded.includes(action)))})})diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex ccff7d2a357f..65f5181a871f 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -10,7 +10,9 @@ import {props,reducers,selectors,+ sharedListeners,} from 'kea'+import type { BreakPointFunction } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'import posthog from 'posthog-js'@@ -298,11 +300,67 @@ export function getSectionMetricUuids(experiment: Experiment, isSecondary: boolereturn [...inlineMetrics.map((metric) => metric.uuid), ...sharedMetrics.map(({ query }) => query?.uuid)]}+interface MetricLocation {+ kind: 'shared' | 'inline'+ isPrimary: boolean+ /** Position in `saved_metrics` for a shared metric, and in `metrics` or `metrics_secondary` for an inline one. */+ index: number+}++function locateMetric(experiment: Experiment, uuid: string): MetricLocation | null {+ const savedMetrics: ExperimentSavedMetric[] = experiment.saved_metrics || []+ const sharedIndex = savedMetrics.findIndex(({ query }) => query?.uuid === uuid)+ if (sharedIndex !== -1) {+ return { kind: 'shared', isPrimary: savedMetrics[sharedIndex].metadata?.type === 'primary', index: sharedIndex }+ }+ const primaryIndex = (experiment.metrics || []).findIndex((metric) => metric.uuid === uuid)+ if (primaryIndex !== -1) {+ return { kind: 'inline', isPrimary: true, index: primaryIndex }+ }+ const secondaryIndex = (experiment.metrics_secondary || []).findIndex((metric) => metric.uuid === uuid)+ return secondaryIndex === -1 ? null : { kind: 'inline', isPrimary: false, index: secondaryIndex }+}+function isPrimaryMetric(experiment: Experiment, uuid: string): boolean {- const sharedMetric = ((experiment.saved_metrics || []) as ExperimentSavedMetric[]).find(- ({ query }) => query?.uuid === uuid- )- return sharedMetric ? sharedMetric.metadata.type === 'primary' : experiment.metrics.some((m) => m.uuid === uuid)+ return locateMetric(experiment, uuid)?.isPrimary ?? false+}++/**+ * Applies a breakdown config edit to one metric of the experiment. A shared metric keeps this config on the+ * metadata of its link to the experiment, so the edit does not change the shared metric for other experiments.+ * An inline metric keeps the config on the metric itself. When the uuid matches no metric, or the edit returns+ * its input as is, this returns the same experiment object, which tells the listeners that nothing changed.+ */+function editMetricConfig(+ experiment: Experiment,+ uuid: string,+ edit: {+ shared: (metadata: ExperimentSavedMetric['metadata']) => ExperimentSavedMetric['metadata']+ inline: (metric: ExperimentMetric) => ExperimentMetric+ }+): Experiment {+ const location = locateMetric(experiment, uuid)+ if (location?.kind === 'shared') {+ const savedMetrics: ExperimentSavedMetric[] = [...experiment.saved_metrics]+ const savedMetric = savedMetrics[location.index]+ const metadata = edit.shared(savedMetric.metadata)+ if (metadata === savedMetric.metadata) {+ return experiment+ }+ savedMetrics[location.index] = { ...savedMetric, metadata }+ return { ...experiment, saved_metrics: savedMetrics }+ }+ if (location?.kind === 'inline') {+ const metricsKey = location.isPrimary ? 'metrics' : 'metrics_secondary'+ const metrics = [...experiment[metricsKey]]+ const metric = edit.inline(metrics[location.index] as ExperimentMetric)+ if (metric === metrics[location.index]) {+ return experiment+ }+ metrics[location.index] = metric+ return { ...experiment, [metricsKey]: metrics }+ }+ return experiment}/**@@ -1218,6 +1276,21 @@ export interface experimentLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentLogicMeta {key: ExperimentIdType+ sharedListeners: {+ saveMetricConfigAndReload: (+ payload: {+ uuid: string+ },+ breakpoint: BreakPointFunction,+ action: {+ type: string+ payload: {+ uuid: string+ }+ },+ previousState: any+ ) => void | Promise<void>+ }__keaTypeGenInternalSelectorTypes: {props: (arg: any) => anyexperimentId: (arg: any) => Experiment['id']@@ -1871,264 +1944,69 @@ export const experimentLogic = kea<experimentLogicType>([[metricsKey]: metrics,}},- updateMetricBreakdown: (state, { uuid, breakdown }) => {- /**- * Check if the UUID belongs to a shared metric- * Shared Metric types are confusing. The query property- * is, for all practical purposes, an ExperimentMetric.- */- const savedMetrics: ExperimentSavedMetric[] = [...(state?.saved_metrics || [])]- const savedMetricIndex = savedMetrics.findIndex(- ({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid- )-- if (savedMetricIndex !== -1) {- // Handle shared metric - update saved_metrics metadata- const savedMetric = savedMetrics[savedMetricIndex]- savedMetrics[savedMetricIndex] = {- ...savedMetric,- metadata: {- ...savedMetric.metadata,- breakdowns: [...(savedMetric.metadata?.breakdowns || []), breakdown],- },- }-- return {- ...state,- saved_metrics: savedMetrics,- }- }-- // Handle inline metric- const metricsKey =- (state?.metrics || ([] as ExperimentMetric[])).findIndex((m) => m.uuid === uuid) > -1- ? 'metrics'- : 'metrics_secondary'-- const metrics = [...(state?.[metricsKey] || [])]- const targetIndex = metrics.findIndex((m) => m.uuid === uuid)- if (targetIndex === -1) {- return state- }-- const metric = metrics[targetIndex] as ExperimentMetric- const breakdownFilter = {- ...metric.breakdownFilter,- breakdowns: [...(metric.breakdownFilter?.breakdowns || []), breakdown],- }-- metrics[targetIndex] = {- ...metric,- breakdownFilter,- } as ExperimentMetric-- return {- ...state,- [metricsKey]: metrics,- }- },- removeMetricBreakdown: (state, { uuid, index, breakdown }) => {- /**- * Check if the UUID belongs to a shared metric- * Shared Metric types are confusing. The query property- * is, for all practical purposes, an ExperimentMetric.- */- const savedMetrics: ExperimentSavedMetric[] = [...(state?.saved_metrics || [])]- const savedMetricIndex = savedMetrics.findIndex(- ({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid- )-- if (savedMetricIndex !== -1) {- // Handle shared metric - update saved_metrics metadata. The scene shows the breakdowns- // of the link's effective_query, which only the API resolves, so that list can differ- // from metadata.breakdowns until the save returns. Remove the breakdown by value, so- // that an index into the shown list never removes a different breakdown.- const savedMetric = savedMetrics[savedMetricIndex]- const breakdowns = savedMetric.metadata?.breakdowns || []- const position = breakdowns.findIndex((candidate) => objectsEqual(candidate, breakdown))- savedMetrics[savedMetricIndex] = {- ...savedMetric,- metadata: {- ...savedMetric.metadata,- breakdowns: breakdowns.filter((_, i) => i !== position),- },- }-- return {- ...state,- saved_metrics: savedMetrics,- }- }-- // Handle inline metric- const metricsKey =- (state?.metrics || ([] as ExperimentMetric[])).findIndex((m) => m.uuid === uuid) > -1- ? 'metrics'- : 'metrics_secondary'-- const metrics = [...(state?.[metricsKey] || [])]- const targetIndex = metrics.findIndex((m) => m.uuid === uuid)- if (targetIndex === -1) {- return state- }-- const metric = metrics[targetIndex] as ExperimentMetric- const breakdownFilter = {- ...metric.breakdownFilter,- breakdowns: (metric.breakdownFilter?.breakdowns || []).filter((_, i) => i !== index),- }-- metrics[targetIndex] = {- ...metric,- breakdownFilter,- } as ExperimentMetric-- return {- ...state,- [metricsKey]: metrics,- }- },- updateMetricBreakdownAttribution: (state, { uuid, attributionType, attributionValue }) => {- /**- * 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) {- const savedMetric = savedMetrics[savedMetricIndex]- savedMetrics[savedMetricIndex] = {- ...savedMetric,- metadata: {- ...savedMetric.metadata,+ updateMetricBreakdown: (state, { uuid, breakdown }) =>+ editMetricConfig(state, uuid, {+ shared: (metadata) => ({+ ...metadata,+ breakdowns: [...(metadata?.breakdowns || []), breakdown],+ }),+ inline: (metric) =>+ ({+ ...metric,+ breakdownFilter: {+ ...metric.breakdownFilter,+ breakdowns: [...(metric.breakdownFilter?.breakdowns || []), breakdown],+ },+ }) as ExperimentMetric,+ }),+ removeMetricBreakdown: (state, { uuid, index, breakdown }) =>+ editMetricConfig(state, uuid, {+ // The scene shows the breakdowns of the link's effective_query, which only the API+ // resolves, so that list can differ from metadata.breakdowns until the save returns.+ // Remove the breakdown by value, so that an index into the shown list never removes a+ // different breakdown.+ shared: (metadata) => {+ const breakdowns = metadata?.breakdowns || []+ const position = breakdowns.findIndex((candidate) => objectsEqual(candidate, breakdown))+ if (position === -1) {+ return metadata+ }+ return { ...metadata, breakdowns: breakdowns.filter((_, i) => i !== position) }+ },+ inline: (metric) =>+ ({+ ...metric,+ breakdownFilter: {+ ...metric.breakdownFilter,+ breakdowns: (metric.breakdownFilter?.breakdowns || []).filter(+ (_, i) => i !== index+ ),+ },+ }) as ExperimentMetric,+ }),+ updateMetricBreakdownAttribution: (state, { uuid, attributionType, attributionValue }) =>+ editMetricConfig(state, uuid, {+ shared: (metadata) => ({+ ...metadata,+ breakdownAttributionType: attributionType,+ breakdownAttributionValue: attributionValue,+ }),+ inline: (metric) =>+ ({+ ...metric,breakdownAttributionType: attributionType,breakdownAttributionValue: attributionValue,- },- }-- /**- * 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 attribution- */- metrics[targetIndex] = {- ...metrics[targetIndex],- breakdownAttributionType: attributionType,- breakdownAttributionValue: attributionValue,- } as ExperimentMetric-- /**- * return the updated experiment state- */- return {- ...state,- [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,- }- },+ }) as ExperimentMetric,+ }),+ updateMetricBreakdownLimit: (state, { uuid, breakdownLimit }) =>+ editMetricConfig(state, uuid, {+ shared: (metadata) => ({ ...metadata, breakdown_limit: breakdownLimit }),+ inline: (metric) =>+ ({+ ...metric,+ breakdownFilter: { ...metric.breakdownFilter, breakdown_limit: breakdownLimit },+ }) as ExperimentMetric,+ }),},],experimentMissing: [@@ -2280,7 +2158,58 @@ export const experimentLogic = kea<experimentLogicType>([},],}),- listeners(({ values, actions, asyncActions, cache, props }) => ({+ sharedListeners(({ values, actions, selectors, cache }) => ({+ /**+ * Saves a breakdown config edit that a reducer has already applied to `values.experiment`, then+ * re-runs the results that the edit changes.+ */+ saveMetricConfigAndReload: async (+ { uuid }: { uuid: string },+ _breakpoint: BreakPointFunction,+ _action: unknown,+ previousState: unknown+ ): Promise<void> => {+ // editMetricConfig returns the same experiment when the edit changes nothing.+ if (values.experiment === selectors.experiment(previousState)) {+ return+ }+ // Locate the metric before the save. The save can outlive the page, and `values.experiment`+ // throws once the logic unmounts.+ const location = locateMetric(values.experiment, uuid)+ const updatePayload: Partial<Experiment> & { update_feature_flag_params?: boolean } = {+ metrics: values.experiment.metrics,+ metrics_secondary: values.experiment.metrics_secondary,+ update_feature_flag_params: false,+ }++ // Only include saved_metrics_ids if we modified a shared metric+ if (location?.kind === 'shared') {+ const savedMetrics: ExperimentSavedMetric[] = values.experiment.saved_metrics+ updatePayload.saved_metrics_ids = savedMetrics.map(({ saved_metric, metadata }) => ({+ id: saved_metric,+ metadata,+ }))+ }++ actions.updateExperiment(updatePayload)+ // The reload reads a shared metric's effective_query, which only the save response carries.+ if (!(await inflightUpdateSaved(cache))) {+ return+ }++ // A breakdown config change alters how the metric is computed, so re-run results. The recalculation+ // flow reuses the current window (metric_config_change), so this metric recomputes on its changed+ // fingerprint while unchanged metrics load from cache. Legacy reloads the section that holds the metric.+ if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {+ actions.refreshExperimentResults(true, 'metric_config_change')+ } else if (location?.isPrimary) {+ actions.loadPrimaryMetricsResults(true)+ } else {+ actions.loadSecondaryMetricsResults(true)+ }+ },+ })),+ listeners(({ values, actions, selectors, asyncActions, cache, props, sharedListeners }) => ({reportExperimentMetricsRefreshed: ({ experiment, forceRefresh, context }) => {posthog.capture('experiment metrics refreshed', {...getEventPropertiesForExperiment(experiment),@@ -3481,177 +3410,26 @@ export const experimentLogic = kea<experimentLogicType>([}}},- updateMetricBreakdown: async ({ uuid, breakdown }) => {- const isPrimary = isPrimaryMetric(values.experiment, uuid)-- actions.reportExperimentMetricBreakdownAdded(values.experiment, uuid, breakdown, isPrimary)-- const savedMetrics: ExperimentSavedMetric[] = [...(values.experiment.saved_metrics || [])]- // Check if this is a shared metric by looking in saved_metrics- const isSharedMetric = savedMetrics.some(({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid)-- const updatePayload: Partial<Experiment> & { update_feature_flag_params?: boolean } = {- metrics: values.experiment.metrics,- metrics_secondary: values.experiment.metrics_secondary,- update_feature_flag_params: false,- }-- // Only include saved_metrics_ids if we modified a shared metric- if (isSharedMetric) {- updatePayload.saved_metrics_ids = savedMetrics.map(({ saved_metric, metadata }) => ({- id: saved_metric,- metadata,- }))- }-- actions.updateExperiment(updatePayload)- // The reload reads a shared metric's effective_query, which only the save response carries.- if (!(await inflightUpdateSaved(cache))) {- return- }-- // Adding a breakdown changes how the metric is computed, so re-run results. The recalculation- // flow reuses the current window (metric_config_change), so this breakdown recomputes on its- // changed fingerprint while unchanged metrics load from cache; legacy reloads per-metric results.- if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- actions.refreshExperimentResults(true, 'metric_config_change')- } else if (isPrimary) {- actions.loadPrimaryMetricsResults(true)- } else {- actions.loadSecondaryMetricsResults(true)- }- },- removeMetricBreakdown: async ({ uuid, index, breakdown }) => {- const isPrimary = isPrimaryMetric(values.experiment, uuid)-- actions.reportExperimentMetricBreakdownRemoved(values.experiment, uuid, breakdown, index, isPrimary)-- const savedMetrics: ExperimentSavedMetric[] = [...(values.experiment.saved_metrics || [])]- // Check if this is a shared metric by looking in saved_metrics- const isSharedMetric = savedMetrics.some(({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid)-- const updatePayload: Partial<Experiment> & { update_feature_flag_params?: boolean } = {- metrics: values.experiment.metrics,- metrics_secondary: values.experiment.metrics_secondary,- update_feature_flag_params: false,- }-- // Only include saved_metrics_ids if we modified a shared metric- if (isSharedMetric) {- updatePayload.saved_metrics_ids = savedMetrics.map(({ saved_metric, metadata }) => ({- id: saved_metric,- metadata,- }))- }-- actions.updateExperiment(updatePayload)- // The reload reads a shared metric's effective_query, which only the save response carries.- if (!(await inflightUpdateSaved(cache))) {- return- }-- // Removing a breakdown changes how the metric is computed, so re-run results. On the- // recalculation flow this reuses the current window (metric_config_change), so this metric- // recomputes on its changed fingerprint while others load from cache; legacy reloads per-metric.- if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- actions.refreshExperimentResults(true, 'metric_config_change')- } else if (isPrimary) {- actions.loadPrimaryMetricsResults(true)- } else {- actions.loadSecondaryMetricsResults(true)- }- },- updateMetricBreakdownAttribution: async ({ uuid }) => {- /**- * build the experiment 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 attribution on the many to many relationship metadata- */- const savedMetrics: ExperimentSavedMetric[] = [...(values.experiment.saved_metrics || [])]- const sharedMetric = savedMetrics.find(({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid)- 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- */- actions.updateExperiment(updatePayload)- if (!(await inflightUpdateSaved(cache))) {- return- }-- /**- * figure out if it's a primary metric- */- const isPrimary = isPrimaryMetric(values.experiment, uuid)-- /**- * updating a breakdown limit triggers a recalculation.- */- if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- actions.refreshExperimentResults(true, 'metric_config_change')- } else if (isPrimary) {- actions.loadPrimaryMetricsResults(true)- } else {- actions.loadSecondaryMetricsResults(true)- }- },- updateMetricBreakdownLimit: async ({ 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- */- const savedMetrics: ExperimentSavedMetric[] = [...(values.experiment.saved_metrics || [])]- const sharedMetric = savedMetrics.find(({ query: { uuid: savedMetricUuid } }) => savedMetricUuid === uuid)- 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- */- actions.updateExperiment(updatePayload)- if (!(await inflightUpdateSaved(cache))) {- return- }-- /**- * find if the updated metris is primary- */- const isPrimary = isPrimaryMetric(values.experiment, uuid)- /**- * updating a breakdown limit triggers a recalculation.- */- if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- actions.refreshExperimentResults(true, 'metric_config_change')- } else if (isPrimary) {- actions.loadPrimaryMetricsResults(true)- } else {- actions.loadSecondaryMetricsResults(true)- }- },+ updateMetricBreakdown: [+ ({ uuid, breakdown }, _breakpoint, _action, previousState): void => {+ if (values.experiment !== selectors.experiment(previousState)) {+ const isPrimary = isPrimaryMetric(values.experiment, uuid)+ actions.reportExperimentMetricBreakdownAdded(values.experiment, uuid, breakdown, isPrimary)+ }+ },+ sharedListeners.saveMetricConfigAndReload,+ ],+ removeMetricBreakdown: [+ ({ uuid, index, breakdown }, _breakpoint, _action, previousState): void => {+ if (values.experiment !== selectors.experiment(previousState)) {+ const isPrimary = isPrimaryMetric(values.experiment, uuid)+ actions.reportExperimentMetricBreakdownRemoved(values.experiment, uuid, breakdown, index, isPrimary)+ }+ },+ sharedListeners.saveMetricConfigAndReload,+ ],+ updateMetricBreakdownAttribution: sharedListeners.saveMetricConfigAndReload,+ updateMetricBreakdownLimit: sharedListeners.saveMetricConfigAndReload,setVariantExcluded: async ({ variantKey, excluded }, _breakpoint) => {// Build the list only after the queued saves land. A toggle sent while another one is unsaved// (the toast's Undo, for example) would otherwise send the older list and revert that change.