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): skip follow-up work when an experiment save fails (#113762)

Andersa5a0c80bb666
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
index 805357686f26..60e3d1a55fef 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
@@ -12,6 +12,7 @@ import { Experiment } from '~/types'
import { experimentLogic } from '../experimentLogic'
import { experimentMetricsLogic } from '../experimentMetricsLogic'
+import { modalsLogic } from '../modalsLogic'
import { runningTimeLogic } from './runningTimeLogic'
jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
@@ -172,6 +173,28 @@ describe('runningTimeLogic', () => {
})
})
+ describe('save', () => {
+ it('keeps the modal open with the edited config when the experiment save fails', async () => {
+ // A failed estimate request stops the automatic estimate from saving anything on mount.
+ calculateRunningTimeMock.mockRejectedValue(new Error('backend unavailable'))
+ api.update.mockRejectedValueOnce(new Error('network down'))
+
+ logic = runningTimeLogic({ experiment })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ modalsLogic.actions.openRunningTimeConfigModal()
+ logic.actions.setConfig({ mde: 7 })
+
+ await expectLogic(logic, () => logic.actions.save()).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledTimes(1)
+ expect(modalsLogic.values.isRunningTimeConfigModalOpen).toBe(true)
+ expect(logic.values.configOverrides).toEqual({ mde: 7 })
+ // The experiment save reports the failure itself, so the modal adds no second toast.
+ expect(lemonToast.error).toHaveBeenCalledTimes(1)
+ })
+ })
+
describe('isCalculating', () => {
it('stays true while the automatic estimate is in flight, then settles on success', async () => {
let resolveCalc: (value: unknown) => void = () => {}
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
index 1a3370f5ba5e..732637bde33d 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
@@ -20,7 +20,7 @@ import type {
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { CachedNewExperimentQueryResponse, ExperimentMetricUnion } from '../../../queries/schema/schema-general'
-import { experimentLogic } from '../experimentLogic'
+import { experimentLogic, saveExperimentUpdate } from '../experimentLogic'
import { experimentMetricsLogic } from '../experimentMetricsLogic'
import { modalsLogic } from '../modalsLogic'
import {
@@ -718,6 +718,7 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
const { config, numberOfVariants, experiment, currentProjectId } = values
actions.setSaving(true)
+ let saved = false
try {
let update: Partial<Experiment> & { update_feature_flag_params?: boolean }
if (config.mode === 'manual') {
@@ -773,7 +774,7 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
// Await so the experiment reflects the saved config before resetConfig below. Otherwise the
// transient (overrides cleared, experiment not yet updated) would re-trigger the automatic
// auto-persist with stale values and revert the save.
- await experimentLogic({ experimentId: props.experiment.id }).asyncActions.updateExperiment(update)
+ saved = await saveExperimentUpdate(props.experiment.id, update)
} catch {
// Keep the modal open (don't close/reset below) so the user can retry.
lemonToast.error('Failed to save running time settings. Please try again.')
@@ -781,6 +782,10 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
} finally {
actions.setSaving(false)
}
+ // A failed experiment save has already shown its error. Keep the modal open so the user can retry.
+ if (!saved) {
+ return
+ }
actions.closeRunningTimeConfigModal()
actions.resetConfig()
},
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index a52a7933aec3..16dd563c5dd5 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -34,6 +34,7 @@ import type { ExperimentHealthFindingApi } from 'products/experiments/frontend/g
import type { ExperimentHealthFinding } from 'products/experiments/frontend/health/experimentHealthFindingEvents'
import { ExperimentWarning, experimentLogic } from './experimentLogic'
+import { experimentMetricsLogic } from './experimentMetricsLogic'
import type { ExperimentSavedMetric } from './utils'
jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
@@ -456,6 +457,123 @@ describe('experimentLogic', () => {
expect(logic.values.primaryMetricsResults).toEqual([existingResult])
expect(logic.values.primaryMetricsResultsErrors).toEqual([null])
})
+
+ it('reloads cached results for the server metric list after a save conflict', async () => {
+ const staleResult = experimentMetricResultsSuccessJson.query_status
+ .results as unknown as CachedNewExperimentQueryResponse
+
+ logic.actions.setUnmodifiedExperiment(experiment)
+ logic.actions.setExperiment(experiment)
+ logic.actions.setPrimaryMetricsResults([staleResult])
+ jest.spyOn(api, 'update').mockRejectedValueOnce({
+ status: 409,
+ data: { detail: 'The experiment was changed since you loaded it.', current_version: 5 },
+ })
+ // Another editor removed every metric, so the stale result pairs with nothing on the server.
+ jest.spyOn(api, 'get').mockResolvedValueOnce({ ...experiment, version: 5, metrics: [], saved_metrics: [] })
+
+ await expectLogic(logic, () => logic.actions.updateExperimentMetrics())
+ .toDispatchActions([
+ (action) =>
+ action.type === logic.actionTypes.refreshExperimentResults &&
+ action.payload.forceRefresh === false,
+ ])
+ .toFinishAllListeners()
+
+ expect(logic.values.primaryMetricsResults).toEqual([])
+ })
+ })
+
+ describe('date changes', () => {
+ it.each([
+ ['start', 'start_date', (date: string) => logic.asyncActions.changeExperimentStartDate(date)],
+ ['end', 'end_date', (date: string) => logic.asyncActions.changeExperimentEndDate(date)],
+ ] as const)('report the %s date that the change replaced', async (boundary, field, change) => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ const oldDate = '2025-01-01T00:00:00Z'
+ const newDate = '2025-02-01T00:00:00Z'
+ logic.actions.setExperiment({ ...experiment, [field]: oldDate })
+ jest.spyOn(api, 'update').mockResolvedValueOnce({ ...experiment, [field]: newDate })
+
+ await change(newDate)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(captureSpy).toHaveBeenCalledWith(
+ `experiment ${boundary} date changed`,
+ expect.objectContaining({ [`old_${field}`]: oldDate, [`new_${field}`]: newDate })
+ )
+ })
+ })
+
+ describe('after a failed save', () => {
+ const secondaryUuid = experiment.metrics_secondary[0].uuid as string
+
+ it.each([
+ ['the start date change', (): void => logic.actions.changeExperimentStartDate('2026-01-01T00:00:00Z')],
+ ['the end date change', (): void => logic.actions.changeExperimentEndDate('2026-02-01T00:00:00Z')],
+ ['the exposure criteria save', (): void => logic.actions.updateExposureCriteria()],
+ [
+ 'the settings save',
+ (): void => logic.actions.updateExperimentSettings({ only_count_matured_users: true }),
+ ],
+ ['the variant exclusion', (): void => logic.actions.setVariantExcluded('test', true)],
+ [
+ 'the variant exclusion with recalculation on',
+ (): void => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {
+ [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,
+ })
+ logic.actions.setVariantExcluded('test', true)
+ },
+ ],
+ [
+ 'a metric move while results load',
+ (): void => {
+ logic.actions.setPrimaryMetricsResultsLoading(true)
+ logic.actions.moveMetricsBetweenSections(true, [secondaryUuid], [], [secondaryUuid])
+ },
+ ],
+ ])('%s skips the follow-up work', async (_name, dispatch) => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ logic.actions.setExperiment(experiment)
+ jest.spyOn(api, 'update').mockRejectedValueOnce(new Error('network down'))
+
+ // The follow-ups are checked before the failure is matched, because the matcher searches only
+ // the history after the last matched action, and some follow-ups fire before the save settles.
+ await expectLogic(logic, dispatch)
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions([
+ 'refreshExperimentResults',
+ 'loadPrimaryMetricsResults',
+ 'loadSecondaryMetricsResults',
+ 'loadExposures',
+ experimentMetricsLogic({ experiment }).actionTypes.triggerRecalculation,
+ ])
+ .toDispatchActions(['updateExperimentFailure'])
+
+ expect(lemonToast.success).not.toHaveBeenCalled()
+ // The error carries no HTTP status, so the global loader handler stays silent and the save toasts once.
+ expect(lemonToast.error).toHaveBeenCalledTimes(1)
+ expect(captureSpy).toHaveBeenCalledWith('experiment save failed', expect.objectContaining({ status: null }))
+ expect(captureSpy).not.toHaveBeenCalledWith(
+ expect.stringMatching(/^experiment (start|end) date changed$/),
+ expect.anything()
+ )
+ })
+
+ it('puts back the saved exposure criteria', async () => {
+ const saved = { ...experiment, exposure_criteria: { filterTestAccounts: true } } as Experiment
+ logic.actions.setUnmodifiedExperiment(saved)
+ logic.actions.setExperiment(saved)
+ logic.actions.setExposureCriteria({ filterTestAccounts: false })
+ jest.spyOn(api, 'update').mockRejectedValueOnce(new Error('network down'))
+
+ await expectLogic(logic, () => logic.actions.updateExposureCriteria())
+ .toDispatchActions(['updateExperimentFailure'])
+ .toFinishAllListeners()
+
+ expect(logic.values.experiment.exposure_criteria).toEqual({ filterTestAccounts: true })
+ })
})
describe('recalculation trigger mapping', () => {
@@ -1181,14 +1299,17 @@ describe('experimentLogic', () => {
await expectLogic(logic, () => {
logic.actions.moveMetricsBetweenSections(true, ['secondary-metric-uuid'], [], ['secondary-metric-uuid'])
})
- .toDispatchActions(['updateExperimentSuccess', 'retryPrimaryMetric'])
+ .toDispatchActionsInAnyOrder(['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 () => {
+ it.each([
+ ['are already loading', true],
+ ['start loading while the save waits in the queue', false],
+ ])('falls back to a full refresh when results %s', async (_name, loadingBeforeMove) => {
useMocks({
post: {
'/api/environments/:team/query/:kind': () => [
@@ -1210,17 +1331,28 @@ describe('experimentLogic', () => {
} as unknown as Experiment
logic.actions.setExperiment(testExperiment)
- logic.actions.setPrimaryMetricsResultsLoading(true)
- api.update.mockResolvedValue({
+ if (loadingBeforeMove) {
+ logic.actions.setPrimaryMetricsResultsLoading(true)
+ }
+ let finishSave: (saved: Experiment) => void = () => {}
+ api.update.mockReturnValueOnce(
+ new Promise<Experiment>((resolve) => {
+ finishSave = resolve
+ })
+ )
+
+ logic.actions.moveMetricsBetweenSections(false, ['primary-metric-uuid'], [], ['primary-metric-uuid'])
+ if (!loadingBeforeMove) {
+ logic.actions.setPrimaryMetricsResultsLoading(true)
+ }
+ finishSave({
...testExperiment,
metrics: [],
metrics_secondary: [primaryMetric],
primary_metrics_ordered_uuids: [],
- })
+ } as unknown as Experiment)
- await expectLogic(logic, () => {
- logic.actions.moveMetricsBetweenSections(false, ['primary-metric-uuid'], [], ['primary-metric-uuid'])
- })
+ await expectLogic(logic)
.toDispatchActions([
'updateExperiment',
// Moving a metric is metric-scoped: reuse the window so unchanged metrics stay cached.
@@ -1230,6 +1362,46 @@ describe('experimentLogic', () => {
])
.toFinishAllListeners()
})
+
+ it('realigns results to the server metric lists after a save conflict', 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.setUnmodifiedExperiment(testExperiment)
+ logic.actions.setExperiment(testExperiment)
+ logic.actions.setPrimaryMetricsResults([primaryMetricResult, otherPrimaryMetricResult])
+ logic.actions.setSecondaryMetricsResults([secondaryMetricResult])
+ api.update.mockRejectedValueOnce({
+ status: 409,
+ data: { detail: 'The experiment was changed since you loaded it.', current_version: 5 },
+ })
+ // Another editor swapped the two primary metrics, so each result now belongs at the other position.
+ jest.spyOn(api, 'get').mockResolvedValueOnce({
+ ...testExperiment,
+ version: 5,
+ metrics: [otherPrimaryMetric, primaryMetric],
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.moveMetricsBetweenSections(
+ false,
+ ['primary-metric-uuid', 'other-primary-uuid'],
+ [],
+ ['primary-metric-uuid']
+ )
+ })
+ .toDispatchActions(['updateExperimentFailure'])
+ .toFinishAllListeners()
+
+ expect(logic.values.experiment.metrics).toEqual([otherPrimaryMetric, primaryMetric])
+ expect(logic.values.primaryMetricsResults).toEqual([otherPrimaryMetricResult, primaryMetricResult])
+ expect(logic.values.secondaryMetricsResults).toEqual([secondaryMetricResult])
+ })
})
describe('tags refresh', () => {
it('reloads tagsModel after an update that changed tags', async () => {
@@ -2914,6 +3086,28 @@ describe('experimentLogic', () => {
expect(sentBody.excluded_variants).toHaveLength(2)
})
+ it('builds a toggle sent while another one is unsaved on top of that change', async () => {
+ jest.spyOn(api, 'update')
+ api.update.mockClear()
+ const existingExperiment = { ...experiment, excluded_variants: ['test-1'] } as Experiment
+ const echoExclusions = async (_url: string, body: unknown): Promise<Experiment> => ({
+ ...existingExperiment,
+ excluded_variants: (body as Partial<Experiment>).excluded_variants,
+ })
+ api.update.mockImplementationOnce(echoExclusions).mockImplementationOnce(echoExclusions)
+ logic.actions.setExperiment(existingExperiment)
+
+ await expectLogic(logic, () => {
+ logic.actions.setVariantExcluded('test-2', true)
+ logic.actions.setVariantExcluded('test-3', true)
+ }).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledTimes(2)
+ const secondBody = api.update.mock.calls[1][1] as Partial<Experiment>
+ expect(secondBody.excluded_variants).toEqual(['test-1', 'test-2', 'test-3'])
+ expect(logic.values.excludedVariants).toEqual(['test-1', 'test-2', 'test-3'])
+ })
+
it('setVariantExcluded(key, false) removes the key from the exclusion list', async () => {
await expectLogic(logic, () => {
logic.actions.setExperiment({
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 1de8e7a40e64..ccff7d2a357f 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -311,15 +311,24 @@ function isPrimaryMetric(experiment: Experiment, uuid: string): boolean {
* and returns whether the save succeeded. The loader still owns error reporting and conflict recovery.
*/
async function inflightUpdateSaved(cache: Record<string, any>): Promise<boolean> {
+ return (await inflightUpdateOutcome(cache)) === 'saved'
+}
+
+/**
+ * {@link inflightUpdateSaved} for a caller that must know how the save failed. After a `conflict`, the loader has
+ * replaced the experiment with the server's copy and kept only the scalar fields of the rejected update, so metric
+ * lists can differ from the ones the caller started with.
+ */
+async function inflightUpdateOutcome(cache: Record<string, any>): Promise<'saved' | 'conflict' | 'failed'> {
const updatePromise: Promise<Experiment> | undefined = cache.inflightUpdate?.promise
if (!updatePromise) {
- return false
+ return 'failed'
}
try {
await updatePromise
- return true
- } catch {
- return false
+ return 'saved'
+ } catch (error) {
+ return isExperimentConflictError(error) ? 'conflict' : 'failed'
}
}
@@ -2371,24 +2380,32 @@ export const experimentLogic = kea<experimentLogicType>([
}
},
changeExperimentStartDate: async ({ startDate }) => {
- await asyncActions.updateExperiment({ start_date: startDate, update_feature_flag_params: false })
- // eslint-disable-next-line no-unused-expressions
+ // Read the old date before the save, because the save stores the response in values.experiment.
+ const oldStartDate = values.experiment?.start_date
+ actions.updateExperiment({ start_date: startDate, update_feature_flag_params: false })
+ if (!(await inflightUpdateSaved(cache))) {
+ return
+ }
if (values.experiment) {
posthog.capture('experiment start date changed', {
...getEventPropertiesForExperiment(values.experiment),
- old_start_date: values.experiment.start_date,
+ old_start_date: oldStartDate,
new_start_date: startDate,
})
}
actions.refreshExperimentResults(true, 'experiment_config_change')
},
changeExperimentEndDate: async ({ endDate }) => {
- await asyncActions.updateExperiment({ end_date: endDate, update_feature_flag_params: false })
- // eslint-disable-next-line no-unused-expressions
+ // Read the old date before the save, because the save stores the response in values.experiment.
+ const oldEndDate = values.experiment?.end_date
+ actions.updateExperiment({ end_date: endDate, update_feature_flag_params: false })
+ if (!(await inflightUpdateSaved(cache))) {
+ return
+ }
if (values.experiment) {
posthog.capture('experiment end date changed', {
...getEventPropertiesForExperiment(values.experiment),
- old_end_date: values.experiment.end_date,
+ old_end_date: oldEndDate,
new_end_date: endDate,
})
}
@@ -2698,25 +2715,18 @@ export const experimentLogic = kea<experimentLogicType>([
metrics_secondary: values.experiment.metrics_secondary,
update_feature_flag_params: false,
})
-
- // kea-loaders turns a rejected loader into a failure action, so awaiting its async action does
- // not throw. Await the underlying queued request instead to keep the existing result caches when
- // the save fails. The loader still owns error reporting and optimistic-concurrency recovery.
- const updatePromise = cache.inflightUpdate?.promise
- if (!updatePromise) {
- return
- }
- try {
- await updatePromise
- } catch {
+ const outcome = await inflightUpdateOutcome(cache)
+ // After most failures the previous experiment and its results remain valid and visible. After a
+ // conflict the loader has swapped in the server's metric lists, so the previous results no longer
+ // pair with them.
+ if (outcome === 'failed') {
return
}
- // Metric results are positional. Once the metric list has saved, keeping the previous arrays
+ // Metric results are positional. Once the metric list has changed, keeping the previous arrays
// around can briefly pair a result with the wrong metric (and gives no feedback while the
// updated results are computed). Clear both result stores so every metric in the updated list
- // renders its existing per-variant loading skeleton. Do this only after a successful save: if
- // the update fails, the previous experiment and its results remain valid and visible.
+ // renders its existing per-variant loading skeleton.
actions.clearMetricsResults()
const metricsLogic = experimentMetricsLogic({ experiment: values.experiment })
metricsLogic.actions.setPrimaryMetricsResults([])
@@ -2724,8 +2734,9 @@ export const experimentLogic = kea<experimentLogicType>([
metricsLogic.actions.setSecondaryMetricsResults([])
metricsLogic.actions.setSecondaryMetricsResultsErrors([])
- // Reload results for added/edited metrics
- actions.refreshExperimentResults(true, 'metric_config_change')
+ // Reload results for added/edited metrics. After a conflict this edit did not save, so nothing
+ // needs a recompute and cached results are enough.
+ actions.refreshExperimentResults(outcome === 'saved', 'metric_config_change')
},
updateExposureCriteria: async () => {
actions.updateExperiment({
@@ -2734,12 +2745,25 @@ export const experimentLogic = kea<experimentLogicType>([
},
update_feature_flag_params: false,
})
+ const outcome = await inflightUpdateOutcome(cache)
+ if (outcome !== 'saved') {
+ // The modal closes before the save settles. After a conflict the loader keeps the edit for
+ // review. After any other failure, put back the saved criteria, so the page does not show
+ // criteria that the server does not have.
+ if (outcome === 'failed' && values.unmodifiedExperiment) {
+ actions.setExperiment({ exposure_criteria: values.unmodifiedExperiment.exposure_criteria })
+ }
+ return
+ }
actions.refreshExperimentResults(true, 'experiment_config_change')
},
updateExperimentSettings: async ({ update }) => {
// Settings like stats config, CUPED, and conversion-window handling change
// how metrics and exposures are computed, so persist then re-query.
- await asyncActions.updateExperiment({ ...update, update_feature_flag_params: false })
+ actions.updateExperiment({ ...update, update_feature_flag_params: false })
+ if (!(await inflightUpdateSaved(cache))) {
+ return
+ }
// Unlaunched experiments have no results to recalculate, so don't promise a recalculation.
lemonToast.success(
values.isExperimentLaunched ? 'Settings saved. Recalculating results…' : 'Settings saved'
@@ -3402,9 +3426,16 @@ export const experimentLogic = kea<experimentLogicType>([
}))
}
- await asyncActions.updateExperiment(update)
+ actions.updateExperiment(update)
+ // After a conflict the loader has swapped in the server's metric lists, so the results must
+ // follow that layout too.
+ if ((await inflightUpdateOutcome(cache)) === 'failed') {
+ return
+ }
- if (!canReuseResults) {
+ // The save can wait behind other updates in the queue, and a results load can start meanwhile.
+ // A realign would then overwrite the arrays that this load fills.
+ if (!canReuseResults || values.primaryMetricsResultsLoading || values.secondaryMetricsResultsLoading) {
actions.refreshExperimentResults(true, 'metric_config_change')
return
}
@@ -3622,48 +3653,51 @@ export const experimentLogic = kea<experimentLogicType>([
}
},
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.
+ while (cache.inflightUpdate) {
+ await cache.inflightUpdate.promise.catch(() => {})
+ }
const current = values.excludedVariants
const next = excluded
? Array.from(new Set([...current, variantKey]))
: current.filter((k: string) => k !== variantKey)
- try {
- // excluded_variants is the canonical column; the backend mirrors it into the
- // deprecated `parameters` blob. No need to resend feature_flag_variants — the
- // backend validates exclusions against the linked flag. The column updates
- // atomically, so we just send the new list.
- await asyncActions.updateExperiment({
- excluded_variants: next,
- })
- lemonToast.success(
- excluded
- ? `Variant ${variantKey} excluded from analysis`
- : `Variant ${variantKey} re-included in analysis`,
- {
- button: {
- label: 'Undo',
- action: () => actions.setVariantExcluded(variantKey, !excluded),
- },
- }
- )
- // Re-fetch results since the variant set changed. On the recalculation flow this advances the
- // window (experiment_config_change), so every metric recomputes; legacy uses the per-metric
- // loaders. Exposures refresh either way.
- if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
- // eslint-disable-next-line no-unused-expressions
- values.experiment &&
- experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(
- 'experiment_config_change'
- )
- } else {
- actions.loadPrimaryMetricsResults(true)
- actions.loadSecondaryMetricsResults(true)
+ // excluded_variants is the canonical column; the backend mirrors it into the
+ // deprecated `parameters` blob. No need to resend feature_flag_variants — the
+ // backend validates exclusions against the linked flag. The column updates
+ // atomically, so we just send the new list.
+ actions.updateExperiment({
+ excluded_variants: next,
+ })
+ if (!(await inflightUpdateSaved(cache))) {
+ return
+ }
+ lemonToast.success(
+ excluded
+ ? `Variant ${variantKey} excluded from analysis`
+ : `Variant ${variantKey} re-included in analysis`,
+ {
+ button: {
+ label: 'Undo',
+ action: () => actions.setVariantExcluded(variantKey, !excluded),
+ },
}
- actions.loadExposures(true)
- } catch (error) {
- lemonToast.error('Could not update variant exclusion. Please try again.')
- throw error
+ )
+ // Re-fetch results since the variant set changed. On the recalculation flow this advances the
+ // window (experiment_config_change), so every metric recomputes; legacy uses the per-metric
+ // loaders. Exposures refresh either way.
+ if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
+ // eslint-disable-next-line no-unused-expressions
+ values.experiment &&
+ experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(
+ 'experiment_config_change'
+ )
+ } else {
+ actions.loadPrimaryMetricsResults(true)
+ actions.loadSecondaryMetricsResults(true)
}
+ actions.loadExposures(true)
},
})),
loaders(({ actions, values, cache }) => ({
@@ -3711,6 +3745,11 @@ export const experimentLogic = kea<experimentLogicType>([
actions.setExperiment(response)
return response
} catch (error: any) {
+ posthog.capture('experiment save failed', {
+ experiment_id: values.experimentId,
+ fields: Object.keys(update).filter((field) => field !== 'update_feature_flag_params'),
+ status: error?.status ?? null,
+ })
if (isExperimentConflictError(error)) {
lemonToast.error(
error.data?.detail ||
@@ -3730,6 +3769,11 @@ export const experimentLogic = kea<experimentLogicType>([
} catch {
actions.loadExperiment()
}
+ } else if (error?.status === undefined) {
+ // The loader onFailure handler in initKea toasts only errors that carry an HTTP
+ // status. Without this toast, a request that got no response (offline, blocked,
+ // dropped) would fail with no feedback.
+ lemonToast.error('Could not save the experiment. Check your connection and try again.')
}
throw error
}
@@ -4173,3 +4217,17 @@ export const experimentLogic = kea<experimentLogicType>([
],
}),
])
+
+/**
+ * Saves an update through the update queue of the mounted experiment logic and resolves to whether it saved. For a
+ * caller outside the logic: awaiting `asyncActions.updateExperiment()` resolves even when the save fails, and the
+ * loader still reports the error.
+ */
+export async function saveExperimentUpdate(
+ experimentId: ExperimentIdType,
+ update: ExperimentUpdatePayload
+): Promise<boolean> {
+ const logic = experimentLogic({ experimentId })
+ logic.actions.updateExperiment(update)
+ return await inflightUpdateSaved(logic.cache)
+}