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): three-way merge scalar fields in stale updates (#77437)

Marcel Poelker384113e31fd1
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
new file mode 100644
index 000000000000..836c31b219e7
--- /dev/null
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
@@ -0,0 +1,155 @@
+import { api } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { Experiment } from '~/types'
+
+import { experimentLogic } from '../experimentLogic'
+import { runningTimeLogic } from './runningTimeLogic'
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: {
+ success: jest.fn(),
+ error: jest.fn(),
+ info: jest.fn(),
+ },
+}))
+
+const calculateRunningTimeMock = jest.fn()
+jest.mock('products/experiments/frontend/generated/api', () => ({
+ ...jest.requireActual('products/experiments/frontend/generated/api'),
+ experimentsCalculateRunningTimeCreate: (...args: any[]) => calculateRunningTimeMock(...args),
+}))
+
+const EXPERIMENT_ID = 99
+const METRIC_UUID = 'metric-1'
+
+// A launched experiment ten days in, so the automatic estimate has a live baseline to work from.
+const TEN_DAYS_AGO = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString()
+const experiment = {
+ id: EXPERIMENT_ID,
+ name: 'Auto-save race',
+ feature_flag_key: 'autosave-race',
+ start_date: TEN_DAYS_AGO,
+ end_date: null,
+ metrics: [
+ {
+ kind: 'ExperimentMetric',
+ uuid: METRIC_UUID,
+ metric_type: 'mean',
+ source: { kind: 'EventsNode', event: '$pageview' },
+ },
+ ],
+ metrics_secondary: [],
+ saved_metrics: [],
+ primary_metrics_ordered_uuids: [METRIC_UUID],
+ secondary_metrics_ordered_uuids: [],
+ parameters: {},
+ running_time_calculation: {},
+ version: 3,
+} as unknown as Experiment
+
+const metricResultsWithBaseline = [
+ {
+ metric_uuid: METRIC_UUID,
+ baseline: { key: 'control', number_of_samples: 600, sum: 120, sum_squares: 48 },
+ variant_results: [{ key: 'test', number_of_samples: 600, sum: 130, sum_squares: 52 }],
+ },
+] as any[]
+
+describe('runningTimeLogic', () => {
+ let logic: ReturnType<typeof runningTimeLogic.build>
+ let experimentLogicInstance: ReturnType<typeof experimentLogic.build>
+ let getSpy: jest.SpyInstance | undefined
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team/experiments': { count: 0, next: null, previous: null, results: [] },
+ '/api/projects/:team/experiment_holdouts': { count: 0, next: null, previous: null, results: [] },
+ '/api/projects/:team/experiment_saved_metrics': { count: 0, next: null, previous: null, results: [] },
+ '/api/projects/:team/experiments/:id': experiment,
+ },
+ })
+ initKeaTests()
+ jest.spyOn(api, 'update')
+ api.update.mockClear()
+ calculateRunningTimeMock.mockReset()
+ ;(lemonToast.error as jest.Mock).mockClear()
+
+ experimentLogicInstance = experimentLogic({ experimentId: EXPERIMENT_ID })
+ experimentLogicInstance.mount()
+ experimentLogicInstance.actions.setExperiment(experiment)
+ experimentLogicInstance.actions.setUnmodifiedExperiment(experiment)
+ experimentLogicInstance.actions.setPrimaryMetricsResults(metricResultsWithBaseline)
+ })
+
+ afterEach(() => {
+ getSpy?.mockRestore()
+ getSpy = undefined
+ logic?.unmount()
+ experimentLogicInstance?.unmount()
+ })
+
+ describe('persistRunningTimeEstimate', () => {
+ it('auto-persists with the concurrency handshake and absorbs the response version', async () => {
+ calculateRunningTimeMock.mockResolvedValue({
+ recommended_sample_size: 2000,
+ recommended_running_time_days: 20,
+ })
+ api.update.mockResolvedValue({
+ ...experiment,
+ version: 4,
+ running_time_calculation: { recommended_running_time: 7, recommended_sample_size: 2000 },
+ })
+
+ logic = runningTimeLogic({ experiment })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['persistRunningTimeEstimate']).toFinishAllListeners()
+
+ // Without the version handshake this write bumps the server version invisibly,
+ // making every later scalar save from any open tab a guaranteed 409.
+ expect(api.update).toHaveBeenCalledWith(
+ expect.stringContaining(`/experiments/${EXPERIMENT_ID}`),
+ expect.objectContaining({
+ version: 3,
+ original_experiment: expect.objectContaining({ metrics: experiment.metrics }),
+ running_time_calculation: expect.objectContaining({ recommended_sample_size: 2000 }),
+ })
+ )
+ expect(experimentLogicInstance.values.unmodifiedExperiment?.version).toEqual(4)
+ expect(lemonToast.error).not.toHaveBeenCalled()
+ })
+
+ it('drops the estimate silently and resyncs the snapshot when it loses a concurrency race', async () => {
+ calculateRunningTimeMock.mockResolvedValue({
+ recommended_sample_size: 2000,
+ recommended_running_time_days: 20,
+ })
+ api.update.mockRejectedValue({
+ status: 409,
+ data: { detail: 'This experiment changed since you loaded it.', current_version: 9 },
+ })
+ getSpy = jest.spyOn(api, 'get').mockResolvedValue({
+ ...experiment,
+ version: 9,
+ running_time_calculation: { recommended_running_time: 11, recommended_sample_size: 2400 },
+ })
+
+ logic = runningTimeLogic({ experiment })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['persistRunningTimeEstimate']).toFinishAllListeners()
+
+ // A machine-written estimate losing a race is not a user problem: no error toast,
+ // just resync so the tab stops being stale and the estimate recomputes from fresh state.
+ expect(lemonToast.error).not.toHaveBeenCalled()
+ expect(experimentLogicInstance.values.unmodifiedExperiment?.version).toEqual(9)
+ })
+ })
+})
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
index 901b35aacaf4..2d78cc4a0763 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
@@ -23,7 +23,13 @@ import { experimentLogic } from '../experimentLogic'
import { experimentMetricsLogic } from '../experimentMetricsLogic'
import { isLaunched } from '../experimentsLogic'
import { modalsLogic } from '../modalsLogic'
-import { getFlagVariants, getOrderedMetricsWithResults } from '../utils'
+import {
+ getFlagVariants,
+ getOrderedMetricsWithResults,
+ initializeMetricOrdering,
+ isExperimentConflictError,
+ toConcurrencyPayload,
+} from '../utils'
import {
ManualCalculatorMetricType,
baselineStatsFromResults,
@@ -62,6 +68,7 @@ export interface runningTimeLogicValues {
result: any
}[] // experimentLogic
primaryMetricsResultsLoading: boolean // experimentLogic
+ unmodifiedExperiment: Experiment | null // experimentLogic
recalcPrimaryMetricsResults: CachedNewExperimentQueryResponse[] // experimentMetricsLogic
recalcPrimaryMetricsResultsErrors: (unknown | null)[] // experimentMetricsLogic
defaultMinimumDetectableEffect: number // experimentsConfigLogic
@@ -101,6 +108,9 @@ export interface runningTimeLogicActions {
setExperiment: (experiment: Partial<Experiment>) => {
experiment: Partial<Experiment>
} // experimentLogic
+ setUnmodifiedExperiment: (experiment: Experiment) => {
+ experiment: Experiment
+ } // experimentLogic
closeRunningTimeConfigModal: () => {
value: true
} // modalsLogic
@@ -263,7 +273,13 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
return {
values: [
experimentLogic({ experimentId }),
- ['experiment', 'orderedPrimaryMetricsWithResults', 'primaryMetricsResultsLoading', 'currentProjectId'],
+ [
+ 'experiment',
+ 'unmodifiedExperiment',
+ 'orderedPrimaryMetricsWithResults',
+ 'primaryMetricsResultsLoading',
+ 'currentProjectId',
+ ],
// On the recalculation flow, metric results live in experimentMetricsLogic, not experimentLogic.
experimentMetricsLogic({ experiment: props.experiment }),
[
@@ -279,7 +295,7 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
],
actions: [
experimentLogic({ experimentId }),
- ['setExperiment'],
+ ['setExperiment', 'setUnmodifiedExperiment'],
modalsLogic,
['closeRunningTimeConfigModal'],
],
@@ -614,11 +630,38 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
recommended_sample_size: targetSampleSize,
}
- await api.update(`api/projects/${currentProjectId}/experiments/${props.experiment.id}`, {
- running_time_calculation: updatedRunningTimeCalculation,
- })
-
- actions.setExperiment({ running_time_calculation: updatedRunningTimeCalculation })
+ // This write bumps the experiment's concurrency version like any other, so it must
+ // carry the handshake and absorb the response — otherwise every open tab of a running
+ // experiment goes silently stale on results load and later scalar saves 409.
+ try {
+ const response: Experiment = await api.update(
+ `api/projects/${currentProjectId}/experiments/${props.experiment.id}`,
+ {
+ ...toConcurrencyPayload(values.unmodifiedExperiment),
+ running_time_calculation: updatedRunningTimeCalculation,
+ }
+ )
+ actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(response)))
+ actions.setExperiment({
+ running_time_calculation: response.running_time_calculation ?? updatedRunningTimeCalculation,
+ })
+ } catch (error: any) {
+ if (!isExperimentConflictError(error)) {
+ throw error
+ }
+ // A machine-written estimate losing a race is not a user problem: drop it silently
+ // and resync the snapshot so this tab stops being stale (and the guard above stops
+ // re-persisting the same values against fresh server state).
+ try {
+ const fresh: Experiment = await api.get(
+ `api/projects/${currentProjectId}/experiments/${props.experiment.id}`
+ )
+ actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(fresh)))
+ actions.setExperiment({ running_time_calculation: fresh.running_time_calculation })
+ } catch {
+ // Leave state as-is; the next full experiment load resyncs the snapshot.
+ }
+ }
},
save: async () => {
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 3c09a9365cf6..5db782b0fb28 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -559,6 +559,29 @@ describe('experimentLogic', () => {
)
})
+ it.each([
+ ['variant notes', (): void => logic.actions.updateExperimentVariantNotes({ control: 'a note' })],
+ ['variant images', (): void => logic.actions.updateExperimentVariantImages({ control: ['media-id-1'] })],
+ ])('includes the concurrency payload on the raw %s write path', async (_name, dispatch) => {
+ const snapshot = { ...experiment, version: 6 } as Experiment
+ logic.actions.setUnmodifiedExperiment(snapshot)
+ logic.actions.setExperiment(snapshot)
+ api.update.mockResolvedValue({ ...snapshot, version: 7 })
+
+ await expectLogic(logic, dispatch).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledWith(
+ expect.stringContaining('/experiments/'),
+ expect.objectContaining({
+ version: 6,
+ original_experiment: expect.objectContaining({ metrics: snapshot.metrics }),
+ })
+ )
+ // The write bumped the version server-side; the snapshot must absorb the response,
+ // or every later save from this tab is stale and can 409.
+ expect(logic.values.unmodifiedExperiment?.version).toEqual(7)
+ })
+
it('reloads fresh state but keeps the rejected scalar edit on a version conflict', async () => {
const snapshot = { ...experiment, version: 1 } as Experiment
logic.actions.setUnmodifiedExperiment(snapshot)
@@ -1854,7 +1877,7 @@ describe('experimentLogic', () => {
api.update.mockClear()
})
- it('sends variant split and holdout via experiment update with update_feature_flag_params', async () => {
+ it('sends variant split via experiment update without resending an unchanged holdout', async () => {
const updatedExperiment = {
...experiment,
parameters: {
@@ -1867,6 +1890,7 @@ describe('experimentLogic', () => {
}
api.update.mockResolvedValue(updatedExperiment)
+ logic.actions.setUnmodifiedExperiment(experiment)
logic.actions.setExperiment(experiment)
await expectLogic(logic, () => {
@@ -1889,16 +1913,37 @@ describe('experimentLogic', () => {
},
},
},
- holdout_id: experiment.holdout_id,
update_feature_flag_params: true,
})
)
+ // An unchanged holdout must not ride along: resending it makes every stale
+ // distribution save read as a holdout edit and conflict server-side.
+ expect(api.update.mock.calls[0][1]).not.toHaveProperty('holdout_id')
// No rollout group when the caller omits rolloutPercentage (the modal itself always
// passes one; this covers the omit branch)
const sentFlagFilters = (api.update.mock.calls[0][1] as Record<string, any>).feature_flag.filters
expect(sentFlagFilters).not.toHaveProperty('groups')
})
+ it('sends holdout_id when the user changed it since the last save', async () => {
+ api.update.mockResolvedValue(experiment)
+
+ logic.actions.setUnmodifiedExperiment({ ...experiment, holdout_id: null } as Experiment)
+ logic.actions.setExperiment({ ...experiment, holdout_id: 42 } as Experiment)
+
+ await expectLogic(logic, () => {
+ logic.actions.updateDistribution([
+ { key: 'control', rollout_percentage: 60 },
+ { key: 'test', rollout_percentage: 40 },
+ ])
+ }).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledWith(
+ expect.stringContaining('/experiments/'),
+ expect.objectContaining({ holdout_id: 42 })
+ )
+ })
+
it('does not call feature flag API directly', async () => {
api.update.mockResolvedValue(experiment)
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 2b4d90753dfb..5764e1b44ab8 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -2844,15 +2844,28 @@ export const experimentLogic = kea<experimentLogicType>([
...values.experiment.parameters,
variant_screenshot_media_ids: variantPreviewMediaIds,
}
- await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`, {
- parameters: updatedParameters,
- update_feature_flag_params: false,
- })
+ const response: Experiment = await api.update(
+ `api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,
+ {
+ ...toConcurrencyPayload(values.unmodifiedExperiment),
+ parameters: updatedParameters,
+ update_feature_flag_params: false,
+ }
+ )
+ actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(response)))
actions.setExperiment({
parameters: updatedParameters,
})
- } catch {
- lemonToast.error('Failed to update experiment variant images')
+ } catch (error: any) {
+ if (isExperimentConflictError(error)) {
+ lemonToast.error(
+ error.data?.detail ||
+ 'This experiment was changed while you were editing it. Review the latest changes and try again.'
+ )
+ actions.loadExperiment()
+ } else {
+ lemonToast.error('Failed to update experiment variant images')
+ }
}
},
updateExperimentVariantNotes: async ({ variantNotes }) => {
@@ -2861,18 +2874,35 @@ export const experimentLogic = kea<experimentLogicType>([
...values.experiment.parameters,
variant_notes: variantNotes,
}
- await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`, {
- parameters: updatedParameters,
- update_feature_flag_params: false,
- })
+ const response: Experiment = await api.update(
+ `api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,
+ {
+ ...toConcurrencyPayload(values.unmodifiedExperiment),
+ parameters: updatedParameters,
+ update_feature_flag_params: false,
+ }
+ )
+ actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(response)))
actions.setExperiment({
parameters: updatedParameters,
})
- } catch {
- lemonToast.error('Failed to update experiment variant notes')
+ } catch (error: any) {
+ if (isExperimentConflictError(error)) {
+ lemonToast.error(
+ error.data?.detail ||
+ 'This experiment was changed while you were editing it. Review the latest changes and try again.'
+ )
+ actions.loadExperiment()
+ } else {
+ lemonToast.error('Failed to update experiment variant notes')
+ }
}
},
updateDistribution: async ({ variants, rolloutPercentage }) => {
+ // Resending an unchanged holdout would make every stale distribution save read as a
+ // holdout edit server-side; include it only when the selector actually changed it.
+ const holdoutChanged =
+ (values.experiment.holdout_id ?? null) !== (values.unmodifiedExperiment?.holdout_id ?? null)
actions.updateExperiment({
feature_flag: {
filters: {
@@ -2882,7 +2912,7 @@ export const experimentLogic = kea<experimentLogicType>([
: {}),
},
},
- holdout_id: values.experiment.holdout_id,
+ ...(holdoutChanged ? { holdout_id: values.experiment.holdout_id } : {}),
update_feature_flag_params: true,
})
},
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index 15802179038f..49834f8cbef1 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -51,6 +51,7 @@ import {
isLegacyExperimentQuery,
metricResults,
percentageDistribution,
+ toConcurrencyPayload,
toExperimentWritePayload,
} from './utils'
@@ -2067,3 +2068,62 @@ describe('toExperimentWritePayload', () => {
})
})
})
+
+describe('toConcurrencyPayload', () => {
+ const unmodified = {
+ id: 7,
+ version: 4,
+ metrics: [{ uuid: 'm1' }],
+ metrics_secondary: [],
+ saved_metrics: [{ saved_metric: 11, metadata: { type: 'secondary' } }],
+ start_date: '2026-07-02T23:10:00Z',
+ end_date: null,
+ name: 'Checkout test',
+ description: 'Original description',
+ exposure_criteria: { filterTestAccounts: true },
+ stats_config: { method: 'bayesian' },
+ running_time_calculation: { recommended_running_time: 12 },
+ holdout_id: 5,
+ conclusion: null,
+ conclusion_comment: null,
+ parameters: {},
+ excluded_variants: [],
+ only_count_matured_users: false,
+ } as unknown as Experiment
+
+ it('sends the version plus metric collections and scalar bases for server-side three-way merge', () => {
+ const payload = toConcurrencyPayload(unmodified)
+
+ expect(payload.version).toEqual(4)
+ expect(payload.original_experiment).toEqual(
+ expect.objectContaining({
+ metrics: unmodified.metrics,
+ metrics_secondary: [],
+ saved_metrics_ids: [{ id: 11, metadata: { type: 'secondary' } }],
+ name: 'Checkout test',
+ description: 'Original description',
+ start_date: '2026-07-02T23:10:00Z',
+ end_date: null,
+ exposure_criteria: { filterTestAccounts: true },
+ stats_config: { method: 'bayesian' },
+ running_time_calculation: { recommended_running_time: 12 },
+ holdout_id: 5,
+ })
+ )
+ })
+
+ it('sends explicit nulls for absent scalar bases so the server can tell "empty" from "unknown"', () => {
+ // An undefined base is dropped by JSON serialization; the server then falls back to
+ // rejecting any change to that field, which is exactly the over-rejection being fixed.
+ const payload = toConcurrencyPayload({
+ ...unmodified,
+ start_date: undefined,
+ holdout_id: undefined,
+ exposure_criteria: undefined,
+ } as unknown as Experiment)
+
+ expect(payload.original_experiment?.start_date).toBeNull()
+ expect(payload.original_experiment?.holdout_id).toBeNull()
+ expect(payload.original_experiment?.exposure_criteria).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 4d30cad19dc7..e5f4aa9766b8 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -1262,9 +1262,28 @@ export type ExperimentUpdatePayload = Omit<Partial<Experiment>, 'feature_flag'>
original_experiment?: Record<string, any>
}
-/** Concurrency context for experiment PATCHes: the version last read plus the metric collections
- * that version belongs to, so the server can merge concurrent metric edits safely and reject
- * everything else with a 409 instead of letting a stale write clobber it. */
+/** The scalar fields experiment surfaces PATCH, sent as base values so the server can three-way
+ * merge them per field: a stale write only conflicts when the same field changed on both sides. */
+const CONCURRENCY_SCALAR_BASE_FIELDS = [
+ 'name',
+ 'description',
+ 'start_date',
+ 'end_date',
+ 'exposure_criteria',
+ 'stats_config',
+ 'running_time_calculation',
+ 'holdout_id',
+ 'conclusion',
+ 'conclusion_comment',
+ 'excluded_variants',
+ 'only_count_matured_users',
+ 'parameters',
+] as const
+
+/** Concurrency context for experiment PATCHes: the version last read plus the state that version
+ * belongs to (metric collections and scalar bases), so the server can merge concurrent edits per
+ * metric uuid / per field and reject only true same-field conflicts with a 409, instead of letting
+ * a stale write clobber them. */
export function toConcurrencyPayload(
unmodified: Experiment | null
): Pick<ExperimentUpdatePayload, 'version' | 'original_experiment'> {
@@ -1280,6 +1299,9 @@ export function toConcurrencyPayload(
id: sharedMetric.saved_metric,
metadata: sharedMetric.metadata,
})),
+ // Explicit null over undefined: a missing base key makes the server fall back to
+ // rejecting any change to that field, while null means "the field was empty".
+ ...Object.fromEntries(CONCURRENCY_SCALAR_BASE_FIELDS.map((field) => [field, unmodified[field] ?? null])),
},
}
}
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 62d8f5576f12..1e69895c349d 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -7,7 +7,7 @@ from copy import deepcopy
from datetime import date, datetime, timedelta
from enum import Enum
from typing import Any, Literal, TypedDict, get_args
-from uuid import uuid4
+from uuid import UUID, uuid4
from zoneinfo import ZoneInfo
from django.db import transaction
@@ -408,6 +408,88 @@ def _merge_saved_metric_links(
return merged, conflicts
+# The client base uses API field names while validated payloads use model field names.
+_SCALAR_BASE_ALIASES = {"holdout": "holdout_id"}
+
+_SCALAR_MISSING = object()
+
+
+# Canonicalization depth bound: values needing conversion (datetimes, model instances) only
+# occur in the shallow, schema-shaped parts of a payload, while the unrestricted JSON fields
+# can nest arbitrarily deep — beyond this depth values are JSON-native on all three sides,
+# so plain equality compares them correctly without recursing down the interpreter stack.
+_CONCURRENCY_VIEW_MAX_DEPTH = 32
+
+
+def _concurrency_value_view(value: Any, depth: int = 0) -> Any:
+ """A scalar value as compared for concurrency resolution, canonicalized so the three
+ representations of one field agree: the client's base echoes API JSON (ISO datetime
+ strings, related-object ids), the payload carries validated Python objects (datetimes,
+ model instances), and the row holds ORM values."""
+ if isinstance(value, datetime):
+ # Match DRF's rendering, which the client echoes back: isoformat with +00:00 as Z.
+ iso = value.isoformat()
+ return iso[:-6] + "Z" if iso.endswith("+00:00") else iso
+ if isinstance(value, UUID):
+ return str(value)
+ pk = getattr(value, "pk", None)
+ if pk is not None:
+ return pk
+ if depth >= _CONCURRENCY_VIEW_MAX_DEPTH:
+ return value
+ if isinstance(value, dict):
+ return {key: _concurrency_value_view(item, depth + 1) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_concurrency_value_view(item, depth + 1) for item in value]
+ return value
+
+
+def _scalar_merge_view(field: str, value: Any) -> Any:
+ """The value of one scalar payload field as compared for concurrency resolution.
+
+ ``parameters`` needs shape normalization on top of value canonicalization: reads project
+ the linked flag's config into it (``ExperimentBaseSerializer._project_feature_flag_config``)
+ while writes strip that config before storage, so a client-echoed base only matches the
+ stored column when all sides are compared flag-stripped, with empty and null collapsed.
+ """
+ if field == "parameters":
+ if value is None:
+ return {}
+ if isinstance(value, dict):
+ value = ExperimentService._strip_feature_flag_config(value)
+ return _concurrency_value_view(value)
+
+
+def _resolve_scalar_updates(update_data: dict, original: Mapping, current_values: Mapping) -> list[str]:
+ """Per-field three-way merge for the scalar (non-mergeable) fields of a stale write.
+
+ Per field: an echo of the current value is a no-op; if only this write changed it, it
+ applies; if only the other side changed it (the payload echoes the base), the field is
+ dropped so the concurrent edit survives; both sides changing it differently is a
+ conflict. Without a base value for the field, anything but an echo of the current value
+ conflicts — the conservative behavior clients that only send metric bases keep. Mutates
+ ``update_data`` in place (dropping other-side-owned fields) and returns the conflicting
+ field names, sorted.
+ """
+ conflicts: list[str] = []
+ scalar_fields = sorted(set(update_data) - CONCURRENCY_MERGEABLE_FIELDS - {"get_feature_flag_key"})
+ for field in scalar_fields:
+ mine = _scalar_merge_view(field, update_data[field])
+ current = _scalar_merge_view(field, current_values.get(field, _SCALAR_MISSING))
+ if mine == current:
+ continue
+ base = original.get(_SCALAR_BASE_ALIASES.get(field, field), _SCALAR_MISSING)
+ if base is not _SCALAR_MISSING:
+ base = _scalar_merge_view(field, base)
+ if base == current:
+ continue
+ if mine == base:
+ del update_data[field]
+ continue
+ conflicts.append(field)
+ return conflicts
+
+
class ExperimentQueryStatus(str, Enum):
"""
Filter values for the experiment list endpoint.
@@ -3057,6 +3139,18 @@ class ExperimentService:
for link in experiment.experimenttosavedmetric_set.all()
]
+ @staticmethod
+ def _current_scalar_values(experiment: Experiment, update_data: Mapping) -> dict[str, Any]:
+ """The stored values scalar payload fields resolve against, keyed by payload field name.
+
+ ``holdout`` reads the id column directly so the comparison never fetches the related row.
+ """
+ return {
+ field: (experiment.holdout_id if field == "holdout" else getattr(experiment, field, _SCALAR_MISSING))
+ for field in update_data
+ if field not in CONCURRENCY_MERGEABLE_FIELDS and field != "get_feature_flag_key"
+ }
+
def _resolve_concurrent_update(
self,
experiment: Experiment,
@@ -3066,26 +3160,28 @@ class ExperimentService:
) -> None:
"""Resolve a stale write (client version behind the row) against the current state.
- Only the metric collections are resolvable: they merge per uuid (each metric's
- server-assigned uuid preserves intent across concurrent edits), and client-supplied
- ordering arrays are reconciled to the current state — the ordering syncs re-derive
- the rest. A stale write touching anything else conflicts outright: scalar fields
- have no sub-identity to merge on, and the edit was likely written against context
- that has since changed. Scalar changes made by the *other* side never block a
- metric-only write — a PATCH that omits a field cannot clobber it. Mutates
- ``update_data`` in place, or raises ``ExperimentVersionConflict``.
+ The metric collections merge per uuid (each metric's server-assigned uuid preserves
+ intent across concurrent edits), and client-supplied ordering arrays are reconciled
+ to the current state — the ordering syncs re-derive the rest. Scalar fields merge
+ per field against their base value in ``original`` (see ``_resolve_scalar_updates``):
+ only a same-field double edit conflicts, so background writers bumping the version
+ (e.g. the running-time calculator auto-save) don't fail unrelated scalar saves.
+ Either side's changes never block a write that omits the field — a PATCH that omits
+ a field cannot clobber it. Mutates ``update_data`` in place, or raises
+ ``ExperimentVersionConflict``.
"""
if original is None:
raise ExperimentVersionConflict(current_version=current_version)
- payload_fields = {key for key in update_data if key != "get_feature_flag_key"}
- non_mergeable_payload = sorted(payload_fields - CONCURRENCY_MERGEABLE_FIELDS)
- if non_mergeable_payload:
+ scalar_conflicts = _resolve_scalar_updates(
+ update_data, original, self._current_scalar_values(experiment, update_data)
+ )
+ if scalar_conflicts:
raise ExperimentVersionConflict(
f"This experiment changed since you loaded it, and your update changes fields that "
- f"can't be merged ({', '.join(non_mergeable_payload)}). Review the latest changes and try again.",
+ f"can't be merged ({', '.join(scalar_conflicts)}). Review the latest changes and try again.",
current_version=current_version,
- conflicting_fields=non_mergeable_payload,
+ conflicting_fields=scalar_conflicts,
)
conflict_uuids: list[str] = []
@@ -3192,7 +3288,7 @@ class ExperimentService:
resolution="merged",
versions_behind=current_version - client_version,
base_snapshot_sent=True,
- merged_fields=sorted(set(update_data) & CONCURRENCY_MERGEABLE_FIELDS),
+ merged_fields=sorted(set(update_data) - {"get_feature_flag_key"}),
)
resolution_version = current_version
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 2c1f18cbdb12..0e8089c473c0 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -393,9 +393,10 @@ class ExperimentSerializer(ExperimentBaseSerializer):
help_text=(
"Optimistic-concurrency token. Reads return the experiment's current version, bumped on "
"every update. Send the version you last read with an update to detect concurrent edits: "
- "a stale update that only touches the metric collections is merged per metric uuid when "
- "`original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip "
- "the check."
+ "a stale update merges concurrent changes where safe — metric collections per metric "
+ "uuid, other fields per field — using the base values sent in `original_experiment`, and "
+ "fails with HTTP 409 only when the same metric or field changed on both sides (or no "
+ "base value was sent for a changed field). Omit to skip the check."
),
)
original_experiment = serializers.DictField(
@@ -403,11 +404,13 @@ class ExperimentSerializer(ExperimentBaseSerializer):
allow_null=True,
write_only=True,
help_text=(
- "The metric collections as the client last read them, used together with `version` to "
- "resolve concurrent metric edits: changes made by other users are merged per metric uuid "
- "where safe instead of failing. Relevant keys are metrics, metrics_secondary, and "
- "saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails "
- "with HTTP 409."
+ "The experiment state as the client last read it, used together with `version` to "
+ "resolve concurrent edits: metric collections merge per metric uuid, and any other "
+ "field the update carries merges per field against its base value here (only a "
+ "same-field double edit fails). Relevant keys are metrics, metrics_secondary, "
+ "saved_metrics_ids, plus the last-read values of whichever scalar fields the update "
+ "writes; unknown keys are ignored. Changed fields without a base value — and, without "
+ "this object, any version mismatch — fail with HTTP 409."
),
)
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index de4a6133f7f2..f79d3316a50b 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -1,8 +1,9 @@
import json
from contextlib import contextmanager
from copy import deepcopy
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
from decimal import Decimal
+from types import SimpleNamespace
from typing import Any
from uuid import UUID, uuid4
@@ -42,6 +43,7 @@ from products.experiments.backend.experiment_service import (
_deprecated_parameters_keys_in_request,
_merge_metric_arrays,
_merge_saved_metric_links,
+ _resolve_scalar_updates,
)
from products.experiments.backend.models.experiment import (
EXPOSURE_FROZEN_COHORT_KEY,
@@ -6983,3 +6985,155 @@ class TestConcurrentMetricMerge(SimpleTestCase):
self.assertEqual(conflicts, [])
self.assertEqual(merged, [{"id": 1, "metadata": {"type": "secondary"}}])
+
+
+class TestScalarConcurrencyResolution(SimpleTestCase):
+ """Branch pins for the per-field scalar three-way merge behind experiment optimistic
+ concurrency, isolating the value canonicalization the API tests can't reach directly:
+ the client base echoes API JSON (ISO datetime strings, holdout ids) while the payload
+ and row carry validated Python objects (datetimes, model instances)."""
+
+ @parameterized.expand(
+ [
+ (
+ "noop_equal_value_passes_without_base",
+ {"description": "same"},
+ {},
+ {"description": "same"},
+ {"description": "same"},
+ [],
+ ),
+ (
+ "only_mine_changed_applies",
+ {"description": "mine"},
+ {"description": "base"},
+ {"description": "base"},
+ {"description": "mine"},
+ [],
+ ),
+ (
+ "echo_of_base_drops_so_theirs_survives",
+ {"description": "base", "name": "renamed by me"},
+ {"description": "base", "name": "base name"},
+ {"description": "theirs", "name": "base name"},
+ {"name": "renamed by me"},
+ [],
+ ),
+ (
+ "both_changed_same_field_conflicts",
+ {"description": "mine"},
+ {"description": "base"},
+ {"description": "theirs"},
+ {"description": "mine"},
+ ["description"],
+ ),
+ (
+ "missing_base_with_real_change_conflicts",
+ {"description": "mine"},
+ {},
+ {"description": "theirs"},
+ {"description": "mine"},
+ ["description"],
+ ),
+ (
+ "iso_string_base_matches_stored_datetime",
+ {"start_date": datetime(2026, 7, 27, 16, 10, tzinfo=UTC)},
+ {"start_date": "2026-07-02T23:10:00Z"},
+ {"start_date": datetime(2026, 7, 2, 23, 10, tzinfo=UTC)},
+ {"start_date": datetime(2026, 7, 27, 16, 10, tzinfo=UTC)},
+ [],
+ ),
+ (
+ "holdout_instance_compares_by_id_to_the_holdout_id_base",
+ {"holdout": SimpleNamespace(pk=7)},
+ {"holdout_id": 5},
+ {"holdout": 5},
+ {"holdout": SimpleNamespace(pk=7)},
+ [],
+ ),
+ (
+ "mergeable_metric_collections_are_left_alone",
+ {"metrics": [{"uuid": "m1"}], "description": "same"},
+ {},
+ {"description": "same"},
+ {"metrics": [{"uuid": "m1"}], "description": "same"},
+ [],
+ ),
+ (
+ # Reads project the linked flag's config into `parameters` (with split_percent),
+ # so the client base carries keys the stored column and validated payload never
+ # hold; compared in stored shape this is "only mine changed", not a conflict.
+ "parameters_flag_projection_in_base_is_not_a_conflict",
+ {"parameters": {"variant_notes": {"control": "note"}}},
+ {
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50, "split_percent": 50},
+ {"key": "test", "rollout_percentage": 50, "split_percent": 50},
+ ],
+ "rollout_percentage": 100,
+ "ensure_experience_continuity": False,
+ }
+ },
+ {"parameters": None},
+ {"parameters": {"variant_notes": {"control": "note"}}},
+ [],
+ ),
+ (
+ "parameters_double_edit_still_conflicts",
+ {"parameters": {"variant_notes": {"control": "mine"}}},
+ {"parameters": {"feature_flag_variants": [{"key": "control", "rollout_percentage": 100}]}},
+ {"parameters": {"variant_notes": {"control": "theirs"}}},
+ {"parameters": {"variant_notes": {"control": "mine"}}},
+ ["parameters"],
+ ),
+ ]
+ )
+ def test_resolve_scalar_updates(
+ self,
+ _name: str,
+ update_data: dict,
+ original: dict,
+ current_values: dict,
+ expected_update_data: dict,
+ expected_conflicts: list[str],
+ ) -> None:
+ conflicts = _resolve_scalar_updates(update_data, original, current_values)
+
+ self.assertEqual(conflicts, expected_conflicts)
+ self.assertEqual(update_data, expected_update_data)
+
+ def test_microsecond_datetime_base_roundtrips_like_drf(self) -> None:
+ # DRF renders aware UTC datetimes as `isoformat()` with `+00:00` folded to `Z`,
+ # microseconds included — the client echoes that string back as the base.
+ stored = datetime(2026, 8, 3, 18, 5, 3, 123456, tzinfo=UTC)
+ update_data = {"end_date": datetime(2026, 8, 10, tzinfo=UTC)}
+
+ conflicts = _resolve_scalar_updates(
+ update_data, {"end_date": "2026-08-03T18:05:03.123456Z"}, {"end_date": stored}
+ )
+
+ self.assertEqual(conflicts, [])
+ self.assertIn("end_date", update_data)
+
+ @parameterized.expand(
+ [
+ ("equal_deep_values_are_a_noop", "same", []),
+ ("differing_deep_values_conflict", "different", ["stats_config"]),
+ ]
+ )
+ def test_deeply_nested_payload_value_does_not_crash(self, _name: str, current_leaf: str, expected: list) -> None:
+ # stats_config/exposure_criteria/parameters are unrestricted JSONFields, so a stale
+ # write can nest a few thousand levels in a few KB of body; resolving it must not
+ # recurse past the interpreter stack.
+ def nested(depth: int, leaf: str) -> dict[str, Any]:
+ value: dict[str, Any] = {"a": leaf}
+ for _ in range(depth - 1):
+ value = {"a": value}
+ return value
+
+ update_data = {"stats_config": nested(5000, "same")}
+
+ conflicts = _resolve_scalar_updates(update_data, {}, {"stats_config": nested(5000, current_leaf)})
+
+ self.assertEqual(conflicts, expected)
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 4497b2bf23d7..1594bb0b89ba 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -9146,6 +9146,31 @@ class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):
],
}
+ def _original_with_scalars(self, snapshot: dict) -> dict:
+ """The extended base the frontend sends: metric collections plus the scalar fields the
+ experiment surfaces PATCH, so the server can three-way merge scalars per field too."""
+ return {
+ **self._original(snapshot),
+ **{
+ field: snapshot.get(field)
+ for field in (
+ "name",
+ "description",
+ "start_date",
+ "end_date",
+ "exposure_criteria",
+ "stats_config",
+ "running_time_calculation",
+ "holdout_id",
+ "conclusion",
+ "conclusion_comment",
+ "parameters",
+ "excluded_variants",
+ "only_count_matured_users",
+ )
+ },
+ }
+
def _events(self, metrics: list) -> set[str]:
return {metric["source"]["event"] for metric in metrics}
@@ -9277,7 +9302,7 @@ class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):
else:
self.assertEqual(current_value, their_value)
- def test_stale_scalar_write_conflicts_with_any_concurrent_change(self) -> None:
+ def test_stale_scalar_write_without_base_value_conflicts_with_any_concurrent_change(self) -> None:
snapshot = self._create_experiment("stale-scalar", metrics=[self._metric("base")])
concurrent = self._patch(snapshot["id"], {"metrics": [*snapshot["metrics"], self._metric("theirs")]})
self.assertEqual(concurrent.status_code, status.HTTP_200_OK)
@@ -9294,6 +9319,143 @@ class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(stale_description_write.status_code, status.HTTP_409_CONFLICT)
self.assertIn("description", stale_description_write.json()["conflicting_fields"])
+ def test_stale_start_date_change_merges_over_concurrent_calculator_autosave(self) -> None:
+ # Incident replay: the running-time calculator auto-saves its estimate on results load,
+ # silently bumping the version; the user's start-date change from the same (now stale)
+ # tab must apply instead of 409ing. Also exercises the datetime base: the client echoes
+ # the ISO string it read while the row holds a datetime.
+ created = self._create_experiment("autosave-race", metrics=[self._metric("base")])
+ launch = self.client.post(f"/api/projects/{self.team.id}/experiments/{created['id']}/launch/")
+ self.assertEqual(launch.status_code, status.HTTP_200_OK, launch.json())
+ snapshot = launch.json()
+
+ autosave = self._patch(
+ snapshot["id"],
+ {"running_time_calculation": {"recommended_running_time": 12, "recommended_sample_size": 3400}},
+ )
+ self.assertEqual(autosave.status_code, status.HTTP_200_OK)
+
+ new_start = "2026-07-27T16:10:00Z"
+ stale_start_date_write = self._patch(
+ snapshot["id"],
+ {
+ "start_date": new_start,
+ "version": snapshot["version"],
+ "original_experiment": self._original_with_scalars(snapshot),
+ },
+ )
+
+ self.assertEqual(stale_start_date_write.status_code, status.HTTP_200_OK, stale_start_date_write.json())
+ result = stale_start_date_write.json()
+ self.assertEqual(parser.parse(result["start_date"]), parser.parse(new_start))
+ self.assertEqual(result["running_time_calculation"]["recommended_running_time"], 12)
+
+ @parameterized.expand(
+ [
+ ("with_scalar_base", True),
+ ("without_scalar_base", False),
+ ]
+ )
+ def test_stale_write_resending_unchanged_scalar_is_not_a_conflict(self, _name: str, with_base: bool) -> None:
+ # The distribution modal resends holdout_id even when the user only changed the variant
+ # split; an unchanged value must not conflict just because the write is stale.
+ holdout = ExperimentHoldout.objects.create(
+ team=self.team,
+ name=f"Concurrency holdout {_name}",
+ filters=[{"properties": [], "rollout_percentage": 10, "variant": "holdout-x"}],
+ created_by=self.user,
+ )
+ created = self._create_experiment(f"noop-holdout-{with_base}", metrics=[self._metric("base")])
+ linked = self._patch(created["id"], {"holdout_id": holdout.id})
+ self.assertEqual(linked.status_code, status.HTTP_200_OK)
+ snapshot = linked.json()
+
+ concurrent = self._patch(snapshot["id"], {"metrics": [*snapshot["metrics"], self._metric("theirs")]})
+ self.assertEqual(concurrent.status_code, status.HTTP_200_OK)
+
+ stale_echo = self._patch(
+ snapshot["id"],
+ {
+ "holdout_id": holdout.id,
+ "version": snapshot["version"],
+ "original_experiment": self._original_with_scalars(snapshot) if with_base else self._original(snapshot),
+ },
+ )
+
+ self.assertEqual(stale_echo.status_code, status.HTTP_200_OK, stale_echo.json())
+ self.assertEqual(stale_echo.json()["holdout_id"], holdout.id)
+ self.assertEqual(self._events(stale_echo.json()["metrics"]), {"base", "theirs"})
+
+ def test_stale_write_echoing_base_scalar_does_not_revert_concurrent_edit(self) -> None:
+ # A form save resends fields the user didn't touch; echoing the base value must not
+ # revert what a teammate changed meanwhile, while the user's own edit still applies.
+ snapshot = self._create_experiment("echo-base", metrics=[self._metric("base")])
+ their_edit = self._patch(snapshot["id"], {"description": "rewritten by a teammate"})
+ self.assertEqual(their_edit.status_code, status.HTTP_200_OK)
+
+ stale_form_save = self._patch(
+ snapshot["id"],
+ {
+ "description": snapshot["description"],
+ "name": "New name from the stale tab",
+ "version": snapshot["version"],
+ "original_experiment": self._original_with_scalars(snapshot),
+ },
+ )
+
+ self.assertEqual(stale_form_save.status_code, status.HTTP_200_OK, stale_form_save.json())
+ self.assertEqual(stale_form_save.json()["description"], "rewritten by a teammate")
+ self.assertEqual(stale_form_save.json()["name"], "New name from the stale tab")
+
+ def test_stale_same_scalar_field_double_edit_still_conflicts(self) -> None:
+ # All three values must differ: an edit that matches the base is not "my change"
+ # (the echo rule), and one that matches the current value is a no-op.
+ snapshot = self._create_experiment("double-scalar", metrics=[self._metric("base")])
+ their_edit = self._patch(snapshot["id"], {"description": "their rewrite"})
+ self.assertEqual(their_edit.status_code, status.HTTP_200_OK)
+
+ stale_conflicting_edit = self._patch(
+ snapshot["id"],
+ {
+ "description": "my rewrite",
+ "version": snapshot["version"],
+ "original_experiment": self._original_with_scalars(snapshot),
+ },
+ )
+
+ self.assertEqual(stale_conflicting_edit.status_code, status.HTTP_409_CONFLICT)
+ self.assertEqual(stale_conflicting_edit.json()["conflicting_fields"], ["description"])
+ experiment = Experiment.objects.get(id=snapshot["id"])
+ self.assertEqual(experiment.description, "their rewrite")
+
+ def test_stale_variant_notes_write_merges_on_flag_linked_experiment(self) -> None:
+ # Incident replay for the variant notes/images path: reads project the linked flag's
+ # config into `parameters` while writes strip it before storage, so the client's base
+ # never matches the stored column byte-for-byte — the merge must compare `parameters`
+ # in stored shape instead of treating the projection as a concurrent edit.
+ snapshot = self._create_experiment("notes-over-autosave", metrics=[self._metric("base")])
+ self.assertIn("feature_flag_variants", snapshot["parameters"])
+
+ autosave = self._patch(
+ snapshot["id"],
+ {"running_time_calculation": {"recommended_running_time": 9, "recommended_sample_size": 1200}},
+ )
+ self.assertEqual(autosave.status_code, status.HTTP_200_OK)
+
+ stale_notes_write = self._patch(
+ snapshot["id"],
+ {
+ "parameters": {**snapshot["parameters"], "variant_notes": {"control": "baseline notes"}},
+ "version": snapshot["version"],
+ "original_experiment": self._original_with_scalars(snapshot),
+ },
+ )
+
+ self.assertEqual(stale_notes_write.status_code, status.HTTP_200_OK, stale_notes_write.json())
+ result = stale_notes_write.json()
+ self.assertEqual(result["parameters"]["variant_notes"], {"control": "baseline notes"})
+ self.assertEqual(result["running_time_calculation"]["recommended_running_time"], 9)
+
def test_stale_reorder_keeps_relative_order_and_appends_concurrent_addition(self) -> None:
snapshot = self._create_experiment("reorder", metrics=[self._metric("m1"), self._metric("m2")])
added = self._patch(snapshot["id"], {"metrics": [*snapshot["metrics"], self._metric("m3")]})
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 6110a4010b6d..5d57c0f0b332 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -825,7 +825,7 @@ export interface PaginatedExperimentBasicListApi {
}
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
export type ExperimentWriteApiOriginalExperiment = { [key: string]: unknown } | null
@@ -1491,12 +1491,12 @@ export interface ExperimentWriteApi {
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean
/**
- * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check.
+ * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check.
* @nullable
*/
version?: number | null
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
original_experiment?: ExperimentWriteApiOriginalExperiment
@@ -1516,7 +1516,7 @@ export interface ExperimentWriteApi {
}
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
export type ExperimentApiOriginalExperiment = { [key: string]: unknown } | null
@@ -1628,12 +1628,12 @@ export interface ExperimentApi {
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean
/**
- * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check.
+ * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check.
* @nullable
*/
version?: number | null
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
original_experiment?: ExperimentApiOriginalExperiment
@@ -1653,7 +1653,7 @@ export interface ExperimentApi {
}
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
export type PatchedExperimentWriteApiOriginalExperiment = { [key: string]: unknown } | null
@@ -1761,12 +1761,12 @@ export interface PatchedExperimentWriteApi {
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean
/**
- * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check.
+ * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check.
* @nullable
*/
version?: number | null
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
original_experiment?: PatchedExperimentWriteApiOriginalExperiment
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index de9f0fd02047..3e9b4b263631 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -28094,7 +28094,7 @@ export namespace Schemas {
} as const;
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
export type ExperimentOriginalExperiment = { [key: string]: unknown } | null;
@@ -28778,12 +28778,12 @@ export namespace Schemas {
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean;
/**
- * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check.
+ * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check.
* @nullable
*/
version?: number | null;
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
original_experiment?: ExperimentOriginalExperiment;
@@ -29586,7 +29586,7 @@ export namespace Schemas {
}
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
export type ExperimentWriteOriginalExperiment = { [key: string]: unknown } | null;
@@ -29694,12 +29694,12 @@ export namespace Schemas {
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean;
/**
- * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check.
+ * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check.
* @nullable
*/
version?: number | null;
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
original_experiment?: ExperimentWriteOriginalExperiment;
@@ -52569,7 +52569,7 @@ export namespace Schemas {
}
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
export type PatchedExperimentWriteOriginalExperiment = { [key: string]: unknown } | null;
@@ -52677,12 +52677,12 @@ export namespace Schemas {
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean;
/**
- * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check.
+ * Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check.
* @nullable
*/
version?: number | null;
/**
- * The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.
+ * The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
*/
original_experiment?: PatchedExperimentWriteOriginalExperiment;
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index f5ed7bcb8912..2debb7f8e53b 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -4477,13 +4477,13 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod
.number()
.nullish()
.describe(
- "Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check."
+ "Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check."
),
original_experiment: zod
.record(zod.string(), zod.unknown())
.nullish()
.describe(
- 'The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.'
+ 'The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.'
),
})
.describe('Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.')
@@ -8247,13 +8247,13 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod
.number()
.nullish()
.describe(
- "Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check."
+ "Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check."
),
original_experiment: zod
.record(zod.string(), zod.unknown())
.nullish()
.describe(
- 'The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.'
+ 'The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.'
),
})
.describe('Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.')
@@ -11989,13 +11989,13 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod
.number()
.nullish()
.describe(
- "Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update that only touches the metric collections is merged per metric uuid when `original_experiment` is also sent; anything else fails with HTTP 409. Omit to skip the check."
+ "Optimistic-concurrency token. Reads return the experiment's current version, bumped on every update. Send the version you last read with an update to detect concurrent edits: a stale update merges concurrent changes where safe — metric collections per metric uuid, other fields per field — using the base values sent in `original_experiment`, and fails with HTTP 409 only when the same metric or field changed on both sides (or no base value was sent for a changed field). Omit to skip the check."
),
original_experiment: zod
.record(zod.string(), zod.unknown())
.nullish()
.describe(
- 'The metric collections as the client last read them, used together with `version` to resolve concurrent metric edits: changes made by other users are merged per metric uuid where safe instead of failing. Relevant keys are metrics, metrics_secondary, and saved_metrics_ids; unknown keys are ignored. Without it, any version mismatch fails with HTTP 409.'
+ 'The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.'
),
})
.describe(