:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): optimistic concurrency for experiment updates (#71032)
Marcel Poelker8e31e96b4f5f
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 093c1820c861..3c09a9365cf6 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -501,6 +501,87 @@ describe('experimentLogic', () => {expect(logic.values.experiment.metrics_secondary).toEqual([])})})+ describe('optimistic concurrency', () => {+ let getSpy: jest.SpyInstance | undefined++ beforeEach(() => {+ jest.spyOn(api, 'update')+ api.update.mockClear()+ })++ afterEach(() => {+ // The conflict test stubs api.get. Left in place it also answers the+ // query polling later describe blocks rely on, so restore it here+ // rather than at the end of the test, where a failed assertion skips it.+ getSpy?.mockRestore()+ getSpy = undefined+ })++ it('sends version and original_experiment from the unmodified snapshot on update', async () => {+ const snapshot = { ...experiment, version: 3 } as Experiment+ logic.actions.setUnmodifiedExperiment(snapshot)+ logic.actions.setExperiment(snapshot)+ api.update.mockResolvedValue(snapshot)++ await expectLogic(logic, () => {+ logic.actions.updateExperiment({ description: 'updated' })+ }).toFinishAllListeners()++ expect(api.update).toHaveBeenCalledWith(+ expect.stringContaining('/experiments/'),+ expect.objectContaining({+ description: 'updated',+ version: 3,+ original_experiment: expect.objectContaining({+ metrics: snapshot.metrics,+ metrics_secondary: snapshot.metrics_secondary,+ }),+ })+ )+ })++ it('includes the concurrency payload on the raw shared-metric write path', async () => {+ const snapshot = { ...experiment, version: 2, saved_metrics: [], metrics_secondary: [] } as Experiment+ logic.actions.setUnmodifiedExperiment(snapshot)+ logic.actions.setExperiment(snapshot)+ api.update.mockResolvedValue(snapshot)++ await expectLogic(logic, () => {+ logic.actions.removeSharedMetricFromExperiment(12345)+ }).toFinishAllListeners()++ expect(api.update).toHaveBeenCalledWith(+ expect.stringContaining('/experiments/'),+ expect.objectContaining({+ version: 2,+ original_experiment: expect.objectContaining({ metrics: snapshot.metrics }),+ })+ )+ })++ 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)+ logic.actions.setExperiment(snapshot)+ api.update.mockRejectedValue({+ status: 409,+ data: { detail: 'The experiment was changed since you loaded it.', current_version: 5 },+ })+ const fresh = { ...experiment, version: 5, name: 'renamed by someone else' } as Experiment+ getSpy = jest.spyOn(api, 'get').mockResolvedValue(fresh)++ await expectLogic(logic, () => {+ logic.actions.updateExperiment({ description: 'stale write' })+ }).toFinishAllListeners()++ expect(lemonToast.error).toHaveBeenCalledWith('The experiment was changed since you loaded it.')+ // Fresh server state is loaded so the next save carries the current version...+ expect(logic.values.unmodifiedExperiment?.version).toEqual(5)+ expect(logic.values.experiment.name).toEqual('renamed by someone else')+ // ...but the user's rejected edit stays visible for review and retry.+ expect(logic.values.experiment.description).toEqual('stale write')+ })+ })describe('saveMetricsReorder', () => {const primaryMetric = {kind: 'ExperimentMetric',diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex cfd8d6b9ed4a..a03f881f3065 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -139,7 +139,10 @@ import {getExperimentVariants,getOrderedMetricsWithResults,initializeMetricOrdering,+ conflictPreservedFields,+ isExperimentConflictError,isLegacyExperiment,+ toConcurrencyPayload,toExperimentWritePayload,toFlagVariantsInput,} from './utils'@@ -2868,10 +2871,22 @@ export const experimentLogic = kea<experimentLogicType>([})const combinedMetricsIds = [...existingMetricsIds, ...newMetricsIds]- await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`, {- saved_metrics_ids: combinedMetricsIds,- update_feature_flag_params: false,- })+ try {+ await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`, {+ ...toConcurrencyPayload(values.unmodifiedExperiment),+ saved_metrics_ids: combinedMetricsIds,+ update_feature_flag_params: false,+ })+ } 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.'+ )+ } else {+ throw error+ }+ }actions.loadExperiment({ triggeredBy: 'config_change' })},@@ -2898,12 +2913,24 @@ export const experimentLogic = kea<experimentLogicType>([(m) => !('isSharedMetric' in m && m.isSharedMetric && m.sharedMetricId === sharedMetricId))- await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`, {- saved_metrics_ids: sharedMetricsIds,- metrics: cleanedMetrics,- metrics_secondary: cleanedMetricsSecondary,- update_feature_flag_params: false,- })+ try {+ await api.update(`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`, {+ ...toConcurrencyPayload(values.unmodifiedExperiment),+ saved_metrics_ids: sharedMetricsIds,+ metrics: cleanedMetrics,+ metrics_secondary: cleanedMetricsSecondary,+ update_feature_flag_params: false,+ })+ } 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.'+ )+ } else {+ throw error+ }+ }actions.loadExperiment({ triggeredBy: 'config_change' })},@@ -3569,16 +3596,40 @@ export const experimentLogic = kea<experimentLogicType>([null as Experiment | null,{updateExperiment: async (update: ExperimentUpdatePayload) => {- const response: Experiment = await api.update(- `api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,- update- )- const responseWithMetricsOrdering = initializeMetricOrdering(response)- refreshTreeItem('experiment', String(values.experimentId))- actions.setUnmodifiedExperiment(structuredClone(responseWithMetricsOrdering))- // Also update the main experiment state- actions.setExperiment(responseWithMetricsOrdering)- return responseWithMetricsOrdering+ try {+ const response: Experiment = await api.update(+ `api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,+ { ...toConcurrencyPayload(values.unmodifiedExperiment), ...update }+ )+ const responseWithMetricsOrdering = initializeMetricOrdering(response)+ refreshTreeItem('experiment', String(values.experimentId))+ actions.setUnmodifiedExperiment(structuredClone(responseWithMetricsOrdering))+ // Also update the main experiment state+ actions.setExperiment(responseWithMetricsOrdering)+ return responseWithMetricsOrdering+ } 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.'+ )+ // Reload so the next save carries the current version and base state,+ // but keep this update's rejected scalar fields in local state so the+ // user's edit isn't lost — they can review the fresh state and save again.+ const preserved = conflictPreservedFields(update)+ try {+ const fresh: Experiment = await api.get(+ `api/projects/${values.currentProjectId}/experiments/${values.experimentId}`+ )+ const freshWithOrdering = initializeMetricOrdering(fresh)+ actions.setUnmodifiedExperiment(structuredClone(freshWithOrdering))+ actions.setExperiment({ ...freshWithOrdering, ...preserved })+ } catch {+ actions.loadExperiment()+ }+ }+ throw error+ }},},],diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex e38b18119d0f..73f301122bf3 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -1260,6 +1260,54 @@ export type ExperimentWritePayload<T> = Omit<T, 'feature_flag' | 'feature_flag_cexport type ExperimentUpdatePayload = Omit<Partial<Experiment>, 'feature_flag'> & {feature_flag?: ExperimentFeatureFlagInputApi | Experiment['feature_flag']update_feature_flag_params?: boolean+ 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. */+export function toConcurrencyPayload(+ unmodified: Experiment | null+): Pick<ExperimentUpdatePayload, 'version' | 'original_experiment'> {+ if (!unmodified || typeof unmodified.id !== 'number') {+ return {}+ }+ return {+ version: unmodified.version ?? 0,+ original_experiment: {+ metrics: unmodified.metrics,+ metrics_secondary: unmodified.metrics_secondary,+ saved_metrics_ids: (unmodified.saved_metrics || []).map((sharedMetric) => ({+ id: sharedMetric.saved_metric,+ metadata: sharedMetric.metadata,+ })),+ },+ }+}++/** Whether an API error is the experiment concurrency conflict (as opposed to any other 409,+ * e.g. an approval-required response, which carries no `current_version`). */+export function isExperimentConflictError(error: any): boolean {+ return error?.status === 409 && error?.data?.current_version !== undefined+}++const CONFLICT_UNPRESERVABLE_KEYS = new Set([+ 'metrics',+ 'metrics_secondary',+ 'saved_metrics_ids',+ 'primary_metrics_ordered_uuids',+ 'secondary_metrics_ordered_uuids',+ 'version',+ 'original_experiment',+ 'update_feature_flag_params',+ 'feature_flag',+])++/** The fields of a 409-rejected update worth keeping in local state: the user's scalar edits.+ * Collection and bookkeeping fields are dropped — re-applying a stale metric array over the+ * fresh state would reintroduce exactly the clobbering the conflict prevented. */+export function conflictPreservedFields(payload: ExperimentUpdatePayload): Partial<Experiment> {+ return Object.fromEntries(Object.entries(payload).filter(([key]) => !CONFLICT_UNPRESERVABLE_KEYS.has(key)))}/** Maps UI variants to the flag's write shape, dropping null names the generated type disallows. */diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 294d06da82b3..7c6d88804f58 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4960,6 +4960,9 @@ export interface Experiment {/** Desktop task opened to remove the experiment's flag code, when requested on end/ship. */flag_cleanup_task_id?: string | nulluser_access_level: AccessControlLevel+ /** Optimistic-concurrency token, bumped by the server on every update. Send the last-read+ * value with updates so concurrent edits are detected (409) or merged instead of clobbered. */+ version?: number | null}export interface ExperimentVelocityStats {diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 383457e70677..e2580997caa6 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -537,6 +537,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {"holdout","saved_metrics","experimenttosavedmetric_set",+ # Optimistic-concurrency counter, not a user-meaningful change.+ "version",],"ExperimentSavedMetric": ["experiments",diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 660fb568f6e2..a281e04cf316 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -227,6 +227,7 @@'stats_config','type','variants',+ 'version',])# ---# name: TestVisitorFieldSnapshots.test_primitive_fields_ExperimentHoldoutdiff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 9efdcb5a661c..d3e40f773fc5 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -19,7 +19,8 @@ from django.utils import timezoneimport pydanticimport structlogimport posthoganalytics-from rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework import status+from rest_framework.exceptions import APIException, PermissionDenied, ValidationErrorfrom posthog.schema import (ActionsNode,@@ -273,6 +274,139 @@ def _strip_frozen_exposure(filters: dict) -> tuple[dict, list[int]]:)+class ExperimentVersionConflict(APIException):+ """A stale write raced a concurrent update and could not be applied safely."""++ status_code = status.HTTP_409_CONFLICT+ default_code = "conflict"+ default_detail = "This experiment changed since you loaded it. Review the latest changes and try again."++ def __init__(+ self,+ detail: str | None = None,+ *,+ current_version: int = 0,+ conflicting_fields: list[str] | None = None,+ conflicting_metric_uuids: list[str] | None = None,+ ) -> None:+ super().__init__(detail=detail)+ self.current_version = current_version+ self.conflicting_fields = conflicting_fields or []+ self.conflicting_metric_uuids = conflicting_metric_uuids or []++ def response_data(self) -> dict[str, Any]:+ data: dict[str, Any] = {"detail": str(self.detail), "current_version": self.current_version}+ if self.conflicting_fields:+ data["conflicting_fields"] = self.conflicting_fields+ if self.conflicting_metric_uuids:+ data["conflicting_metric_uuids"] = self.conflicting_metric_uuids+ return data+++# Fields a stale write may still change. The metric collections merge per uuid — each metric+# carries a stable server-assigned uuid, so concurrent intent is preserved — and the ordering+# arrays are re-derived by the ordering syncs. 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 (e.g. a description phrased for metrics someone+# edited meanwhile).+CONCURRENCY_MERGEABLE_FIELDS = frozenset(+ {+ "metrics",+ "metrics_secondary",+ "saved_metrics_ids",+ "primary_metrics_ordered_uuids",+ "secondary_metrics_ordered_uuids",+ }+)+++def _metric_merge_view(metric: dict) -> dict:+ """A metric dict as compared for concurrency resolution: server-derived keys stripped.++ `fingerprint` is recomputed from experiment-level fields on every write (launch, stats+ changes), so including it would make server-side churn look like a concurrent edit.+ """+ return {k: v for k, v in metric.items() if k != "fingerprint"}+++def _metrics_by_uuid(metrics: list | None) -> dict[str, dict]:+ return {m["uuid"]: m for m in (metrics or []) if isinstance(m, dict) and m.get("uuid")}+++def _merge_metric_arrays(base: list | None, theirs: list | None, mine: list | None) -> tuple[list[dict], list[str]]:+ """Three-way merge of a metric array, keyed by metric uuid.++ ``base`` is the client's last-seen state, ``theirs`` the current stored state, ``mine``+ the submitted array. Per uuid: whichever side changed it wins; both sides changing it+ differently (including edit-vs-delete) is a conflict. Returns (merged, conflicting_uuids).+ """+ base_by = _metrics_by_uuid(base)+ theirs_by = _metrics_by_uuid(theirs)+ mine_by = _metrics_by_uuid(mine)+ # Metrics submitted without a uuid are new additions (uuids are server-assigned on write).+ additions_without_uuid = [m for m in (mine or []) if not (isinstance(m, dict) and m.get("uuid"))]++ def changed(a: dict | None, b: dict | None) -> bool:+ if (a is None) != (b is None):+ return True+ return a is not None and b is not None and _metric_merge_view(a) != _metric_merge_view(b)++ merged: list[dict] = []+ conflicts: list[str] = []+ for uuid in [*theirs_by, *(u for u in mine_by if u not in theirs_by)]:+ base_metric, their_metric, my_metric = base_by.get(uuid), theirs_by.get(uuid), mine_by.get(uuid)+ if not changed(their_metric, base_metric):+ survivor = my_metric+ elif not changed(my_metric, base_metric):+ survivor = their_metric+ elif not changed(my_metric, their_metric):+ survivor = my_metric+ else:+ conflicts.append(uuid)+ continue+ if survivor is not None:+ merged.append(survivor)+ merged.extend(additions_without_uuid)+ return merged, conflicts+++def _links_by_id(links: list | None) -> dict[int, dict]:+ return {+ link["id"]: (link.get("metadata") or {})+ for link in (links or [])+ if isinstance(link, dict) and link.get("id") is not None+ }+++def _merge_saved_metric_links(+ base: list | None, theirs: list | None, mine: list | None+) -> tuple[list[dict], list[str]]:+ """Three-way merge of saved-metric link lists (``[{id, metadata}]``), keyed by saved-metric id."""+ _MISSING = object()+ base_by = _links_by_id(base)+ theirs_by = _links_by_id(theirs)+ mine_by = _links_by_id(mine)++ merged: list[dict] = []+ conflicts: list[str] = []+ for link_id in [*theirs_by, *(i for i in mine_by if i not in theirs_by)]:+ base_link = base_by.get(link_id, _MISSING)+ their_link = theirs_by.get(link_id, _MISSING)+ my_link = mine_by.get(link_id, _MISSING)+ if their_link == base_link:+ survivor = my_link+ elif my_link == base_link:+ survivor = their_link+ elif my_link == their_link:+ survivor = my_link+ else:+ conflicts.append(f"saved_metric:{link_id}")+ continue+ if survivor is not _MISSING:+ merged.append({"id": link_id, "metadata": survivor})+ return merged, conflicts++class ExperimentQueryStatus(str, Enum):"""Filter values for the experiment list endpoint.@@ -1474,7 +1608,7 @@ class ExperimentService:"rollout_percentage": variant.get("rollout_percentage"),}experiment.variants = web_variants- experiment.save()+ self._bump_version_and_save(experiment, update_fields=["variants"])def _sync_saved_metrics(self,@@ -1634,26 +1768,49 @@ class ExperimentService:# so start_date stays None and the experiment is not launched.set_flag_active(feature_flag, True, team=self.team, user=self.user, request=request)- # Set start_date- experiment.start_date = timezone.now()+ # Set start_date and persist under the experiment row lock. Refresh the metric+ # collections from the locked row first so fingerprints recompute against the current+ # metrics and the launch save can't revert a metric edit another writer committed+ # since this request loaded the experiment.+ with transaction.atomic():+ locked_version = (+ Experiment.objects.select_for_update()+ .filter(pk=experiment.pk)+ .values_list("version", flat=True)+ .first()+ or 0+ )+ experiment.refresh_from_db(fields=["metrics", "metrics_secondary"])+ experiment.start_date = timezone.now()- # Recompute metric fingerprints with the new start_date- for metric_field in ["metrics", "metrics_secondary"]:- metrics = getattr(experiment, metric_field, None)- if metrics:- setattr(- experiment,- metric_field,- self._recompute_fingerprints(- metrics,- experiment.start_date,- experiment.stats_config,- experiment.exposure_criteria,- excluded_variants=experiment.excluded_variants or [],- ),- )+ # Recompute metric fingerprints with the new start_date+ for metric_field in ["metrics", "metrics_secondary"]:+ metrics = getattr(experiment, metric_field, None)+ if metrics:+ setattr(+ experiment,+ metric_field,+ self._recompute_fingerprints(+ metrics,+ experiment.start_date,+ experiment.stats_config,+ experiment.exposure_criteria,+ excluded_variants=experiment.excluded_variants or [],+ ),+ )- experiment.save()+ experiment.version = locked_version + 1+ # stats_config carries the baseline-variant pin materialized above; persist it too.+ experiment.save(+ update_fields=[+ "start_date",+ "stats_config",+ "metrics",+ "metrics_secondary",+ "version",+ "updated_at",+ ]+ )self._report_experiment_launched(experiment, request=request)@@ -1688,7 +1845,7 @@ class ExperimentService:raise ValidationError("Experiment must be ended before it can be archived.")experiment.archived = True- experiment.save()+ self._bump_version_and_save(experiment, update_fields=["archived"])self._archive_linked_feature_flag(experiment,@@ -1799,7 +1956,7 @@ class ExperimentService:raise ValidationError("Experiment is not archived.")experiment.archived = False- experiment.save()+ self._bump_version_and_save(experiment, update_fields=["archived"])self._unarchive_linked_feature_flag(experiment, can_write_feature_flag=can_write_feature_flag, request=request)@@ -2330,7 +2487,7 @@ class ExperimentService:experiment.end_date = timezone.now()experiment.conclusion = conclusionexperiment.conclusion_comment = conclusion_comment- experiment.save()+ self._bump_version_and_save(experiment, update_fields=["end_date", "conclusion", "conclusion_comment"])self._report_experiment_ended(experiment, request=request, open_cleanup_pr=open_cleanup_pr, repository=repository@@ -2594,6 +2751,14 @@ class ExperimentService:if experiment.is_draft:raise ValidationError("Experiment is already in draft state.")+ # Lock the experiment row before _clear_frozen_exposure locks the flag row, so every+ # transaction that holds both locks acquires them experiment-then-flag and can't+ # deadlock. Held until this @transaction.atomic method commits.+ locked_version = (+ Experiment.objects.select_for_update().filter(pk=experiment.pk).values_list("version", flat=True).first()+ or 0+ )+self._clear_frozen_exposure(experiment, request=request)experiment.start_date = None@@ -2605,7 +2770,19 @@ class ExperimentService:# stale "Cleanup PR opened" line after the experiment is re-ended without opting in.experiment.flag_cleanup_task_id = None- experiment.save()+ experiment.version = locked_version + 1+ experiment.save(+ update_fields=[+ "start_date",+ "end_date",+ "archived",+ "conclusion",+ "conclusion_comment",+ "flag_cleanup_task_id",+ "version",+ "updated_at",+ ]+ )self._report_lifecycle_event(experiment, "experiment reset", request=request)@@ -2730,13 +2907,17 @@ class ExperimentService:# End the experiment only if it's still runningwas_running = experiment.is_running+ shipped_fields: list[str] = []if was_running:experiment.end_date = timezone.now()+ shipped_fields.append("end_date")if conclusion is not None:experiment.conclusion = conclusion+ shipped_fields.append("conclusion")if conclusion_comment is not None:experiment.conclusion_comment = conclusion_comment- experiment.save()+ shipped_fields.append("conclusion_comment")+ self._bump_version_and_save(experiment, update_fields=shipped_fields)self._report_experiment_variant_shipped(experiment, variant_key=variant_key, release_to_everyone=release_to_everyone, request=request@@ -2777,6 +2958,137 @@ class ExperimentService:# an atomic block would roll back the just-created pending ChangeRequest. That flag# write runs first, outside any transaction; the experiment-state writes that follow# are wrapped in a narrow `with transaction.atomic()` block so they stay all-or-nothing.+ def _bump_version_and_save(self, experiment: Experiment, *, update_fields: list[str]) -> None:+ """Persist a lifecycle change under a row lock so the concurrency token stays reliable.++ Locking the experiment row serializes the version bump against any concurrent+ writer — including ``update_experiment``, which takes the same lock — so two racing+ saves can't both land on the same version. The scoped ``update_fields`` write touches+ only the columns this transition owns, so it can't revert metric collections a+ concurrent update committed after this request loaded the row.++ Lock ordering: callers that also lock the linked feature-flag row must take this+ experiment lock first (see ``reset_experiment`` / ``archive_experiment``), so every+ transaction holding both acquires them experiment-then-flag and can't deadlock.+ """+ with transaction.atomic():+ locked_version = (+ Experiment.objects.select_for_update()+ .filter(pk=experiment.pk)+ .values_list("version", flat=True)+ .first()+ or 0+ )+ experiment.version = locked_version + 1+ experiment.save(update_fields=[*update_fields, "version", "updated_at"])++ def _report_update_conflict(+ self,+ experiment: Experiment,+ *,+ request: Any | None,+ resolution: Literal["merged", "rejected"],+ versions_behind: int,+ base_snapshot_sent: bool,+ merged_fields: list[str] | None = None,+ conflict: ExperimentVersionConflict | None = None,+ ) -> None:+ """Post-deploy telemetry for stale writes: chart "experiment update concurrency"+ broken down by ``resolution`` to watch the merge/409 ratio; ``conflicting_fields``+ shows what users trip on."""+ if request is None:+ return+ metadata = experiment.get_analytics_metadata()+ metadata.update(+ {+ "resolution": resolution,+ "versions_behind": versions_behind,+ "base_snapshot_sent": base_snapshot_sent,+ }+ )+ if merged_fields:+ metadata["merged_fields"] = merged_fields+ if conflict is not None:+ metadata["conflicting_fields"] = conflict.conflicting_fields+ metadata["conflicting_metric_uuids_count"] = len(conflict.conflicting_metric_uuids)+ report_user_action(self.user, "experiment update concurrency", metadata, team=experiment.team, request=request)++ @staticmethod+ def _current_saved_metric_link_dicts(experiment: Experiment) -> list[dict]:+ return [+ {"id": link.saved_metric_id, "metadata": link.metadata or {}}+ for link in experiment.experimenttosavedmetric_set.all()+ ]++ def _resolve_concurrent_update(+ self,+ experiment: Experiment,+ update_data: dict,+ original: Mapping | None,+ current_version: int,+ ) -> 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``.+ """+ 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:+ 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.",+ current_version=current_version,+ conflicting_fields=non_mergeable_payload,+ )++ conflict_uuids: list[str] = []+ for field in ("metrics", "metrics_secondary"):+ if field in update_data:+ merged, conflicts = _merge_metric_arrays(+ original.get(field) or [],+ getattr(experiment, field) or [],+ update_data.get(field) or [],+ )+ update_data[field] = merged+ conflict_uuids.extend(conflicts)+ if "saved_metrics_ids" in update_data:+ merged_links, link_conflicts = _merge_saved_metric_links(+ original.get("saved_metrics_ids") or [],+ self._current_saved_metric_link_dicts(experiment),+ update_data.get("saved_metrics_ids") or [],+ )+ update_data["saved_metrics_ids"] = merged_links+ conflict_uuids.extend(link_conflicts)+ if conflict_uuids:+ raise ExperimentVersionConflict(+ "A metric on this experiment changed since you loaded it. Review the latest changes and try again.",+ current_version=current_version,+ conflicting_metric_uuids=conflict_uuids,+ )++ for ordering_field in ("primary_metrics_ordered_uuids", "secondary_metrics_ordered_uuids"):+ client_order = update_data.get(ordering_field)+ if ordering_field in update_data and client_order is not None:+ current_order = list(getattr(experiment, ordering_field) or [])+ current_set = set(current_order)+ # Keep the client's relative order for uuids that still exist, then append+ # concurrently-added ones. The ordering syncs layer this request's own+ # adds/removes on top of this reconciled value.+ update_data[ordering_field] = [+ *(u for u in client_order if u in current_set),+ *(u for u in current_order if u not in client_order),+ ]+def update_experiment(self,experiment: Experiment,@@ -2803,13 +3115,53 @@ class ExperimentService:``deprecated_flag_config_changed`` records (for the "experiment updated" event) that theserializer copy-forward turned deprecated ``parameters`` flag config into a real flag write;the direct-caller derivation below sets it too. It is the gate for retiring the copy-forward.++ ``update_data`` may carry two opt-in concurrency keys, ``version`` (the version the client+ last read) and ``original_experiment`` (the state it last saw): a stale write is then merged+ per metric uuid where safe and rejected with ``ExperimentVersionConflict`` (409) otherwise.+ Without them the write applies as-is; either way the stored ``version`` is bumped."""update_feature_flag_params = update_data.pop("update_feature_flag_params", False)+ client_version = update_data.pop("version", None)+ original_experiment = update_data.pop("original_experiment", None)+ report_request = serializer_context.get("request") if serializer_context else None++ # --- optimistic concurrency (opt-in) ---------------------------------+ # Resolve a stale write against the current row *before* any validation or+ # side effect, so it can neither silently clobber concurrent changes nor+ # persist a flag change ahead of a conflict. The refresh is unlocked; the+ # row lock inside the transaction below re-checks the version, so a writer+ # racing this window still conflicts instead of interleaving.+ resolution_version: int | None = None+ if client_version is not None:+ experiment.refresh_from_db()+ current_version = experiment.version or 0+ if client_version != current_version:+ try:+ self._resolve_concurrent_update(experiment, update_data, original_experiment, current_version)+ except ExperimentVersionConflict as conflict:+ self._report_update_conflict(+ experiment,+ request=report_request,+ resolution="rejected",+ versions_behind=current_version - client_version,+ base_snapshot_sent=original_experiment is not None,+ conflict=conflict,+ )+ raise+ self._report_update_conflict(+ experiment,+ request=report_request,+ resolution="merged",+ versions_behind=current_version - client_version,+ base_snapshot_sent=True,+ merged_fields=sorted(set(update_data) & CONCURRENCY_MERGEABLE_FIELDS),+ )+ resolution_version = current_version# Snapshot before the update to diff what actually changed. The activity-log diff# misses the saved-metric M2M, so capture its signature separately, before the sync# below mutates it. Skip the reads when neither channel will report.- report_request = serializer_context.get("request") if serializer_context else Noneshould_report_update = report_request is not None or event_source is not Nonebefore_update = experiment._get_before_update() if should_report_update else Nonebefore_saved_metrics = self._saved_metric_signature(experiment) if should_report_update else frozenset()@@ -2997,6 +3349,34 @@ class ExperimentService:set_flag_active(feature_flag, True, team=self.team, user=self.user, request=context.get("request"))with transaction.atomic():+ # Row lock: serializes concurrent updaters and re-checks the version the+ # concurrency resolution above was computed against (that read was unlocked).+ # Caveat: the flag sync above already ran outside this transaction (it must —+ # see the comment there), so a 409 raised here leaves a flag change persisted+ # without its experiment write. The window is the few ms between the unlocked+ # resolution read and this lock, and the frontend's metric writes never carry+ # flag config, so in practice this stays theoretical.+ locked_version = (+ Experiment.objects.select_for_update()+ .filter(pk=experiment.pk)+ .values_list("version", flat=True)+ .first()+ or 0+ )+ if resolution_version is not None and locked_version != resolution_version:+ locked_conflict = ExperimentVersionConflict(current_version=locked_version)+ if client_version is not None:+ self._report_update_conflict(+ experiment,+ request=report_request,+ resolution="rejected",+ versions_behind=locked_version - client_version,+ base_snapshot_sent=original_experiment is not None,+ conflict=locked_conflict,+ )+ raise locked_conflict+ update_data["version"] = locked_version + 1+# --- saved metrics sync (update-in-place) -----------old_saved_metric_uuids: dict[str, set[str]] = {"primary": set(), "secondary": set()}if update_saved_metrics:diff --git a/products/experiments/backend/migrations/0031_add_experiment_version.py b/products/experiments/backend/migrations/0031_add_experiment_version.pynew file mode 100644index 000000000000..ab61fb8dfcfb--- /dev/null+++ b/products/experiments/backend/migrations/0031_add_experiment_version.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-15 09:38++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0030_alter_experimentmetricsrecalculation_trigger"),+ ]++ operations = [+ migrations.AddField(+ model_name="experiment",+ name="version",+ field=models.IntegerField(blank=True, default=0, null=True),+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex b729a1fcfb00..c3bcf5291b00 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0030_alter_experimentmetricsrecalculation_trigger+0031_add_experiment_versiondiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 145ff2c0fff1..80d9c097ed48 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -82,6 +82,9 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.end_date = models.DateTimeField(null=True, blank=True)created_at = models.DateTimeField(default=timezone.now)updated_at = models.DateTimeField(auto_now=True)+ # Optimistic-concurrency token: bumped on every user-facing update so stale+ # clients can be detected. Null (pre-backfill rows) is treated as 0.+ version = models.IntegerField(default=0, null=True, blank=True)archived = models.BooleanField(default=False)# Whether archiving this experiment also auto-archived its linked feature flag,# so unarchiving only undoes an archive the experiment itself performed.diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 629a6b619371..8f777dd66db6 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -375,6 +375,29 @@ class ExperimentSerializer(ExperimentBaseSerializer):"conditions)."),)+ version = serializers.IntegerField(+ required=False,+ allow_null=True,+ 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."+ ),+ )+ original_experiment = serializers.DictField(+ required=False,+ 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."+ ),+ )_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)flag_cleanup_task_id = serializers.UUIDField(read_only=True,@@ -439,6 +462,8 @@ class ExperimentSerializer(ExperimentBaseSerializer):"secondary_metrics_ordered_uuids","only_count_matured_users","update_feature_flag_params",+ "version",+ "original_experiment","status","is_legacy","can_freeze_exposure",@@ -757,6 +782,9 @@ class ExperimentSerializer(ExperimentBaseSerializer):# Pop fields not needed for DTO but needed for validationvalidated_data.pop("update_feature_flag_params", None)+ # Concurrency keys are update-only; ignore them on create so clients can share payload builders+ validated_data.pop("version", None)+ validated_data.pop("original_experiment", None)# Check for unexpected fieldsexpected_fields = {diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 5cb855ae48af..8452568641dc 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -51,7 +51,7 @@ from posthog.temporal.experiments.models import ExperimentTimeseriesRecalculatiofrom posthog.user_permissions import UserPermissionsfrom products.approvals.backend.mixins import ApprovalHandlingMixin-from products.experiments.backend.experiment_service import ExperimentService+from products.experiments.backend.experiment_service import ExperimentService, ExperimentVersionConflictfrom products.experiments.backend.llm_metric_templates import build_template, list_templates# TODO: Route through facade instead of direct import@@ -385,6 +385,14 @@ class EnterpriseExperimentsViewSet(return ExperimentBasicSerializerreturn ExperimentSerializer+ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ # Structured 409 body ({detail, current_version, conflicting_*}) so clients can refetch+ # and retry precisely; the default exception handler would flatten it to a plain string.+ try:+ return super().update(request, *args, **kwargs)+ except ExperimentVersionConflict as err:+ return Response(err.response_data(), status=err.status_code)+@tracer.start_as_current_span("ExperimentViewSet.list")def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:return super().list(request, *args, **kwargs)diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 6eb326636309..de4a6133f7f2 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -40,6 +40,8 @@ from products.experiments.backend.experiment_service import (ExperimentService,_deprecated_fields_in_request,_deprecated_parameters_keys_in_request,+ _merge_metric_arrays,+ _merge_saved_metric_links,)from products.experiments.backend.models.experiment import (EXPOSURE_FROZEN_COHORT_KEY,@@ -310,6 +312,55 @@ class TestExperimentService(APIBaseTest):assert isinstance(experiment.metrics[0]["fingerprint"], str)assert len(experiment.metrics[0]["fingerprint"]) == 64 # SHA256 hex+ def test_lifecycle_save_does_not_clobber_concurrent_metric_change(self):+ from django.utils import timezone++ self._create_flag(key="lifecycle-clobber")+ service = self._service()++ metric_one = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "metric-1",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ }+ metric_two = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "metric-2",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ }++ experiment = service.create_experiment(+ name="Lifecycle Clobber",+ feature_flag_key="lifecycle-clobber",+ allow_unknown_events=True,+ metrics=[metric_one],+ start_date=timezone.now(), # launched, so end_experiment is valid+ )++ # A request that loaded the experiment before the concurrent metric add.+ stale = Experiment.objects.get(pk=experiment.pk)+ stale_version = stale.version or 0++ # A concurrent request adds a second metric.+ service.update_experiment(+ Experiment.objects.get(pk=experiment.pk),+ {"metrics": [metric_one, metric_two]},+ allow_unknown_events=True,+ )++ # Ending from the stale instance must not revert metric-2: the scoped, row-locked+ # save touches only end_date/conclusion/version, never the metric collections.+ service.end_experiment(stale)++ final = Experiment.objects.get(pk=experiment.pk)+ assert final.end_date is not None+ assert {m["uuid"] for m in (final.metrics or [])} == {"metric-1", "metric-2"}+ # Both writes advanced the token; the lifecycle bump reads the locked row, so it+ # lands above the concurrent update rather than colliding with it.+ assert (final.version or 0) > stale_version + 1+# ------------------------------------------------------------------# Metric ordering# ------------------------------------------------------------------@@ -6854,3 +6905,81 @@ class TestDeprecatedParametersKeysInRequest(SimpleTestCase):request = MagicMock()type(request).data = PropertyMock(side_effect=RuntimeError("stream consumed"))assert _deprecated_parameters_keys_in_request(request) == []+++class TestConcurrentMetricMerge(SimpleTestCase):+ """Branch pins for the pure three-way merge helpers behind experiment optimistic concurrency.+ The end-to-end behavior is covered in test_presentation_api.py::TestExperimentConcurrency;+ these lock the merge decisions that are awkward to reach through the API (identical edits on+ both sides, double deletes, fingerprint-only churn)."""++ @staticmethod+ def _metric(uuid: str, event: str, fingerprint: str | None = None) -> dict:+ metric = {"uuid": uuid, "kind": "ExperimentMetric", "source": {"kind": "EventsNode", "event": event}}+ if fingerprint is not None:+ metric["fingerprint"] = fingerprint+ return metric++ @parameterized.expand(+ [+ (+ "identical_edit_on_both_sides_is_not_a_conflict",+ [("m1", "old", None)],+ [("m1", "new", None)],+ [("m1", "new", None)],+ {"new"},+ [],+ ),+ (+ "both_delete_the_same_metric",+ [("m1", "e1", None), ("m2", "e2", None)],+ [("m2", "e2", None)],+ [("m2", "e2", None)],+ {"e2"},+ [],+ ),+ (+ "fingerprint_only_churn_is_not_a_concurrent_edit",+ [("m1", "e1", "old-fp"), ("m2", "e2", "old-fp")],+ [("m1", "e1", "new-fp"), ("m2", "e2", "new-fp")],+ [("m2", "e2", "old-fp")],+ {"e2"},+ [],+ ),+ (+ "edit_vs_delete_conflicts",+ [("m1", "e1", None)],+ [("m1", "edited", None)],+ [],+ {"edited"},+ ["m1"],+ ),+ ]+ )+ def test_merge_metric_arrays(+ self,+ _name: str,+ base: list,+ theirs: list,+ mine: list,+ expected_events: set[str],+ expected_conflicts: list[str],+ ) -> None:+ merged, conflicts = _merge_metric_arrays(+ [self._metric(*m) for m in base],+ [self._metric(*m) for m in theirs],+ [self._metric(*m) for m in mine],+ )++ self.assertEqual(conflicts, expected_conflicts)+ if not expected_conflicts:+ self.assertEqual({m["source"]["event"] for m in merged}, expected_events)++ def test_merge_saved_metric_links_identical_metadata_edit_is_not_a_conflict(self) -> None:+ base = [{"id": 1, "metadata": {"type": "primary"}}]+ both_edited = [{"id": 1, "metadata": {"type": "secondary"}}]++ merged, conflicts = _merge_saved_metric_links(base, both_edited, both_edited)++ self.assertEqual(conflicts, [])+ self.assertEqual(merged, [{"id": 1, "metadata": {"type": "secondary"}}])diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex e416e1d74322..79921d51fd3d 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -8966,3 +8966,377 @@ class TestExperimentApiExposureCriteriaParity(unittest.TestCase):"Generated write clients (MCP, frontend) strip these silently — add them to the slim API ""type in frontend/src/queries/schema/schema-general.ts and rerun hogli build:schema.",)+++class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):+ """Optimistic concurrency on experiment updates: stale writes carrying `version` ++ `original_experiment` merge concurrent metric changes per uuid and 409 on everything else.+ Guards the incident class where a stale tab's full-array PATCH silently deleted metrics+ other users had added since the tab loaded."""++ def _metric(self, event: str) -> dict:+ return {"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "EventsNode", "event": event}}++ def _create_experiment(self, key: str, metrics: list | None = None, metrics_secondary: list | None = None) -> dict:+ response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": f"Concurrency {key}",+ "feature_flag_key": key,+ "parameters": {+ "feature_flag_variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ "metrics": metrics or [],+ "metrics_secondary": metrics_secondary or [],+ "allow_unknown_events": True,+ },+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ return response.json()++ def _patch(self, experiment_id: int, payload: dict) -> Any:+ return self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/",+ {"allow_unknown_events": True, **payload},+ )++ def _original(self, snapshot: dict) -> dict:+ """The base snapshot the frontend sends: the metric collections as this client last saw them."""+ return {+ "metrics": snapshot.get("metrics") or [],+ "metrics_secondary": snapshot.get("metrics_secondary") or [],+ "saved_metrics_ids": [+ {"id": link["saved_metric"], "metadata": link["metadata"]}+ for link in snapshot.get("saved_metrics") or []+ ],+ }++ def _events(self, metrics: list) -> set[str]:+ return {metric["source"]["event"] for metric in metrics}++ def test_stale_delete_merges_with_concurrent_additions(self) -> None:+ # Incident replay: a stale tab deletes 1 of the 3 metrics it saw while teammates+ # added 4 more; the stale write must not remove the 4 unseen metrics.+ snapshot = self._create_experiment(+ "incident-replay", metrics_secondary=[self._metric(f"e{i}") for i in (1, 2, 3)]+ )+ teammate_write = self._patch(+ snapshot["id"],+ {"metrics_secondary": [*snapshot["metrics_secondary"], *(self._metric(f"e{i}") for i in (4, 5, 6, 7))]},+ )+ self.assertEqual(teammate_write.status_code, status.HTTP_200_OK)++ stale_delete = self._patch(+ snapshot["id"],+ {+ "metrics_secondary": snapshot["metrics_secondary"][1:],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_delete.status_code, status.HTTP_200_OK, stale_delete.json())+ result = stale_delete.json()+ self.assertEqual(self._events(result["metrics_secondary"]), {"e2", "e3", "e4", "e5", "e6", "e7"})+ self.assertEqual(+ set(result["secondary_metrics_ordered_uuids"]),+ {metric["uuid"] for metric in result["metrics_secondary"]},+ )++ def test_concurrent_additions_of_different_metrics_both_survive(self) -> None:+ snapshot = self._create_experiment("both-add", metrics=[self._metric("base")])+ self.assertEqual(+ self._patch(snapshot["id"], {"metrics": [*snapshot["metrics"], self._metric("theirs")]}).status_code,+ status.HTTP_200_OK,+ )++ stale_add = self._patch(+ snapshot["id"],+ {+ "metrics": [*snapshot["metrics"], self._metric("mine")],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_add.status_code, status.HTTP_200_OK, stale_add.json())+ self.assertEqual(self._events(stale_add.json()["metrics"]), {"base", "theirs", "mine"})++ def test_same_metric_edited_by_both_conflicts(self) -> None:+ snapshot = self._create_experiment("double-edit", metrics=[self._metric("original_event")])+ their_metric = {**snapshot["metrics"][0], "source": {"kind": "EventsNode", "event": "their_event"}}+ self.assertEqual(self._patch(snapshot["id"], {"metrics": [their_metric]}).status_code, status.HTTP_200_OK)++ my_metric = {**snapshot["metrics"][0], "source": {"kind": "EventsNode", "event": "my_event"}}+ stale_edit = self._patch(+ snapshot["id"],+ {+ "metrics": [my_metric],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_edit.status_code, status.HTTP_409_CONFLICT)+ body = stale_edit.json()+ self.assertIn("detail", body)+ self.assertEqual(body["current_version"], 1)+ self.assertEqual(body["conflicting_metric_uuids"], [snapshot["metrics"][0]["uuid"]])+ experiment = Experiment.objects.get(id=snapshot["id"])+ self.assertEqual((experiment.metrics or [])[0]["source"]["event"], "their_event")++ @parameterized.expand(+ [+ ("stale_delete_vs_concurrent_edit", "delete_mine"),+ ("stale_edit_vs_concurrent_delete", "delete_theirs"),+ ]+ )+ def test_edit_vs_delete_of_same_metric_conflicts(self, _name: str, mode: str) -> None:+ snapshot = self._create_experiment(f"edit-vs-delete-{mode}", metrics=[self._metric("contested")])+ edited = {**snapshot["metrics"][0], "source": {"kind": "EventsNode", "event": "edited"}}+ theirs = [] if mode == "delete_theirs" else [edited]+ self.assertEqual(self._patch(snapshot["id"], {"metrics": theirs}).status_code, status.HTTP_200_OK)++ mine = [edited] if mode == "delete_theirs" else []+ stale_write = self._patch(+ snapshot["id"],+ {+ "metrics": mine,+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_write.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(stale_write.json()["conflicting_metric_uuids"], [snapshot["metrics"][0]["uuid"]])++ @parameterized.expand(+ [+ ("their_description_edit", {"description": "theirs"}, "description"),+ ("their_stats_config_edit", {"stats_config": {"method": "frequentist"}}, "stats_config"),+ ]+ )+ def test_concurrent_scalar_edit_does_not_block_stale_metrics_write(+ self, _name: str, their_payload: dict, edited_field: str+ ) -> None:+ # A metric-only PATCH omits scalar fields, so it can't clobber them: the other+ # side's scalar edit and this stale metric addition must both survive.+ snapshot = self._create_experiment(f"scalar-{edited_field}", metrics=[self._metric("base")])+ self.assertEqual(self._patch(snapshot["id"], their_payload).status_code, status.HTTP_200_OK)++ stale_metrics_write = self._patch(+ snapshot["id"],+ {+ "metrics": [*snapshot["metrics"], self._metric("mine")],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_metrics_write.status_code, status.HTTP_200_OK, stale_metrics_write.json())+ self.assertEqual(self._events(stale_metrics_write.json()["metrics"]), {"base", "mine"})+ their_value = their_payload[edited_field]+ current_value = stale_metrics_write.json()[edited_field]+ if isinstance(their_value, dict):+ self.assertEqual({key: current_value.get(key) for key in their_value}, their_value)+ else:+ self.assertEqual(current_value, their_value)++ def test_stale_scalar_write_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)++ stale_description_write = self._patch(+ snapshot["id"],+ {+ "description": "mine",+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_description_write.status_code, status.HTTP_409_CONFLICT)+ self.assertIn("description", stale_description_write.json()["conflicting_fields"])++ 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")]})+ self.assertEqual(added.status_code, status.HTTP_200_OK)+ added_uuid = next(m["uuid"] for m in added.json()["metrics"] if m["source"]["event"] == "m3")++ uuid_1, uuid_2 = (metric["uuid"] for metric in snapshot["metrics"])+ stale_reorder = self._patch(+ snapshot["id"],+ {+ "metrics": snapshot["metrics"],+ "primary_metrics_ordered_uuids": [uuid_2, uuid_1],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_reorder.status_code, status.HTTP_200_OK, stale_reorder.json())+ self.assertEqual(stale_reorder.json()["primary_metrics_ordered_uuids"], [uuid_2, uuid_1, added_uuid])++ def test_stale_shared_metric_removal_keeps_concurrently_linked_metric(self) -> None:+ saved_1 = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="Shared one",+ query={"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "EventsNode", "event": "s1"}},+ )+ saved_2 = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="Shared two",+ query={"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "EventsNode", "event": "s2"}},+ )+ created = self._create_experiment("shared-removal")+ linked = self._patch(+ created["id"], {"saved_metrics_ids": [{"id": saved_1.id, "metadata": {"type": "secondary"}}]}+ )+ self.assertEqual(linked.status_code, status.HTTP_200_OK)+ snapshot = linked.json()++ concurrent_link = self._patch(+ snapshot["id"],+ {+ "saved_metrics_ids": [+ {"id": saved_1.id, "metadata": {"type": "secondary"}},+ {"id": saved_2.id, "metadata": {"type": "secondary"}},+ ]+ },+ )+ self.assertEqual(concurrent_link.status_code, status.HTTP_200_OK)++ stale_removal = self._patch(+ snapshot["id"],+ {+ "saved_metrics_ids": [],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_removal.status_code, status.HTTP_200_OK, stale_removal.json())+ remaining = [link["saved_metric"] for link in stale_removal.json()["saved_metrics"]]+ self.assertEqual(remaining, [saved_2.id])++ def test_shared_metric_metadata_double_edit_conflicts(self) -> None:+ saved = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="Contested shared",+ query={"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "EventsNode", "event": "s1"}},+ )+ created = self._create_experiment("shared-metadata")+ linked = self._patch(created["id"], {"saved_metrics_ids": [{"id": saved.id, "metadata": {"type": "primary"}}]})+ self.assertEqual(linked.status_code, status.HTTP_200_OK)+ snapshot = linked.json()++ their_edit = self._patch(+ snapshot["id"], {"saved_metrics_ids": [{"id": saved.id, "metadata": {"type": "secondary"}}]}+ )+ self.assertEqual(their_edit.status_code, status.HTTP_200_OK)++ stale_edit = self._patch(+ snapshot["id"],+ {+ "saved_metrics_ids": [{"id": saved.id, "metadata": {"type": "primary", "breakdowns": []}}],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_edit.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(stale_edit.json()["conflicting_metric_uuids"], [f"saved_metric:{saved.id}"])++ def test_update_without_version_keeps_last_write_wins_behavior(self) -> None:+ snapshot = self._create_experiment("no-version", metrics=[self._metric("base")])+ self.assertEqual(+ self._patch(snapshot["id"], {"metrics": [*snapshot["metrics"], self._metric("theirs")]}).status_code,+ status.HTTP_200_OK,+ )++ unversioned_write = self._patch(snapshot["id"], {"metrics": snapshot["metrics"]})++ self.assertEqual(unversioned_write.status_code, status.HTTP_200_OK)+ self.assertEqual(self._events(unversioned_write.json()["metrics"]), {"base"})++ def test_null_stored_version_is_treated_as_zero(self) -> None:+ snapshot = self._create_experiment("null-version", metrics=[self._metric("base")])+ Experiment.objects.filter(id=snapshot["id"]).update(version=None)++ versioned_write = self._patch(snapshot["id"], {"description": "updated", "version": 0})++ self.assertEqual(versioned_write.status_code, status.HTTP_200_OK)+ self.assertEqual(versioned_write.json()["version"], 1)++ def test_sequential_writes_with_refreshed_version_increment_monotonically(self) -> None:+ snapshot = self._create_experiment("sequential", metrics=[self._metric("base")])+ first = self._patch(snapshot["id"], {"description": "first", "version": snapshot["version"]})+ self.assertEqual(first.status_code, status.HTTP_200_OK)+ self.assertEqual(first.json()["version"], snapshot["version"] + 1)++ second = self._patch(snapshot["id"], {"description": "second", "version": first.json()["version"]})+ self.assertEqual(second.status_code, status.HTTP_200_OK)+ self.assertEqual(second.json()["version"], snapshot["version"] + 2)++ def test_launch_fingerprint_churn_is_not_a_phantom_metric_conflict(self) -> None:+ snapshot = self._create_experiment("launch-churn", metrics=[self._metric("base")])+ launch = self.client.post(f"/api/projects/{self.team.id}/experiments/{snapshot['id']}/launch/")+ self.assertEqual(launch.status_code, status.HTTP_200_OK, launch.json())++ # The launch rewrote every metric fingerprint; that server-side churn must not read+ # as a concurrent edit of the metric this stale write edits.+ my_metric = {**snapshot["metrics"][0], "source": {"kind": "EventsNode", "event": "edited"}}+ stale_edit = self._patch(+ snapshot["id"],+ {+ "metrics": [my_metric],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_edit.status_code, status.HTTP_200_OK, stale_edit.json())+ self.assertEqual(self._events(stale_edit.json()["metrics"]), {"edited"})+ self.assertIsNotNone(stale_edit.json()["start_date"])++ def test_stale_metric_addition_merges_after_concurrent_launch(self) -> None:+ # A concurrent launch changes start_date, but a metric-only PATCH omits it,+ # so the stale addition merges and the launch survives.+ snapshot = self._create_experiment("launch-merge", metrics=[self._metric("base")])+ launch = self.client.post(f"/api/projects/{self.team.id}/experiments/{snapshot['id']}/launch/")+ self.assertEqual(launch.status_code, status.HTTP_200_OK)++ stale_edit = self._patch(+ snapshot["id"],+ {+ "metrics": [*snapshot["metrics"], self._metric("mine")],+ "version": snapshot["version"],+ "original_experiment": self._original(snapshot),+ },+ )++ self.assertEqual(stale_edit.status_code, status.HTTP_200_OK, stale_edit.json())+ self.assertEqual(self._events(stale_edit.json()["metrics"]), {"base", "mine"})+ self.assertIsNotNone(stale_edit.json()["start_date"])++ def test_version_without_original_is_plain_compare_and_swap(self) -> None:+ snapshot = self._create_experiment("plain-cas", metrics=[self._metric("base")])+ self.assertEqual(+ self._patch(snapshot["id"], {"metrics": [*snapshot["metrics"], self._metric("theirs")]}).status_code,+ status.HTTP_200_OK,+ )++ stale_write = self._patch(+ snapshot["id"],+ {"metrics": snapshot["metrics"], "version": snapshot["version"]},+ )++ self.assertEqual(stale_write.status_code, status.HTTP_409_CONFLICT)+ body = stale_write.json()+ self.assertEqual(body["current_version"], snapshot["version"] + 1)+ self.assertNotIn("conflicting_fields", body)diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex a1368ae118d5..39f781b06ada 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -824,6 +824,12 @@ export interface PaginatedExperimentBasicListApi {results: ExperimentBasicApi[]}+/**+ * 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.+ * @nullable+ */+export type ExperimentWriteApiOriginalExperiment = { [key: string]: unknown } | null+/*** A single release-condition group carrying only the overall rollout percentage, the one* groups entry the experiment input applies.@@ -1484,6 +1490,16 @@ export interface ExperimentWriteApi {only_count_matured_users?: boolean/** 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.+ * @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.+ * @nullable+ */+ original_experiment?: ExperimentWriteApiOriginalExperiment/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnumApi/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */@@ -1497,6 +1513,12 @@ export interface ExperimentWriteApi {readonly user_access_level: string | 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.+ * @nullable+ */+export type ExperimentApiOriginalExperiment = { [key: string]: unknown } | null+/*** Full experiment representation for the detail, create, and update endpoints.*@@ -1603,6 +1625,16 @@ export interface ExperimentApi {only_count_matured_users?: boolean/** 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.+ * @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.+ * @nullable+ */+ original_experiment?: ExperimentApiOriginalExperiment/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnumApi/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */@@ -1616,6 +1648,12 @@ export interface ExperimentApi {readonly user_access_level: string | 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.+ * @nullable+ */+export type PatchedExperimentWriteApiOriginalExperiment = { [key: string]: unknown } | null+/*** Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.*/@@ -1718,6 +1756,16 @@ export interface PatchedExperimentWriteApi {only_count_matured_users?: boolean/** 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.+ * @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.+ * @nullable+ */+ original_experiment?: PatchedExperimentWriteApiOriginalExperiment/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status?: ExperimentStatusEnumApi/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex 9812bca68259..b06e680ee75b 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -1361,6 +1361,7 @@"posthog_experiment"."end_date","posthog_experiment"."created_at","posthog_experiment"."updated_at",+ "posthog_experiment"."version","posthog_experiment"."archived","posthog_experiment"."feature_flag_auto_archived","posthog_experiment"."deleted",@@ -1711,6 +1712,7 @@"posthog_experiment"."end_date","posthog_experiment"."created_at","posthog_experiment"."updated_at",+ "posthog_experiment"."version","posthog_experiment"."archived","posthog_experiment"."feature_flag_auto_archived","posthog_experiment"."deleted",diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex 127677ce5fd1..2fcfc6ff3f43 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -1879,6 +1879,7 @@"posthog_experiment"."end_date","posthog_experiment"."created_at","posthog_experiment"."updated_at",+ "posthog_experiment"."version","posthog_experiment"."archived","posthog_experiment"."feature_flag_auto_archived","posthog_experiment"."deleted",@@ -1958,6 +1959,7 @@"posthog_experiment"."end_date","posthog_experiment"."created_at","posthog_experiment"."updated_at",+ "posthog_experiment"."version","posthog_experiment"."archived","posthog_experiment"."feature_flag_auto_archived","posthog_experiment"."deleted",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5a51338853df..45860d92a9b1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27479,6 +27479,12 @@ export namespace Schemas {ExitOnlyAtEnd: 'exit_only_at_end',} 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.+ * @nullable+ */+ export type ExperimentOriginalExperiment = { [key: string]: unknown } | null;+/*** * `cohort` - cohort* * `person` - person@@ -28157,6 +28163,16 @@ export namespace Schemas {only_count_matured_users?: boolean;/** 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.+ * @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.+ * @nullable+ */+ original_experiment?: ExperimentOriginalExperiment;/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnum;/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */@@ -28950,6 +28966,12 @@ export namespace Schemas {results: ExperimentSessionContextResponse[];}+ /**+ * 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.+ * @nullable+ */+ export type ExperimentWriteOriginalExperiment = { [key: string]: unknown } | null;+/*** Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.*/@@ -29052,6 +29074,16 @@ export namespace Schemas {only_count_matured_users?: boolean;/** 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.+ * @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.+ * @nullable+ */+ original_experiment?: ExperimentWriteOriginalExperiment;/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnum;/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */@@ -51419,6 +51451,12 @@ export namespace Schemas {readonly user_access_level?: string | 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.+ * @nullable+ */+ export type PatchedExperimentWriteOriginalExperiment = { [key: string]: unknown } | null;+/*** Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.*/@@ -51521,6 +51559,16 @@ export namespace Schemas {only_count_matured_users?: boolean;/** 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.+ * @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.+ * @nullable+ */+ original_experiment?: PatchedExperimentWriteOriginalExperiment;/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status?: ExperimentStatusEnum;/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 631c83bbc503..a27b2e29a676 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -4473,6 +4473,18 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod.describe('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.'),+ version: 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."+ ),+ 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.'+ ),}).describe('Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.')@@ -8231,6 +8243,18 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod.describe('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.'),+ version: 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."+ ),+ 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.'+ ),}).describe('Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.')@@ -11961,6 +11985,18 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod.describe('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.'),+ version: 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."+ ),+ 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.'+ ),}).describe('Full experiment representation for the detail, create, and update endpoints.\n\nExtends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric\ndefinitions (``metrics``\/``metrics_secondary``\/``saved_metrics``) and the write-side\nfields, and refreshes stale action names while serializing. The list endpoint uses the\nleaner ``ExperimentBasicSerializer`` instead.'diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex 201e1fd51d22..fcdb1b50ad8d 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -209,6 +209,8 @@ const ExperimentCreateSchema = ExperimentsCreateBody.omit({secondary_metrics_ordered_uuids: true,only_count_matured_users: true,update_feature_flag_params: true,+ version: true,+ original_experiment: true,}).extend({feature_flag: ExperimentsCreateBody.shape['feature_flag'].describe('Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag, in the flag\'s own filters shape. This is the canonical input for flag config. If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100) to customize the variant split. Set filters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to control the overall fraction of users entering the experiment. Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected. No specific variant key is required. The analysis baseline defaults to the variant keyed `control` (lowercase) when present, else the first variant; override with stats_config.baseline_variant_key. Convention: when the user describes variants as "A/B", "old/new", "original/redesign", or any other natural-language pair without naming explicit keys, key the baseline `control` and keep their wording in the variant `name`. When the user asks for specific keys, use them as-is and put the baseline first.'@@ -324,6 +326,8 @@ const ExperimentDuplicateSchema = ExperimentsDuplicateCreateParams.omit({ projecsecondary_metrics_ordered_uuids: true,only_count_matured_users: true,update_feature_flag_params: true,+ version: true,+ original_experiment: true,}).shape).extend({ id: z.preprocess(castStringToInt, ExperimentsDuplicateCreateParams.shape['id']) })@@ -1038,6 +1042,8 @@ const ExperimentUpdateSchema = ExperimentsPartialUpdateParams.omit({ project_id:primary_metrics_ordered_uuids: true,secondary_metrics_ordered_uuids: true,only_count_matured_users: true,+ version: true,+ original_experiment: true,}).shape).extend({