:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(experiments): eliminate false 409 conflicts on experiment updates (#78580)
Marcel Poelker1b195afe372e
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 939d0a699a7c..6ffe1aa3fbf8 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -604,6 +604,100 @@ describe('experimentLogic', () => {// ...but the user's rejected edit stays visible for review and retry.expect(logic.values.experiment.description).toEqual('stale write')})++ it('collapses identical concurrent dispatches into a single request', async () => {+ const snapshot = { ...experiment, version: 3 } as Experiment+ logic.actions.setUnmodifiedExperiment(snapshot)+ logic.actions.setExperiment(snapshot)+ api.update.mockResolvedValue({ ...snapshot, description: 'twice', version: 4 })++ await expectLogic(logic, () => {+ logic.actions.updateExperiment({ description: 'twice' })+ logic.actions.updateExperiment({ description: 'twice' })+ }).toFinishAllListeners()++ expect(api.update).toHaveBeenCalledTimes(1)+ expect(logic.values.unmodifiedExperiment?.version).toEqual(4)+ expect(logic.values.experiment.description).toEqual('twice')+ })++ it('queues a different concurrent update behind the in-flight one and sends the absorbed version', async () => {+ const snapshot = { ...experiment, version: 3 } as Experiment+ logic.actions.setUnmodifiedExperiment(snapshot)+ logic.actions.setExperiment(snapshot)+ api.update.mockResolvedValueOnce({ ...snapshot, description: 'first', version: 4 })+ api.update.mockResolvedValueOnce({ ...snapshot, description: 'first', name: 'renamed', version: 5 })++ await expectLogic(logic, () => {+ logic.actions.updateExperiment({ description: 'first' })+ logic.actions.updateExperiment({ name: 'renamed' })+ }).toFinishAllListeners()++ expect(api.update).toHaveBeenCalledTimes(2)+ expect(api.update).toHaveBeenNthCalledWith(+ 1,+ expect.stringContaining('/experiments/'),+ expect.objectContaining({ description: 'first', version: 3 })+ )+ // The second request waits for the first response and carries its absorbed+ // version, so it never enters the stale-write path at all.+ expect(api.update).toHaveBeenNthCalledWith(+ 2,+ expect.stringContaining('/experiments/'),+ expect.objectContaining({ name: 'renamed', version: 4 })+ )+ })++ it('still sends a queued update when the in-flight one fails', async () => {+ const snapshot = { ...experiment, version: 3 } as Experiment+ logic.actions.setUnmodifiedExperiment(snapshot)+ logic.actions.setExperiment(snapshot)+ api.update.mockRejectedValueOnce(new Error('network down'))+ api.update.mockResolvedValueOnce({ ...snapshot, name: 'second', version: 4 })++ await expectLogic(logic, () => {+ logic.actions.updateExperiment({ description: 'doomed' })+ logic.actions.updateExperiment({ name: 'second' })+ }).toFinishAllListeners()++ expect(api.update).toHaveBeenCalledTimes(2)+ expect(api.update).toHaveBeenLastCalledWith(+ expect.stringContaining('/experiments/'),+ expect.objectContaining({ name: 'second' })+ )+ expect(logic.values.unmodifiedExperiment?.version).toEqual(4)+ })++ it('never moves the concurrency snapshot backwards to an older version', async () => {+ // Concurrent writers (a user save and the running-time auto-save) absorb their+ // responses independently, and responses can land out of order: a late older+ // response poisoning the snapshot makes every following save a false conflict.+ logic.actions.setUnmodifiedExperiment({ ...experiment, version: 5, name: 'newer' } as Experiment)+ logic.actions.setUnmodifiedExperiment({ ...experiment, version: 4, name: 'late straggler' } as Experiment)+ expect(logic.values.unmodifiedExperiment?.name).toEqual('newer')++ logic.actions.setUnmodifiedExperiment({ ...experiment, version: 6, name: 'fresher' } as Experiment)+ expect(logic.values.unmodifiedExperiment?.name).toEqual('fresher')+ // Versionless snapshots (a draft being created) keep replacing freely.+ logic.actions.setUnmodifiedExperiment({+ ...experiment,+ version: undefined,+ name: 'no version',+ } as Experiment)+ expect(logic.values.unmodifiedExperiment?.name).toEqual('no version')++ const snapshot = { ...experiment, version: 3 } as Experiment+ logic.actions.setUnmodifiedExperiment(snapshot)+ logic.actions.setExperiment(snapshot)+ api.update.mockResolvedValueOnce({ ...snapshot, description: 'saved', version: 8 })+ await expectLogic(logic, () => {+ logic.actions.updateExperiment({ description: 'saved' })+ }).toFinishAllListeners()+ // The absorbed post-save state wins over a stale response landing afterwards, so+ // the next save carries version 8, not 3.+ logic.actions.setUnmodifiedExperiment(snapshot)+ expect(logic.values.unmodifiedExperiment?.version).toEqual(8)+ })})describe('moveMetricsBetweenSections', () => {const primaryMetric = {diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 8ffc61a0310f..0cb035e0a7c8 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -2077,7 +2077,18 @@ export const experimentLogic = kea<experimentLogicType>([unmodifiedExperiment: [null as Experiment | null,{- setUnmodifiedExperiment: (_, { experiment }) => experiment,+ // Every write path (user saves, the running-time auto-save, reorders) absorbs its+ // response here, and responses can land out of order. An older response arriving+ // after a newer one must not move this concurrency base backwards: a poisoned base+ // makes every following save from this tab stale, so it 409s as a false conflict+ // against the user's own earlier write.+ setUnmodifiedExperiment: (state, { experiment }) =>+ state &&+ typeof state.version === 'number' &&+ typeof experiment?.version === 'number' &&+ experiment.version < state.version+ ? state+ : experiment,},],// PRIMARY METRICS@@ -3628,7 +3639,7 @@ export const experimentLogic = kea<experimentLogicType>([}},})),- loaders(({ actions, values }) => ({+ loaders(({ actions, values, cache }) => ({experiment: {loadExperiment: async (payload?: { triggeredBy?: ExperimentTriggeredBy }) => {void payload?.triggeredBy@@ -3682,40 +3693,68 @@ export const experimentLogic = kea<experimentLogicType>([null as Experiment | null,{updateExperiment: async (update: ExperimentUpdatePayload) => {- 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.'+ // The concurrency payload is built inside `send`, when the request actually+ // runs, so a queued update reads the version absorbed from its predecessor's+ // response instead of the one both dispatches started from.+ const send = async (): Promise<Experiment> => {+ try {+ const response: Experiment = await api.update(+ `api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,+ { ...toConcurrencyPayload(values.unmodifiedExperiment), ...update })- // 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 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.')- const freshWithOrdering = initializeMetricOrdering(fresh)- actions.setUnmodifiedExperiment(structuredClone(freshWithOrdering))- actions.setExperiment({ ...freshWithOrdering, ...preserved })- } catch {- actions.loadExperiment()+ // 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}- throw error}++ // Concurrent dispatches would race each other into the server's lock window+ // carrying the same version, so the loser 409s even though its change saved.+ // A dispatch identical to the in-flight one (double click, twin listeners)+ // shares its request; a different one queues behind it.+ const key = JSON.stringify(update)+ const inflight: { key: string; promise: Promise<Experiment> } | undefined = cache.inflightUpdate+ if (inflight && inflight.key === key) {+ return inflight.promise+ }+ // Swallow the predecessor's error: it surfaces on its own dispatch, and a+ // failed save must not block the queued one.+ const promise = (inflight ? inflight.promise.catch(() => {}) : Promise.resolve()).then(send)+ const record = { key, promise }+ cache.inflightUpdate = record+ void promise+ .catch(() => {})+ .finally(() => {+ if (cache.inflightUpdate === record) {+ cache.inflightUpdate = undefined+ }+ })+ return promise},},],diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex b1ff5334ad8f..bcdf403ae96b 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -332,6 +332,12 @@ def _metric_merge_view(metric: dict) -> dict:return {k: v for k, v in metric.items() if k != "fingerprint"}+def _metric_list_view(metrics: list | None) -> list:+ """A whole metric array as compared for concurrency resolution: per-item merge views,+ order-sensitive."""+ return [_metric_merge_view(m) if isinstance(m, dict) else m for m in (metrics or [])]++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")}@@ -446,6 +452,14 @@ def _concurrency_value_view(value: Any, depth: int = 0) -> Any:return value+# Estimate keys the running-time calculator auto-saves on every results load of a launched+# experiment, silently bumping the version. Comparing them would make that machine churn read+# as a concurrent user edit and 409 any stale tab's save that carries the field, so concurrency+# resolution only compares the user-set configuration around them (mirroring how metric+# ``fingerprint`` churn is stripped by ``_metric_merge_view``).+_RUNNING_TIME_MACHINE_KEYS = frozenset({"recommended_running_time", "recommended_sample_size"})++def _scalar_merge_view(field: str, value: Any) -> Any:"""The value of one scalar payload field as compared for concurrency resolution.@@ -453,12 +467,19 @@ def _scalar_merge_view(field: str, value: Any) -> Any: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 thestored column when all sides are compared flag-stripped, with empty and null collapsed.+ ``running_time_calculation`` is compared with its machine-recomputed estimate keys+ stripped for the same reason (see ``_RUNNING_TIME_MACHINE_KEYS``)."""if field == "parameters":if value is None:return {}if isinstance(value, dict):value = ExperimentService._strip_feature_flag_config(value)+ if field == "running_time_calculation":+ if value is None:+ return {}+ if isinstance(value, dict):+ value = {key: item for key, item in value.items() if key not in _RUNNING_TIME_MACHINE_KEYS}return _concurrency_value_view(value)@@ -3149,14 +3170,14 @@ class ExperimentService:experiment: Experiment,*,request: Any | None,- resolution: Literal["merged", "rejected"],+ resolution: Literal["merged", "rejected", "noop"],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``+ broken down by ``resolution`` to watch the merged/noop/409 ratio; ``conflicting_fields``shows what users trip on."""if request is None:return@@ -3194,6 +3215,39 @@ class ExperimentService:if field not in CONCURRENCY_MERGEABLE_FIELDS and field != "get_feature_flag_key"}+ def _update_is_noop(+ self,+ experiment: Experiment,+ update_data: Mapping,+ saved_metrics_data: list[dict] | None,+ ) -> bool:+ """Whether applying the update to ``experiment``'s current (freshly re-read) state+ would change nothing.++ Comparisons reuse the concurrency merge views so server-derived churn does not read+ as a difference: metric ``fingerprint``s are recomputed on every write and stripped+ by ``_metric_merge_view``, and ``parameters`` is compared flag-stripped by+ ``_scalar_merge_view``. ``saved_metrics_data`` carries the payload's saved-metric+ links when the update includes them (the caller pops them out of ``update_data``);+ pass ``None`` when the update does not touch them.+ """+ for field, stored_value in self._current_scalar_values(experiment, update_data).items():+ if _scalar_merge_view(field, update_data[field]) != _scalar_merge_view(field, stored_value):+ return False+ for field in ("metrics", "metrics_secondary"):+ if field in update_data and _metric_list_view(update_data[field]) != _metric_list_view(+ getattr(experiment, field)+ ):+ return False+ for field in ("primary_metrics_ordered_uuids", "secondary_metrics_ordered_uuids"):+ if field in update_data and update_data[field] != getattr(experiment, field):+ return False+ if saved_metrics_data is not None and _links_by_id(saved_metrics_data) != _links_by_id(+ self._current_saved_metric_link_dicts(experiment)+ ):+ return False+ return True+def _resolve_concurrent_update(self,experiment: Experiment,@@ -3295,7 +3349,10 @@ class ExperimentService:``update_data`` may carry two opt-in concurrency keys, ``version`` (the version the clientlast read) and ``original_experiment`` (the state it last saw): a stale write is then mergedper metric uuid where safe and rejected with ``ExperimentVersionConflict`` (409) otherwise.- Without them the write applies as-is; either way the stored ``version`` is bumped.+ A versioned write that races the row lock but would change nothing against the committed+ state (a duplicate dispatch, or a retry of a request that landed) succeeds as a no-op+ without bumping ``version``. Without the keys the write applies as-is; ``version`` is+ bumped on every save."""update_feature_flag_params = update_data.pop("update_feature_flag_params", False)client_version = update_data.pop("version", None)@@ -3307,7 +3364,8 @@ class ExperimentService:# 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.+ # racing this window still conflicts (or no-ops, when the surviving update+ # matches what the racer committed) instead of interleaving.resolution_version: int | None = Noneif client_version is not None:experiment.refresh_from_db()@@ -3556,6 +3614,24 @@ class ExperimentService:or 0)if resolution_version is not None and locked_version != resolution_version:+ # A writer committed in the window between the unlocked resolution read and+ # this lock. The dominant case is a duplicate of this very request (the UI+ # dispatching one save twice, or an API client retrying after a timeout), so+ # re-read the row (stable under the lock) and skip the save when the surviving+ # update would change nothing: succeeding is honest, because the requested+ # state is exactly what is stored, and the flag sync above wrote the same flag+ # config the winning twin synced. No version bump either, since a second bump+ # for one logical change would re-stale every other open tab.+ experiment.refresh_from_db()+ if self._update_is_noop(experiment, update_data, saved_metrics_data if update_saved_metrics else None):+ self._report_update_conflict(+ experiment,+ request=report_request,+ resolution="noop",+ versions_behind=locked_version - client_version,+ base_snapshot_sent=original_experiment is not None,+ )+ return experimentlocked_conflict = ExperimentVersionConflict(current_version=locked_version)if client_version is not None:self._report_update_conflict(diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex af57ffa8b691..f356fc3e78fe 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -11,6 +11,7 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, PropertyMock, patch+from django.db.models import Ffrom django.test import SimpleTestCasefrom django.utils import timezone@@ -39,6 +40,7 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.experiment_service import (ExperimentService,+ ExperimentVersionConflict,_deprecated_fields_in_request,_deprecated_parameters_keys_in_request,_merge_metric_arrays,@@ -2038,6 +2040,81 @@ class TestExperimentService(APIBaseTest):assert second_link is not Noneassert second_link.saved_metric_id == sm2.id+ @contextmanager+ def _concurrent_write_in_lock_window(self, experiment_id: int, **twin_update: Any):+ """Commit a concurrent write inside update_experiment's race window: after the+ unlocked concurrency resolution but before the row-locked version re-check, by+ hooking the flag sync that runs between them."""+ real_sync = ExperimentService._sync_feature_flag_on_update++ def twin_write_then_sync(service: ExperimentService, *args: Any, **kwargs: Any) -> None:+ Experiment.objects.filter(pk=experiment_id).update(version=F("version") + 1, **twin_update)+ return real_sync(service, *args, **kwargs)++ with patch.object(+ ExperimentService, "_sync_feature_flag_on_update", autospec=True, side_effect=twin_write_then_sync+ ):+ yield++ @patch("products.experiments.backend.experiment_service.report_user_action")+ def test_duplicate_update_racing_the_lock_window_succeeds_as_noop(self, mock_report_user_action):+ experiment = self._create_draft_experiment(flag_key="lock-window-noop")+ service = self._service()+ version = experiment.version or 0++ with self._concurrent_write_in_lock_window(experiment.pk, description="the same edit"):+ result = service.update_experiment(+ experiment,+ {"description": "the same edit", "version": version},+ serializer_context=service._build_serializer_context(),+ )++ assert result.version == version + 1+ stored = Experiment.objects.get(pk=experiment.pk)+ assert stored.description == "the same edit"+ # Only the twin's bump: a second bump for the same logical change would re-stale+ # every other open tab.+ assert stored.version == version + 1+ concurrency_events = [+ call for call in mock_report_user_action.call_args_list if call.args[1] == "experiment update concurrency"+ ]+ assert [call.args[2]["resolution"] for call in concurrency_events] == ["noop"]+ assert concurrency_events[0].args[2]["versions_behind"] == 1++ def test_conflicting_update_racing_the_lock_window_still_conflicts(self):+ experiment = self._create_draft_experiment(flag_key="lock-window-conflict")+ service = self._service()+ version = experiment.version or 0++ with self._concurrent_write_in_lock_window(experiment.pk, description="their edit"):+ with self.assertRaises(ExperimentVersionConflict) as ctx:+ service.update_experiment(experiment, {"description": "my edit", "version": version})++ assert ctx.exception.conflicting_fields == []+ stored = Experiment.objects.get(pk=experiment.pk)+ assert stored.description == "their edit"+ assert stored.version == version + 1++ def test_duplicate_metrics_update_racing_the_lock_window_ignores_fingerprint_churn(self):+ experiment = self._create_draft_experiment(flag_key="lock-window-fingerprint")+ service = self._service()+ version = experiment.version or 0+ stored_metric = (experiment.metrics or [])[0]+ resubmitted = {key: value for key, value in stored_metric.items() if key != "fingerprint"}++ with self._concurrent_write_in_lock_window(+ experiment.pk, metrics=[{**stored_metric, "fingerprint": "recomputed-by-the-twin"}]+ ):+ result = service.update_experiment(+ experiment, {"metrics": [resubmitted], "version": version}, allow_unknown_events=True+ )++ assert result.version == version + 1+ stored = Experiment.objects.get(pk=experiment.pk)+ assert stored.version == version + 1+ # The short-circuit skipped the save: the twin's row (fingerprint included) is intact.+ assert (stored.metrics or [])[0]["fingerprint"] == "recomputed-by-the-twin"+def _updated_events(self, mock_report_user_action):return [c for c in mock_report_user_action.call_args_list if c.args[1] == "experiment updated"]@@ -7192,6 +7269,40 @@ class TestScalarConcurrencyResolution(SimpleTestCase):{"parameters": {"variant_notes": {"control": "mine"}}},["parameters"],),+ (+ # The calculator auto-save rewrites the recommended_* estimates on every results+ # load, so a stale tab's echo of older estimates is machine churn, not a user edit.+ "running_time_estimate_churn_is_not_a_conflict",+ {"running_time_calculation": {"minimum_detectable_effect": 5, "recommended_running_time": 12}},+ {"running_time_calculation": {"minimum_detectable_effect": 5, "recommended_running_time": 9}},+ {"running_time_calculation": {"minimum_detectable_effect": 5, "recommended_running_time": 30}},+ {"running_time_calculation": {"minimum_detectable_effect": 5, "recommended_running_time": 12}},+ [],+ ),+ (+ "running_time_config_edit_survives_estimate_churn",+ {"running_time_calculation": {"minimum_detectable_effect": 10, "recommended_running_time": 9}},+ {"running_time_calculation": {"minimum_detectable_effect": 5, "recommended_running_time": 9}},+ {"running_time_calculation": {"minimum_detectable_effect": 5, "recommended_running_time": 30}},+ {"running_time_calculation": {"minimum_detectable_effect": 10, "recommended_running_time": 9}},+ [],+ ),+ (+ "running_time_config_double_edit_still_conflicts",+ {"running_time_calculation": {"minimum_detectable_effect": 10}},+ {"running_time_calculation": {"minimum_detectable_effect": 5}},+ {"running_time_calculation": {"minimum_detectable_effect": 20, "recommended_running_time": 30}},+ {"running_time_calculation": {"minimum_detectable_effect": 10}},+ ["running_time_calculation"],+ ),+ (+ "running_time_null_base_vs_machine_only_current_is_not_a_conflict",+ {"running_time_calculation": {"minimum_detectable_effect": 5}},+ {"running_time_calculation": None},+ {"running_time_calculation": {"recommended_running_time": 30, "recommended_sample_size": 100}},+ {"running_time_calculation": {"minimum_detectable_effect": 5}},+ [],+ ),])def test_resolve_scalar_updates(diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex d3f379d7b788..6d76282762c6 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -10,6 +10,7 @@ from unittest.mock import ANY, MagicMock, patchfrom django.core.cache import cachefrom django.db import connection+from django.db.models import Ffrom django.test.utils import CaptureQueriesContextfrom dateutil import parser@@ -28,6 +29,7 @@ from posthog.test.test_journeys import journeys_forfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.event_definition import EventDefinition+from products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.hogql_queries.exposure_query_logic import (EXPERIMENT_EXPOSURE_EVENT_CUTOFF,EXPERIMENT_EXPOSURE_EVENT_FLAG,@@ -9570,3 +9572,76 @@ class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):body = stale_write.json()self.assertEqual(body["current_version"], snapshot["version"] + 1)self.assertNotIn("conflicting_fields", body)++ def test_duplicate_patch_racing_the_lock_window_succeeds_as_noop(self) -> None:+ # The UI sometimes dispatches one save as two parallel PATCHes: the loser reaches the+ # row-locked version re-check only after the winner committed the identical change.+ # It must succeed with the current state instead of 409ing on a change that saved.+ snapshot = self._create_experiment("lock-window-twin", metrics=[self._metric("base")])+ real_sync = ExperimentService._sync_feature_flag_on_update++ def twin_write_then_sync(service: ExperimentService, *args: Any, **kwargs: Any) -> None:+ Experiment.objects.filter(pk=snapshot["id"]).update(description="the same edit", version=F("version") + 1)+ return real_sync(service, *args, **kwargs)++ with patch.object(+ ExperimentService, "_sync_feature_flag_on_update", autospec=True, side_effect=twin_write_then_sync+ ):+ duplicate = self._patch(+ snapshot["id"],+ {+ "description": "the same edit",+ "version": snapshot["version"],+ "original_experiment": self._original_with_scalars(snapshot),+ },+ )++ self.assertEqual(duplicate.status_code, status.HTTP_200_OK, duplicate.json())+ self.assertEqual(duplicate.json()["description"], "the same edit")+ self.assertEqual(duplicate.json()["version"], snapshot["version"] + 1)++ def test_stale_running_time_config_edit_merges_over_estimate_churn(self) -> None:+ # The calculator auto-save rewrites recommended_* on every results load, so a tab is+ # routinely several versions behind holding a stale estimate echo. Editing the MDE from+ # that tab must not read as a double-edit of running_time_calculation.+ created = self._create_experiment("rtc-churn", metrics=[self._metric("base")])+ seeded = self._patch(+ created["id"],+ {+ "running_time_calculation": {+ "minimum_detectable_effect": 5,+ "recommended_running_time": 9,+ "recommended_sample_size": 800,+ }+ },+ )+ self.assertEqual(seeded.status_code, status.HTTP_200_OK)+ snapshot = seeded.json()++ churn = self._patch(+ snapshot["id"],+ {+ "running_time_calculation": {+ "minimum_detectable_effect": 5,+ "recommended_running_time": 30,+ "recommended_sample_size": 4000,+ }+ },+ )+ self.assertEqual(churn.status_code, status.HTTP_200_OK)++ stale_config_edit = self._patch(+ snapshot["id"],+ {+ "running_time_calculation": {+ "minimum_detectable_effect": 10,+ "recommended_running_time": 9,+ "recommended_sample_size": 800,+ },+ "version": snapshot["version"],+ "original_experiment": self._original_with_scalars(snapshot),+ },+ )++ self.assertEqual(stale_config_edit.status_code, status.HTTP_200_OK, stale_config_edit.json())+ self.assertEqual(stale_config_edit.json()["running_time_calculation"]["minimum_detectable_effect"], 10)