: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): deduplicate uuid on experiment operations. (#59729)
Rodrigo Iloro19c458448324
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 644da571d175..be6827f95f50 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -620,8 +620,17 @@ class ExperimentService:creation_mode: ExperimentCreationMode = "new",) -> Experiment:"""Create experiment with full validation and defaults."""- metrics = self._assign_uuids_to_metrics(metrics)- metrics_secondary = self._assign_uuids_to_metrics(metrics_secondary)+ # Seed the dedup set with uuids the inline metrics must not collide with:+ # - any saved-metric uuids referenced via saved_metrics_ids (their query.uuid+ # appears in the ordering arrays, so any inline copy must be regenerated).+ # Then share ``seen`` across primary + secondary so a uuid present on one+ # list can't collide with the other. Regenerated dups don't need an+ # ordering remap: the kept incumbent still uses the original uuid, so any+ # ordering reference to it remains valid. The regenerated uuid is appended+ # to ordering by the loop below as a brand-new entry.+ seen_metric_uuids: set[str] = self._collect_saved_metric_uuids(saved_metrics_ids)+ metrics = self._assign_uuids_to_metrics(metrics, seen=seen_metric_uuids)+ metrics_secondary = self._assign_uuids_to_metrics(metrics_secondary, seen=seen_metric_uuids)self.validate_variant_shapes(parameters)self.validate_variant_percentages(parameters)self.validate_experiment_metrics(metrics)@@ -866,21 +875,86 @@ class ExperimentService:raise ValidationError("Feature flag must have a variant with key 'control'")@staticmethod- def _assign_uuids_to_metrics(metrics: list[dict] | None) -> list[dict] | None:- """Return a deep copy of ``metrics`` with a ``uuid`` filled in on every entry.-- Run this before metric validation so the validated dict already carries its- final uuid. Callers pass dicts by reference, so we deepcopy to avoid leaking- the generated uuid back into their data.+ def _assign_uuids_to_metrics(+ metrics: list[dict] | None,+ *,+ seen: set[str] | None = None,+ ) -> list[dict] | None:+ """Return a deep copy of ``metrics`` with a unique ``uuid`` on every entry.++ Fills missing uuids and regenerates any uuid that collides with one already+ in ``seen`` (used to share a single uniqueness space across primary ++ secondary metric lists, plus saved-metric query uuids).++ Ordering arrays don't need a remap from this function: the first occurrence+ of a duplicated uuid keeps its original value, so existing ordering entries+ stay valid; regenerated duplicates are handled as new additions by+ ``_sync_ordering_with_metric_changes`` (update path) or by the append loop+ in ``create_experiment``.++ Callers pass dicts by reference, so we deepcopy to avoid leaking the+ generated uuid back into their data."""if metrics is None:return Noneprepared = deepcopy(metrics)+ seen = seen if seen is not None else set()for metric in prepared:- if not metric.get("uuid"):- metric["uuid"] = str(uuid4())+ original = metric.get("uuid")+ if not original or original in seen:+ new_uuid = str(uuid4())+ metric["uuid"] = new_uuid+ seen.add(new_uuid)+ else:+ seen.add(original)return prepared+ @staticmethod+ def _remap_ordering(ordering: list[str] | None, remap: dict[str, str]) -> list[str] | None:+ """Rewrite an ordering array with the old→new uuid mapping from dedup."""+ if not ordering or not remap:+ return ordering+ return [remap.get(uuid, uuid) for uuid in ordering]++ def _collect_saved_metric_uuids(self, saved_metrics_ids: list | None) -> set[str]:+ """Return the set of saved-metric query uuids referenced by ``saved_metrics_ids``.++ These uuids live in the experiment's ordering arrays alongside inline-metric+ uuids. Any inline metric in the same write must not collide with one — if+ the payload reuses a saved-metric uuid for an inline metric, dedup+ regenerates the inline copy so each ordering entry resolves to one thing.+ """+ if not saved_metrics_ids:+ return set()+ ids = [sm["id"] for sm in saved_metrics_ids if isinstance(sm, dict) and "id" in sm]+ if not ids:+ return set()+ seen: set[str] = set()+ for sm in ExperimentSavedMetric.objects.filter(id__in=ids, team_id=self.team.id).only("query"):+ if sm.query and (uuid := sm.query.get("uuid")):+ seen.add(uuid)+ return seen++ @staticmethod+ def _regenerate_all_metric_uuids(metrics: list[dict] | None) -> tuple[list[dict] | None, dict[str, str]]:+ """Return a deep copy of ``metrics`` with every uuid regenerated.++ Used by clone flows so a cloned experiment never shares metric uuids with+ its source. Returns the prepared list plus an old→new mapping the caller+ threads into the corresponding ordering array.+ """+ if metrics is None:+ return None, {}+ prepared = deepcopy(metrics)+ remap: dict[str, str] = {}+ for metric in prepared:+ new_uuid = str(uuid4())+ original = metric.get("uuid")+ if original:+ remap[original] = new_uuid+ metric["uuid"] = new_uuid+ return prepared, remap+@staticmethoddef _recompute_fingerprints(metrics: list[dict],@@ -1608,14 +1682,47 @@ class ExperimentService:if "saved_metrics_ids" in update_data:self.validate_saved_metrics_ids(update_data["saved_metrics_ids"], self.team.id)++ # Seed the uniqueness set with uuids that must remain stable in the+ # ordering arrays — any inline metric reusing one of these gets+ # regenerated to keep ordering entries unambiguous:+ # - the stored inline metric list NOT being updated (a primary-only+ # update must not collide with the stored secondary, and vice versa).+ # - saved-metric query uuids (post-update set: the payload's+ # saved_metrics_ids if supplied, otherwise the experiment's current+ # links).+ seen_metric_uuids: set[str] = set()+ if "metrics" in update_data and "metrics_secondary" not in update_data:+ for metric in experiment.metrics_secondary or []:+ if uuid := metric.get("uuid"):+ seen_metric_uuids.add(uuid)+ if "metrics_secondary" in update_data and "metrics" not in update_data:+ for metric in experiment.metrics or []:+ if uuid := metric.get("uuid"):+ seen_metric_uuids.add(uuid)+ if "saved_metrics_ids" in update_data:+ seen_metric_uuids |= self._collect_saved_metric_uuids(update_data["saved_metrics_ids"])+ else:+ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():+ if link.saved_metric.query and (uuid := link.saved_metric.query.get("uuid")):+ seen_metric_uuids.add(uuid)++ # Regenerated dups don't need an ordering remap: the original uuid is+ # kept on the incumbent so any ordering reference to it remains valid+ # (including references to saved-metric uuids that happen to be inlined).+ # _sync_ordering_with_metric_changes runs later and appends the new+ # regenerated uuids as additions; _sync_ordering_for_saved_metrics_on_update+ # handles saved-metric link uuids independently.if "metrics" in update_data:- update_data["metrics"] = self._assign_uuids_to_metrics(update_data["metrics"])+ update_data["metrics"] = self._assign_uuids_to_metrics(update_data["metrics"], seen=seen_metric_uuids)self.validate_experiment_metrics(update_data["metrics"])self.validate_metric_action_ids(update_data["metrics"], self.team.id)if not allow_unknown_events:self.validate_metric_event_names(update_data["metrics"])if "metrics_secondary" in update_data:- update_data["metrics_secondary"] = self._assign_uuids_to_metrics(update_data["metrics_secondary"])+ update_data["metrics_secondary"] = self._assign_uuids_to_metrics(+ update_data["metrics_secondary"], seen=seen_metric_uuids+ )self.validate_experiment_metrics(update_data["metrics_secondary"])self.validate_metric_action_ids(update_data["metrics_secondary"], self.team.id)if not allow_unknown_events:@@ -1740,9 +1847,12 @@ class ExperimentService:if "stats_config" in update_data:self.validate_stats_config(update_data["stats_config"])- updated_primary = update_data.get("metrics", experiment.metrics)- updated_secondary = update_data.get("metrics_secondary", experiment.metrics_secondary)- self.validate_no_duplicate_metric_uuids(updated_primary, updated_secondary)+ # Defense-in-depth: only validate the inline metric lists this update+ # is actually touching. Dedup-on-input has already made these lists+ # unique; validating the stored arrays would block a soft-delete (or any+ # other PATCH) on rows that pre-date the dedup logic.+ if "metrics" in update_data or "metrics_secondary" in update_data:+ self.validate_no_duplicate_metric_uuids(update_data.get("metrics"), update_data.get("metrics_secondary"))# --- fingerprint recalculation -------------------------------------start_date = update_data.get("start_date", experiment.start_date)@@ -1922,6 +2032,18 @@ class ExperimentService:for link in source_experiment.experimenttosavedmetric_set.all()] or None+ # Regenerate metric uuids so the clone has its own identity space — sharing+ # uuids with the source is a foot-gun for any code that uses uuid as a+ # metric identifier across experiments (recalculations, fingerprints).+ cloned_metrics, primary_remap = self._regenerate_all_metric_uuids(source_experiment.metrics)+ cloned_metrics_secondary, secondary_remap = self._regenerate_all_metric_uuids(+ source_experiment.metrics_secondary+ )+ cloned_primary_ordering = self._remap_ordering(source_experiment.primary_metrics_ordered_uuids, primary_remap)+ cloned_secondary_ordering = self._remap_ordering(+ source_experiment.secondary_metrics_ordered_uuids, secondary_remap+ )+service = ExperimentService(team=target, user=self.user) if is_cross_project else selfcreation_mode: ExperimentCreationMode = "copy_to_project" if is_cross_project else "duplicate"return service.create_experiment(@@ -1931,14 +2053,14 @@ class ExperimentService:type=source_experiment.type or "product",parameters=parameters,filters=source_experiment.filters,- metrics=deepcopy(source_experiment.metrics),- metrics_secondary=deepcopy(source_experiment.metrics_secondary),+ metrics=cloned_metrics,+ metrics_secondary=cloned_metrics_secondary,stats_config=source_experiment.stats_config,scheduling_config=source_experiment.scheduling_config,exposure_criteria=source_experiment.exposure_criteria,saved_metrics_ids=saved_metrics_data,- primary_metrics_ordered_uuids=source_experiment.primary_metrics_ordered_uuids,- secondary_metrics_ordered_uuids=source_experiment.secondary_metrics_ordered_uuids,+ primary_metrics_ordered_uuids=cloned_primary_ordering,+ secondary_metrics_ordered_uuids=cloned_secondary_ordering,only_count_matured_users=source_experiment.only_count_matured_users,serializer_context=serializer_context,# For duplicate we set allow_unknown_events since the goal here is to actually duplicate:diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex d2110a3439aa..42388921c16c 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -3756,55 +3756,74 @@ class TestExperimentService(APIBaseTest):)assert experiment.id is not None- def test_duplicate_metric_uuids_raises_validation_error(self):- """Metrics with duplicate UUIDs should be rejected."""+ def test_duplicate_metric_uuids_within_list_are_regenerated(self):+ """Duplicate metric UUIDs within one list should be silently regenerated.++ First occurrence keeps the supplied uuid; later occurrences get fresh ones,+ and the ordering array is rewritten to match.+ """+ shared_uuid = "11bfb66a-51f5-48d0-a87e-bde2b4c958a6"service = self._service()- with self.assertRaises(ValidationError):- service.create_experiment(- name="Dup UUIDs",- feature_flag_key="dup-uuid-flag",- allow_unknown_events=True,- metrics=[- {- "kind": "ExperimentMetric",- "metric_type": "mean",- "uuid": "11bfb66a-51f5-48d0-a87e-bde2b4c958a6",- "source": {"kind": "EventsNode", "event": "$pageview"},- },- {- "kind": "ExperimentMetric",- "metric_type": "mean",- "uuid": "11bfb66a-51f5-48d0-a87e-bde2b4c958a6",- "source": {"kind": "EventsNode", "event": "other_event"},- },- ],- )+ experiment = service.create_experiment(+ name="Dup UUIDs",+ feature_flag_key="dup-uuid-flag",+ allow_unknown_events=True,+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "other_event"},+ },+ ],+ )+ assert experiment.metrics is not None+ uuid_0 = experiment.metrics[0]["uuid"]+ uuid_1 = experiment.metrics[1]["uuid"]+ assert uuid_0 == shared_uuid+ assert uuid_1 != shared_uuid+ UUID(uuid_1)+ assert experiment.primary_metrics_ordered_uuids is not None+ assert set(experiment.primary_metrics_ordered_uuids) == {uuid_0, uuid_1}- def test_duplicate_metric_uuids_across_primary_and_secondary_raises(self):- """Duplicate UUIDs across primary and secondary metrics should also be rejected."""+ def test_duplicate_metric_uuids_across_primary_and_secondary_are_regenerated(self):+ """Cross-list collisions are deduped — secondary gets a fresh uuid."""+ shared_uuid = "11bfb66a-51f5-48d0-a87e-bde2b4c958a6"service = self._service()- with self.assertRaises(ValidationError):- service.create_experiment(- name="Dup UUIDs Cross",- feature_flag_key="dup-uuid-cross-flag",- allow_unknown_events=True,- metrics=[- {- "kind": "ExperimentMetric",- "metric_type": "mean",- "uuid": "11bfb66a-51f5-48d0-a87e-bde2b4c958a6",- "source": {"kind": "EventsNode", "event": "$pageview"},- },- ],- metrics_secondary=[- {- "kind": "ExperimentMetric",- "metric_type": "mean",- "uuid": "11bfb66a-51f5-48d0-a87e-bde2b4c958a6",- "source": {"kind": "EventsNode", "event": "other_event"},- },- ],- )+ experiment = service.create_experiment(+ name="Dup UUIDs Cross",+ feature_flag_key="dup-uuid-cross-flag",+ allow_unknown_events=True,+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ ],+ metrics_secondary=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "other_event"},+ },+ ],+ )+ assert experiment.metrics is not None+ assert experiment.metrics_secondary is not None+ primary_uuid = experiment.metrics[0]["uuid"]+ secondary_uuid = experiment.metrics_secondary[0]["uuid"]+ assert primary_uuid == shared_uuid+ assert secondary_uuid != shared_uuid+ UUID(secondary_uuid)def test_metrics_without_uuids_get_auto_assigned(self):"""Metrics with no UUID should get unique auto-generated UUIDs on create."""@@ -3891,6 +3910,275 @@ class TestExperimentService(APIBaseTest):UUID(uuid_1)assert uuid_0 != uuid_1+ def test_update_dedupes_metric_uuids_on_input(self):+ """Updating an experiment with duplicate uuids in the payload should regenerate the dups."""+ self._create_flag(key="dup-update-flag")+ service = self._service()+ experiment = service.create_experiment(+ name="To dedupe",+ feature_flag_key="dup-update-flag",+ allow_unknown_events=True,+ )+ shared_uuid = "11bfb66a-51f5-48d0-a87e-bde2b4c958a6"+ updated = service.update_experiment(+ experiment,+ {+ "metrics": [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "other_event"},+ },+ ],+ },+ allow_unknown_events=True,+ )+ assert updated.metrics is not None+ uuid_0 = updated.metrics[0]["uuid"]+ uuid_1 = updated.metrics[1]["uuid"]+ assert uuid_0 == shared_uuid+ assert uuid_1 != shared_uuid+ UUID(uuid_1)++ def test_soft_delete_succeeds_when_stored_metrics_had_duplicate_uuids(self):+ """An experiment with corrupt (duplicated) uuids in storage should still be soft-deletable.++ Pre-migration data could have two metrics sharing one uuid in the DB. The+ post-migration code path should not block a soft-delete PATCH on that row.+ """+ self._create_flag(key="corrupt-soft-delete")+ service = self._service()+ experiment = service.create_experiment(+ name="Corrupt",+ feature_flag_key="corrupt-soft-delete",+ allow_unknown_events=True,+ )+ # Bypass the service to plant corrupt data, mirroring what legacy rows look like.+ shared_uuid = "22bfb66a-51f5-48d0-a87e-bde2b4c958a6"+ Experiment.objects.filter(id=experiment.id).update(+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": shared_uuid,+ "source": {"kind": "EventsNode", "event": "other_event"},+ },+ ],+ primary_metrics_ordered_uuids=[shared_uuid, shared_uuid],+ )+ experiment.refresh_from_db()++ updated = service.update_experiment(experiment, {"deleted": True}, allow_unknown_events=True)+ assert updated.deleted is True++ def test_clone_regenerates_metric_uuids(self):+ """Cloning an experiment must produce metrics with fresh uuids — never shared with the source."""+ self._create_flag(key="clone-fresh-uuids")+ service = self._service()+ source = service.create_experiment(+ name="Source",+ feature_flag_key="clone-fresh-uuids",+ allow_unknown_events=True,+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ ],+ metrics_secondary=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "other_event"},+ },+ ],+ )+ assert source.metrics is not None+ assert source.metrics_secondary is not None+ source_primary_uuid = source.metrics[0]["uuid"]+ source_secondary_uuid = source.metrics_secondary[0]["uuid"]++ dup = service.duplicate_experiment(source)++ assert dup.metrics is not None+ assert dup.metrics_secondary is not None+ dup_primary_uuid = dup.metrics[0]["uuid"]+ dup_secondary_uuid = dup.metrics_secondary[0]["uuid"]+ assert dup_primary_uuid != source_primary_uuid+ assert dup_secondary_uuid != source_secondary_uuid+ UUID(dup_primary_uuid)+ UUID(dup_secondary_uuid)+ # Ordering arrays should reference the new uuids, not the source ones.+ assert dup.primary_metrics_ordered_uuids == [dup_primary_uuid]+ assert dup.secondary_metrics_ordered_uuids == [dup_secondary_uuid]++ def test_dedup_regenerates_inline_uuids_that_collide_with_saved_metric_uuid(self):+ """When an inline metric reuses a saved-metric's uuid, dedup must regenerate+ the inline copy so each ordering entry resolves to exactly one thing.++ The saved-metric link is independent of the inline metrics array, but its+ uuid lives alongside inline-metric uuids in primary_metrics_ordered_uuids.+ An inline metric reusing the saved-metric uuid would make ordering ambiguous.+ """+ self._create_flag(key="dedup-with-saved")+ saved_metric_uuid = "33bfb66a-51f5-48d0-a87e-bde2b4c958a6"+ sm = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="SM with dup uuid",+ query={+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": saved_metric_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ )+ service = self._service()+ experiment = service.create_experiment(+ name="With Saved + Dup",+ feature_flag_key="dedup-with-saved",+ allow_unknown_events=True,+ saved_metrics_ids=[{"id": sm.id, "metadata": {"type": "primary"}}],+ )+ # Sanity: the saved-metric uuid is in the ordering.+ assert experiment.primary_metrics_ordered_uuids == [saved_metric_uuid]++ # Now the user sends an update with two inline metrics, both reusing the+ # saved-metric's uuid (the case where an LLM/frontend has inlined the+ # shared metric twice).+ updated = service.update_experiment(+ experiment,+ {+ "metrics": [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": saved_metric_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": saved_metric_uuid,+ "source": {"kind": "EventsNode", "event": "other_event"},+ },+ ],+ },+ allow_unknown_events=True,+ )+ # Both inline metrics get fresh uuids — neither shares the saved-metric uuid.+ assert updated.metrics is not None+ uuid_0 = updated.metrics[0]["uuid"]+ uuid_1 = updated.metrics[1]["uuid"]+ assert uuid_0 != saved_metric_uuid+ assert uuid_1 != saved_metric_uuid+ assert uuid_0 != uuid_1+ UUID(uuid_0)+ UUID(uuid_1)+ # The saved-metric uuid is still in ordering, plus both new inline uuids.+ assert updated.primary_metrics_ordered_uuids is not None+ assert saved_metric_uuid in updated.primary_metrics_ordered_uuids+ assert uuid_0 in updated.primary_metrics_ordered_uuids+ assert uuid_1 in updated.primary_metrics_ordered_uuids+ # The saved-metric link itself is untouched.+ assert list(updated.experimenttosavedmetric_set.values_list("saved_metric_id", flat=True)) == [sm.id]++ def test_create_regenerates_inline_uuid_that_collides_with_saved_metric_uuid(self):+ """Same protection on create: inline metric reusing a saved-metric uuid gets regenerated."""+ self._create_flag(key="create-dedup-with-saved")+ saved_metric_uuid = "55bfb66a-51f5-48d0-a87e-bde2b4c958a6"+ sm = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="SM",+ query={+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": saved_metric_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ )+ service = self._service()+ experiment = service.create_experiment(+ name="Create Dedup with Saved",+ feature_flag_key="create-dedup-with-saved",+ allow_unknown_events=True,+ saved_metrics_ids=[{"id": sm.id, "metadata": {"type": "primary"}}],+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": saved_metric_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ ],+ )+ assert experiment.metrics is not None+ inline_uuid = experiment.metrics[0]["uuid"]+ assert inline_uuid != saved_metric_uuid+ UUID(inline_uuid)+ assert experiment.primary_metrics_ordered_uuids is not None+ assert saved_metric_uuid in experiment.primary_metrics_ordered_uuids+ assert inline_uuid in experiment.primary_metrics_ordered_uuids++ def test_clone_regenerates_uuids_even_when_source_uuid_matches_saved_metric(self):+ """Cloning regenerates inline metric uuids so they no longer collide with the+ saved metric's uuid carried by the cloned saved-metric link."""+ self._create_flag(key="clone-saved-collision")+ saved_metric_uuid = "44bfb66a-51f5-48d0-a87e-bde2b4c958a6"+ sm = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="SM",+ query={+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": saved_metric_uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ )+ service = self._service()+ source = service.create_experiment(+ name="With Saved + Inline Same UUID",+ feature_flag_key="clone-saved-collision",+ allow_unknown_events=True,+ saved_metrics_ids=[{"id": sm.id, "metadata": {"type": "primary"}}],+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "other_event"},+ },+ ],+ )+ assert source.metrics is not None+ source_inline_uuid = source.metrics[0]["uuid"]++ dup = service.duplicate_experiment(source)++ # Clone's inline metric has a fresh uuid.+ assert dup.metrics is not None+ dup_inline_uuid = dup.metrics[0]["uuid"]+ assert dup_inline_uuid != source_inline_uuid+ UUID(dup_inline_uuid)+ # Saved metric uuid (carried via the link in the clone) must still be in ordering.+ assert dup.primary_metrics_ordered_uuids is not None+ assert saved_metric_uuid in dup.primary_metrics_ordered_uuids+ assert dup_inline_uuid in dup.primary_metrics_ordered_uuids+ # Cloned saved-metric link points to the same saved metric (same team).+ assert list(dup.experimenttosavedmetric_set.values_list("saved_metric_id", flat=True)) == [sm.id]+def _base_queryset(self):return Experiment.objects.filter(team=self.team)diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex eb394b75f515..eb7609a7ecec 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -3193,17 +3193,25 @@ class TestExperimentCRUD(APILicensedTest):self.assertEqual(duplicate_experiment["parameters"], original_experiment["parameters"])self.assertEqual(duplicate_experiment["filters"], original_experiment["filters"])- # Compare metrics ignoring fingerprints (they differ due to different start_dates)- def remove_fingerprints(metrics):- return [{k: v for k, v in metric.items() if k != "fingerprint"} for metric in metrics or []]+ # Compare metric content ignoring fingerprints (they differ due to different+ # start_dates) and uuids (regenerated by clone so the duplicate has its own+ # identity space — see _regenerate_all_metric_uuids).+ def strip_identity(metrics):+ return [{k: v for k, v in metric.items() if k not in ("fingerprint", "uuid")} for metric in metrics or []]self.assertEqual(- remove_fingerprints(duplicate_experiment["metrics"]), remove_fingerprints(original_experiment["metrics"])+ strip_identity(duplicate_experiment["metrics"]), strip_identity(original_experiment["metrics"]))self.assertEqual(- remove_fingerprints(duplicate_experiment["metrics_secondary"]),- remove_fingerprints(original_experiment["metrics_secondary"]),+ strip_identity(duplicate_experiment["metrics_secondary"]),+ strip_identity(original_experiment["metrics_secondary"]),)+ # Clone must regenerate every metric uuid.+ original_uuids = {m["uuid"] for m in original_experiment["metrics"] or []}+ duplicate_uuids = {m["uuid"] for m in duplicate_experiment["metrics"] or []}+ if original_uuids:+ self.assertTrue(original_uuids.isdisjoint(duplicate_uuids))+self.assertEqual(duplicate_experiment["stats_config"], original_experiment["stats_config"])self.assertEqual(duplicate_experiment["exposure_criteria"], original_experiment["exposure_criteria"])@@ -3340,14 +3348,19 @@ class TestExperimentCRUD(APILicensedTest):"feature_flag_variants": None,}- # Compare metrics ignoring fingerprints (they differ due to different start_dates)- def remove_fingerprints(metrics):- return [{k: v for k, v in metric.items() if k != "fingerprint"} for metric in metrics or []]+ # Compare metric content ignoring fingerprints (they differ due to different+ # start_dates) and uuids (regenerated by clone).+ def strip_identity(metrics):+ return [{k: v for k, v in metric.items() if k not in ("fingerprint", "uuid")} for metric in metrics or []]- assert remove_fingerprints(duplicate_data["metrics"]) == remove_fingerprints(original_experiment["metrics"])- assert remove_fingerprints(duplicate_data["metrics_secondary"]) == remove_fingerprints(+ assert strip_identity(duplicate_data["metrics"]) == strip_identity(original_experiment["metrics"])+ assert strip_identity(duplicate_data["metrics_secondary"]) == strip_identity(original_experiment["metrics_secondary"])+ original_uuids = {m["uuid"] for m in original_experiment["metrics"] or []}+ duplicate_uuids = {m["uuid"] for m in duplicate_data["metrics"] or []}+ if original_uuids:+ assert original_uuids.isdisjoint(duplicate_uuids)# Verify temporal fields are resetassert duplicate_data["start_date"] is None@@ -3533,16 +3546,20 @@ class TestExperimentCRUD(APILicensedTest):self.assertIsNone(copied_experiment["start_date"])self.assertIsNone(copied_experiment["end_date"])- def remove_fingerprints(metrics):- return [{k: v for k, v in metric.items() if k != "fingerprint"} for metric in metrics or []]+ # Compare metric content ignoring fingerprints and uuids (regenerated by clone).+ def strip_identity(metrics):+ return [{k: v for k, v in metric.items() if k not in ("fingerprint", "uuid")} for metric in metrics or []]+ self.assertEqual(strip_identity(copied_experiment["metrics"]), strip_identity(original_experiment["metrics"]))self.assertEqual(- remove_fingerprints(copied_experiment["metrics"]), remove_fingerprints(original_experiment["metrics"])- )- self.assertEqual(- remove_fingerprints(copied_experiment["metrics_secondary"]),- remove_fingerprints(original_experiment["metrics_secondary"]),+ strip_identity(copied_experiment["metrics_secondary"]),+ strip_identity(original_experiment["metrics_secondary"]),)+ original_uuids = {m["uuid"] for m in original_experiment["metrics"] or []}+ copied_uuids = {m["uuid"] for m in copied_experiment["metrics"] or []}+ if original_uuids:+ self.assertTrue(original_uuids.isdisjoint(copied_uuids))+self.assertEqual(copied_experiment["stats_config"], original_experiment["stats_config"])self.assertEqual(copied_experiment["exposure_criteria"], original_experiment["exposure_criteria"])