: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): migrate a legacy experiment from the API and PostHog AI (#104391)
Anderscb2b20ec1e67
diff --git a/products/experiments/backend/admin/experiment_admin.py b/products/experiments/backend/admin/experiment_admin.pyindex 368831e29623..42a0b3baf508 100644--- a/products/experiments/backend/admin/experiment_admin.py+++ b/products/experiments/backend/admin/experiment_admin.py@@ -3,7 +3,6 @@ from uuid import UUIDfrom django.contrib import admin, messagesfrom django.core.exceptions import PermissionDenied-from django.db import transactionfrom django.forms import ModelFormfrom django.http import HttpRequest, HttpResponseRedirectfrom django.shortcuts import redirect@@ -11,20 +10,14 @@ from django.urls import path, reversefrom django.utils.html import format_htmlfrom posthog.models.organization import Organization-from posthog.models.utils import convert_legacy_metricsfrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.admin.recalculation_panel import (build_recalculation_panel,start_recalculation_for_experiment,)-from products.experiments.backend.models.experiment import (- Experiment,- ExperimentHoldout,- ExperimentMetricsRecalculation,- ExperimentSavedMetric,- ExperimentToSavedMetric,-)+from products.experiments.backend.legacy_migration import migrate_experiment as migrate_legacy_experiment+from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentMetricsRecalculationfrom products.experiments.backend.recalculation import get_latest_recalculationfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -347,74 +340,15 @@ class ExperimentAdmin(admin.ModelAdmin):def migrate_experiment(self, request, object_id):try:- with transaction.atomic():- original = Experiment.objects.select_for_update().get(pk=object_id)-- if original.stats_config and original.stats_config.get("migrated_to"):- messages.warning(request, f"Experiment already migrated to {original.stats_config['migrated_to']}")- return redirect("admin:experiments_experiment_change", original.stats_config["migrated_to"])-- new_experiment = Experiment()-- # copy all fields... almost all...- excluded_fields = ["id", "created_at", "key"]- for field in original._meta.fields:- if field.name not in excluded_fields:- value = getattr(original, field.name)- # Deep copy dicts to avoid shared references- if isinstance(value, dict):- value = copy.deepcopy(value)- setattr(new_experiment, field.name, value)-- # migrate metrics and secondary metrics- new_experiment.metrics = convert_legacy_metrics(original.metrics)- new_experiment.metrics_secondary = convert_legacy_metrics(original.metrics_secondary)-- # update the migrated from relation- if new_experiment.stats_config is None:- new_experiment.stats_config = {}- new_experiment.stats_config["migrated_from"] = int(object_id)-- # save the experiment, we need this for referential integrity- new_experiment.save()-- # find the shared metrics "migrated to" and create new relationships- # check if all saved metrics have been migrated- for metric in original.saved_metrics.all():- kind = metric.query.get("kind") if metric.query else None- is_legacy = kind in ("ExperimentFunnelsQuery", "ExperimentTrendsQuery")- migrated = bool(metric.metadata and "migrated_to" in metric.metadata)-- # bail with an exception if the metric is legacy and has not been migrated- if is_legacy and not migrated:- raise Exception(f"Saved metric {metric.id} has not been migrated yet")-- # because we need metadata from the through table, we can't just do- # experiment.saved_metrics.add. We need to create the relationship by hand- original_to_saved_metric = ExperimentToSavedMetric.objects.get(- experiment=original, saved_metric=metric- )-- # if is legacy, get the migrated metric, otherwise, keep the id from the original experiment- metric_id = metric.metadata["migrated_to"] if is_legacy else metric.id-- saved_metric = ExperimentSavedMetric.objects.get(id=metric_id)-- # Create the new through object with the same metadata- ExperimentToSavedMetric.objects.create(- experiment=new_experiment,- saved_metric=saved_metric,- metadata=copy.deepcopy(original_to_saved_metric.metadata),- )-- # update the migrated to soft relation- if original.stats_config is None:- original.stats_config = {}- original.stats_config["migrated_to"] = new_experiment.id- original.save(update_fields=["stats_config"])-- messages.success(request, "Experiment migrated successfully")- return redirect("admin:experiments_experiment_change", new_experiment.pk)+ # nosemgrep: idor-lookup-without-team (Django admin, staff-only)+ team_id = Experiment.objects.values_list("team_id", flat=True).get(pk=object_id)+ migration = migrate_legacy_experiment(int(object_id), team_id)++ if migration.already_migrated:+ messages.warning(request, f"Experiment already migrated to {migration.experiment.id}")+ else:+ messages.success(request, "Experiment migrated successfully")+ return redirect("admin:experiments_experiment_change", migration.experiment.pk)except Experiment.DoesNotExist:messages.error(request, "Experiment not found")return redirect("admin:experiments_experiment_changelist")diff --git a/products/experiments/backend/admin/experiment_saved_metric_admin.py b/products/experiments/backend/admin/experiment_saved_metric_admin.pyindex 19e8437092ac..b92fbe0f3db6 100644--- a/products/experiments/backend/admin/experiment_saved_metric_admin.py+++ b/products/experiments/backend/admin/experiment_saved_metric_admin.py@@ -1,11 +1,9 @@from django.contrib import admin, messages-from django.db import transactionfrom django.shortcuts import redirectfrom django.urls import path, reversefrom django.utils.html import format_html-from posthog.models.utils import convert_legacy_metric-+from products.experiments.backend.legacy_migration import migrate_saved_metricfrom products.experiments.backend.models.experiment import ExperimentSavedMetric@@ -81,27 +79,15 @@ class ExperimentSavedMetricAdmin(admin.ModelAdmin):def migrate_metric(self, request, object_id):try:- with transaction.atomic():- original = ExperimentSavedMetric.objects.select_for_update().get(pk=object_id)-- if original.metadata and original.metadata.get("migrated_to"):- messages.warning(request, f"Metric already migrated to {original.metadata['migrated_to']}")- return redirect("admin:experiments_experimentsavedmetric_change", original.metadata["migrated_to"])-- new_metric = ExperimentSavedMetric()- new_metric.name = original.name- new_metric.team = original.team- new_metric.created_by = original.created_by- new_metric.query = convert_legacy_metric(original.query)- new_metric.metadata = {"migrated_from": original.id}- new_metric.save()-- if original.metadata is None:- original.metadata = {}- original.metadata["migrated_to"] = new_metric.id- original.save(update_fields=["metadata"])+ # nosemgrep: idor-lookup-without-team (Django admin, staff-only)+ original = ExperimentSavedMetric.objects.only("metadata", "team_id").get(pk=object_id)+ already_migrated = bool((original.metadata or {}).get("migrated_to"))+ new_metric = migrate_saved_metric(int(object_id), original.team_id)- messages.success(request, "Metric migrated successfully")+ if already_migrated:+ messages.warning(request, f"Metric already migrated to {new_metric.id}")+ else:+ messages.success(request, "Metric migrated successfully")return redirect("admin:experiments_experimentsavedmetric_change", new_metric.pk)except ExperimentSavedMetric.DoesNotExist:messages.error(request, "Metric not found")diff --git a/products/experiments/backend/experiment_saved_metric_service.py b/products/experiments/backend/experiment_saved_metric_service.pyindex 34af4c833c8f..aef93df76c47 100644--- a/products/experiments/backend/experiment_saved_metric_service.py+++ b/products/experiments/backend/experiment_saved_metric_service.py@@ -83,7 +83,7 @@ class ExperimentSavedMetricService:description: str | None = None,) -> ExperimentSavedMetric:"""Create a saved metric with full business-logic validation."""- normalized_query = self._normalize_query_for_write(query)+ normalized_query = self.normalize_query_for_write(query)enforce_warehouse_metric_access([normalized_query], team=self.team, user=self.user)return ExperimentSavedMetric.objects.create(@@ -102,7 +102,7 @@ class ExperimentSavedMetricService:if "query" in update_data:existing_uuid = saved_metric.query.get("uuid") if saved_metric.query else None- update_data["query"] = self._normalize_query_for_write(update_data["query"], existing_uuid=existing_uuid)+ update_data["query"] = self.normalize_query_for_write(update_data["query"], existing_uuid=existing_uuid)enforce_warehouse_metric_access([update_data["query"]], team=self.team, user=self.user)for attr, value in update_data.items():@@ -124,7 +124,7 @@ class ExperimentSavedMetricService:raise ValidationError("Saved metric does not exist or does not belong to this project")@classmethod- def _normalize_query_for_write(cls, query: dict, *, existing_uuid: str | None = None) -> dict:+ def normalize_query_for_write(cls, query: dict, *, existing_uuid: str | None = None) -> dict:cls.validate_query(query)normalized_query = dict(query)diff --git a/products/experiments/backend/facade/legacy_migration.py b/products/experiments/backend/facade/legacy_migration.pynew file mode 100644index 000000000000..a4f92154563e--- /dev/null+++ b/products/experiments/backend/facade/legacy_migration.py@@ -0,0 +1,8 @@+"""Legacy migration capability, re-exported for callers outside the experiments internals."""++from products.experiments.backend.legacy_migration import LegacyMigrationError, migrate_experiment++__all__ = [+ "LegacyMigrationError",+ "migrate_experiment",+]diff --git a/products/experiments/backend/legacy_migration.py b/products/experiments/backend/legacy_migration.pynew file mode 100644index 000000000000..c9c41c0058b7--- /dev/null+++ b/products/experiments/backend/legacy_migration.py@@ -0,0 +1,209 @@+import copy+from uuid import uuid4++from django.db import transaction++from posthog.dataclasses import frozen+from posthog.models.utils import convert_legacy_metric, convert_legacy_metrics++from products.experiments.backend.experiment_saved_metric_service import ExperimentSavedMetricService+from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentSavedMetric,+ ExperimentToSavedMetric,+ saved_metric_has_legacy_query,+)++# The copy carries everything except identity and creation time, so the new experiment keeps the+# original's feature flag, name, dates and results window. The rules v2 link and its snapshot+# belong to the source flag's rule, and the rule id is globally unique, so a copy starts unlinked.+_NOT_COPIED_FIELDS = ("id", "created_at", "key", "feature_flag_rule_id", "feature_flag_rule_snapshot")+++class LegacyMigrationError(Exception):+ """Raised with a message meant for the person who asked for the migration."""+++@frozen+class ExperimentMigration:+ experiment: Experiment+ already_migrated: bool+ migrated_saved_metric_ids: list[int]+++def migrate_saved_metric(saved_metric_id: int, team_id: int) -> ExperimentSavedMetric:+ """Create a new-engine copy of a legacy shared metric, or return the copy made earlier."""+ with transaction.atomic():+ original = ExperimentSavedMetric.objects.select_for_update().get(pk=saved_metric_id, team_id=team_id)++ if existing := _migrated_target(original, team_id):+ return existing++ new_metric = ExperimentSavedMetric.objects.create(+ name=original.name,+ team=original.team,+ created_by=original.created_by,+ # Through the service, so the new query gets the uuid every new-engine metric needs.+ query=ExperimentSavedMetricService.normalize_query_for_write(convert_legacy_metric(original.query)),+ metadata={"migrated_from": original.id},+ )++ original.metadata = {**(original.metadata or {}), "migrated_to": new_metric.id}+ original.save(update_fields=["metadata"])++ return new_metric+++def migrate_experiment(+ experiment_id: int, team_id: int, *, migrate_shared_metrics: bool = False+) -> ExperimentMigration:+ """Create a new-engine copy of a legacy experiment, or return the copy made earlier.++ The original is left untouched and keeps its results. Both experiments point at the same+ feature flag, so the copy needs no new rollout.++ Legacy shared metrics have to be migrated too. With migrate_shared_metrics they are migrated+ as part of this call; without it, an unmigrated one raises LegacyMigrationError.+ """+ with transaction.atomic():+ original = Experiment.objects.select_for_update().get(pk=experiment_id, team_id=team_id)++ migrated_to = (original.stats_config or {}).get("migrated_to")+ existing = Experiment.objects.filter(pk=migrated_to, team_id=team_id).first() if migrated_to else None+ if existing:+ return ExperimentMigration(+ experiment=existing,+ already_migrated=True,+ migrated_saved_metric_ids=[],+ )++ saved_metric_targets, migrated_saved_metric_ids = _resolve_saved_metrics(+ original, team_id, migrate_shared_metrics=migrate_shared_metrics+ )++ new_experiment = Experiment()+ for field in original._meta.fields:+ if field.name in _NOT_COPIED_FIELDS:+ continue+ value = getattr(original, field.name)+ # Deep copy dicts to avoid shared references+ if isinstance(value, dict):+ value = copy.deepcopy(value)+ setattr(new_experiment, field.name, value)++ new_experiment.stats_config = {**(new_experiment.stats_config or {}), "migrated_from": original.id}+ new_experiment.metrics = _prepare_metrics(convert_legacy_metrics(original.metrics), new_experiment)+ new_experiment.metrics_secondary = _prepare_metrics(+ convert_legacy_metrics(original.metrics_secondary), new_experiment+ )+ _set_metric_ordering(new_experiment, saved_metric_targets)+ new_experiment.save()++ for link, target in saved_metric_targets:+ # The through row carries metadata, so the link is created by hand rather than+ # through experiment.saved_metrics.add.+ ExperimentToSavedMetric.objects.create(+ experiment=new_experiment,+ saved_metric=target,+ metadata=copy.deepcopy(link.metadata),+ )++ original.stats_config = {**(original.stats_config or {}), "migrated_to": new_experiment.id}+ original.save(update_fields=["stats_config"])++ return ExperimentMigration(+ experiment=new_experiment,+ already_migrated=False,+ migrated_saved_metric_ids=migrated_saved_metric_ids,+ )+++def _resolve_saved_metrics(+ original: Experiment, team_id: int, *, migrate_shared_metrics: bool+) -> tuple[list[tuple[ExperimentToSavedMetric, ExperimentSavedMetric]], list[int]]:+ """Pick the shared metric each link should point at, migrating legacy ones when allowed."""+ # Ordered, because the links are what puts the shared metrics in order on the experiment.+ links = list(+ ExperimentToSavedMetric.objects.filter(experiment=original).select_related("saved_metric").order_by("id")+ )+ already_migrated: dict[int, ExperimentSavedMetric] = {}+ blocked_by_id: dict[int, ExperimentSavedMetric] = {}+ for link in links:+ metric = link.saved_metric+ if not saved_metric_has_legacy_query(metric):+ continue+ if target := _migrated_target(metric, team_id):+ already_migrated[metric.id] = target+ else:+ blocked_by_id[metric.id] = metric+ blocked = list(blocked_by_id.values())++ if blocked and not migrate_shared_metrics:+ names = ", ".join(f'"{metric.name}" (id {metric.id})' for metric in blocked)+ raise LegacyMigrationError(f"Migrate these shared metrics first, then migrate the experiment: {names}")++ # In id order, so two experiments sharing these metrics can't migrate into a deadlock.+ replacements = {+ metric.id: migrate_saved_metric(metric.id, team_id) for metric in sorted(blocked, key=lambda metric: metric.id)+ }+ migrated_ids = [metric.id for metric in replacements.values()]++ targets = [(link, _target_metric(link.saved_metric, {**already_migrated, **replacements})) for link in links]+ return targets, migrated_ids+++def _target_metric(metric: ExperimentSavedMetric, targets: dict[int, ExperimentSavedMetric]) -> ExperimentSavedMetric:+ if not saved_metric_has_legacy_query(metric):+ return metric+ return targets[metric.id]+++def _migrated_target(metric: ExperimentSavedMetric, team_id: int) -> ExperimentSavedMetric | None:+ """The new-engine copy this legacy shared metric already has, if it still exists.++ The pointer outlives a hard delete of its target, so a stale one counts as unmigrated and the+ metric is migrated again. Reading it as a live id instead blocks every later migration.+ """+ migrated_to = (metric.metadata or {}).get("migrated_to")+ if not migrated_to:+ return None+ return ExperimentSavedMetric.objects.filter(pk=migrated_to, team_id=team_id).first()+++def _prepare_metrics(metrics: list[dict], experiment: Experiment) -> list[dict]:+ """Give each converted metric the uuid and fingerprint the new engine writes on create.++ The conversion drops the legacy uuid and never had a fingerprint. Without a uuid the metric+ cannot enter the ordering arrays, and the UI renders only what those arrays list, so an+ experiment migrated without one shows no metrics at all.+ """+ stats_method = (experiment.stats_config or {}).get("method", "bayesian")+ for metric in metrics:+ metric["uuid"] = str(uuid4())+ metric["fingerprint"] = compute_metric_fingerprint(+ metric,+ experiment.start_date,+ stats_method,+ experiment.exposure_criteria,+ only_count_matured_users=experiment.only_count_matured_users,+ excluded_variants=experiment.excluded_variants,+ )+ return metrics+++def _set_metric_ordering(+ experiment: Experiment, saved_metric_targets: list[tuple[ExperimentToSavedMetric, ExperimentSavedMetric]]+) -> None:+ """Fill the ordering arrays the new engine reads metrics through, inline metrics first."""+ ordering: dict[str, list[str]] = {+ "primary": [metric["uuid"] for metric in experiment.metrics or []],+ "secondary": [metric["uuid"] for metric in experiment.metrics_secondary or []],+ }+ for link, target in saved_metric_targets:+ if uuid := (target.query or {}).get("uuid"):+ metric_type = (link.metadata or {}).get("type", "primary")+ ordering["primary" if metric_type == "primary" else "secondary"].append(uuid)++ experiment.primary_metrics_ordered_uuids = ordering["primary"]+ experiment.secondary_metrics_ordered_uuids = ordering["secondary"]diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex bdc2ee1c6d7f..db20cf1915fe 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -68,6 +68,10 @@ from products.access_control.backend.facade.user_access_control import (from products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom products.approvals.backend.mixins import ApprovalHandlingMixinfrom products.experiments.backend.experiment_service import ExperimentService, ExperimentVersionConflict+from products.experiments.backend.facade.legacy_migration import (+ LegacyMigrationError,+ migrate_experiment as migrate_legacy_experiment,+)from products.experiments.backend.facade.replay import resolve_in_session_exposure_semanticsfrom products.experiments.backend.llm_metric_templates import build_template, list_templates@@ -1039,6 +1043,43 @@ class EnterpriseExperimentsViewSet(ExperimentSerializer(duplicate_experiment, context=self.get_serializer_context()).data, status=201)+ @extend_schema(+ request=None,+ responses=ExperimentSerializer,+ )+ @action(methods=["POST"], detail=True, required_scopes=["experiment:write"])+ def migrate(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """+ Move a legacy experiment onto the new experiments engine.++ Creates a new experiment with the same configuration and its metrics converted+ to the new format, and returns it. The legacy experiment is left untouched and+ keeps its results, so the project ends up with two experiments. Both point at+ the same feature flag, so no new rollout is needed and users keep the variant+ they already have.++ Legacy shared metrics used by the experiment are converted as part of the same+ call. Each one gets a new shared metric, and the new experiment links to that.++ Calling this again returns the experiment created the first time instead of+ making another copy.++ Returns 400 if the experiment already uses the new engine.+ """+ experiment: Experiment = self.get_object()++ if not experiment_has_legacy_metrics(experiment):+ raise ValidationError(+ "This experiment already uses the new experiments engine, so there is nothing to migrate."+ )++ try:+ migration = migrate_legacy_experiment(experiment.id, self.team.id, migrate_shared_metrics=True)+ except (LegacyMigrationError, ValueError) as e:+ raise ValidationError(f"Couldn't migrate this experiment: {e}. Contact support if it keeps happening.")++ return Response(ExperimentSerializer(migration.experiment, context=self.get_serializer_context()).data)+@extend_schema(request=CreateFromPromptInputSerializer,responses=ExperimentSerializer,diff --git a/products/experiments/backend/test/test_experiment_admin.py b/products/experiments/backend/test/test_experiment_admin.pyindex e0b8b4f59756..39ada5762af3 100644--- a/products/experiments/backend/test/test_experiment_admin.py+++ b/products/experiments/backend/test/test_experiment_admin.py@@ -79,3 +79,27 @@ class TestExperimentAdmin(BaseTest):if run is not None:assert run.trigger == ExperimentMetricsRecalculation.Trigger.MANUALassert str(run.pk) in response.url++ def test_migrate_experiment_view_creates_a_new_engine_copy(self) -> None:+ Experiment.objects.filter(pk=self.draft.pk).update(+ metrics=[+ {+ "kind": "ExperimentTrendsQuery",+ "count_query": {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},+ }+ ]+ )+ request = RequestFactory().post("/")+ request.user = self.user+ request.session = SessionStore()+ request._messages = FallbackStorage(request) # type: ignore[attr-defined]++ response = self.model_admin.migrate_experiment(request, str(self.draft.pk))++ self.draft.refresh_from_db()+ assert self.draft.stats_config is not None+ migrated_to = self.draft.stats_config["migrated_to"]+ assert str(migrated_to) in response.url+ migrated_metrics = Experiment.objects.get(pk=migrated_to).metrics+ assert migrated_metrics is not None+ assert migrated_metrics[0]["kind"] == "ExperimentMetric"diff --git a/products/experiments/backend/test/test_legacy_migration.py b/products/experiments/backend/test/test_legacy_migration.pynew file mode 100644index 000000000000..3357e9c7ef81--- /dev/null+++ b/products/experiments/backend/test/test_legacy_migration.py@@ -0,0 +1,123 @@+from uuid import uuid4++from rest_framework import status++from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric+from products.feature_flags.backend.models.feature_flag import FeatureFlag++from ee.api.test.base import APILicensedTest++LEGACY_TRENDS_METRIC = {+ "kind": "ExperimentTrendsQuery",+ "count_query": {"series": [{"kind": "EventsNode", "event": "$pageview"}]},+}+LEGACY_FUNNEL_QUERY = {+ "kind": "ExperimentFunnelsQuery",+ "funnels_query": {"series": [{"kind": "EventsNode", "event": "signed_up", "name": "x"}]},+}+++class TestExperimentMigrateEndpoint(APILicensedTest):+ def setUp(self) -> None:+ super().setUp()+ self.experiment = Experiment.objects.create(+ team=self.team,+ name="Legacy experiment",+ created_by=self.user,+ feature_flag=FeatureFlag.objects.create(team=self.team, key="legacy-flag", created_by=self.user),+ metrics=[LEGACY_TRENDS_METRIC],+ )+ self.shared_metric = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="Legacy shared metric",+ created_by=self.user,+ query=LEGACY_FUNNEL_QUERY,+ )+ ExperimentToSavedMetric.objects.create(+ experiment=self.experiment, saved_metric=self.shared_metric, metadata={"type": "secondary"}+ )++ def _migrate(self):+ return self.client.post(f"/api/projects/{self.team.id}/experiments/{self.experiment.id}/migrate")++ def test_migrates_the_experiment_and_its_legacy_shared_metric(self) -> None:+ response = self._migrate()+ assert response.status_code == status.HTTP_200_OK, response.json()++ migrated = Experiment.objects.get(pk=response.json()["id"])+ assert migrated.id != self.experiment.id+ assert migrated.metrics is not None+ [migrated_metric] = migrated.metrics+ assert migrated_metric["kind"] == "ExperimentMetric"+ assert migrated_metric["metric_type"] == "mean"+ assert migrated_metric["source"] == {"kind": "EventsNode", "event": "$pageview"}+ assert migrated.feature_flag_id == self.experiment.feature_flag_id++ self.experiment.refresh_from_db()+ assert self.experiment.stats_config is not None+ assert migrated.stats_config is not None+ assert self.experiment.stats_config["migrated_to"] == migrated.id+ assert migrated.stats_config["migrated_from"] == self.experiment.id++ link = ExperimentToSavedMetric.objects.get(experiment=migrated)+ assert link.metadata == {"type": "secondary"}+ assert link.saved_metric_id != self.shared_metric.id+ assert link.saved_metric.query["kind"] == "ExperimentMetric"++ self.shared_metric.refresh_from_db()+ assert self.shared_metric.metadata is not None+ assert self.shared_metric.metadata["migrated_to"] == link.saved_metric_id++ def test_migrated_metrics_are_reachable_through_the_ordering_arrays(self) -> None:+ # The UI renders only what the ordering arrays list, so a metric missing from them is invisible.+ migrated = Experiment.objects.get(pk=self._migrate().json()["id"])+ link = ExperimentToSavedMetric.objects.get(experiment=migrated)++ assert migrated.metrics is not None+ assert migrated.primary_metrics_ordered_uuids == [migrated.metrics[0]["uuid"]]+ assert migrated.secondary_metrics_ordered_uuids == [link.saved_metric.query["uuid"]]+ assert migrated.metrics[0]["fingerprint"]++ def test_the_copy_starts_unlinked_from_the_source_flag_rule(self) -> None:+ rule_id = uuid4()+ Experiment.objects.filter(pk=self.experiment.pk).update(+ feature_flag_rule_id=rule_id, feature_flag_rule_snapshot={"variants": []}+ )++ migrated = Experiment.objects.get(pk=self._migrate().json()["id"])++ assert migrated.feature_flag_rule_id is None+ assert migrated.feature_flag_rule_snapshot is None++ def test_migrates_again_when_the_earlier_copy_was_deleted(self) -> None:+ first = Experiment.objects.get(pk=self._migrate().json()["id"])+ first_id = first.id+ ExperimentSavedMetric.objects.get(+ pk=ExperimentToSavedMetric.objects.get(experiment=first).saved_metric_id+ ).delete()+ first.delete()++ response = self._migrate()++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["id"] != first_id+ second = Experiment.objects.get(pk=response.json()["id"])+ assert ExperimentToSavedMetric.objects.get(experiment=second).saved_metric.query["kind"] == "ExperimentMetric"++ def test_migrating_twice_returns_the_first_copy(self) -> None:+ first = self._migrate().json()["id"]+ second = self._migrate()++ assert second.status_code == status.HTTP_200_OK+ assert second.json()["id"] == first+ assert Experiment.objects.filter(team=self.team).count() == 2+ assert ExperimentSavedMetric.objects.filter(team=self.team).count() == 2++ def test_rejects_an_experiment_that_is_already_on_the_new_engine(self) -> None:+ Experiment.objects.filter(pk=self.experiment.pk).update(metrics=[])+ ExperimentToSavedMetric.objects.filter(experiment=self.experiment).delete()++ response = self._migrate()++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert Experiment.objects.filter(team=self.team).count() == 1diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex dda92bc6d4ab..8858c0c0511b 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -817,6 +817,38 @@ export const experimentsMetricsRecalculationLatestRetrieve = async ()}+export const getExperimentsMigrateCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/migrate/`+}++/**+ * Move a legacy experiment onto the new experiments engine.+ *+ * Creates a new experiment with the same configuration and its metrics converted+ * to the new format, and returns it. The legacy experiment is left untouched and+ * keeps its results, so the project ends up with two experiments. Both point at+ * the same feature flag, so no new rollout is needed and users keep the variant+ * they already have.+ *+ * Legacy shared metrics used by the experiment are converted as part of the same+ * call. Each one gets a new shared metric, and the new experiment links to that.+ *+ * Calling this again returns the experiment created the first time instead of+ * making another copy.+ *+ * Returns 400 if the experiment already uses the new engine.+ */+export const experimentsMigrateCreate = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<ExperimentApi> => {+ return apiMutator<ExperimentApi>(getExperimentsMigrateCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getExperimentsPauseCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/experiments/${id}/pause/`}diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 5b62f1aada12..0da5aca659fd 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -925,6 +925,49 @@ tools:- results.*.result.query_status- results.*.result.stats_version- results.*.result.insight+ experiment-migrate:+ operation: experiments_migrate_create+ enabled: true+ scopes:+ - experiment:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ enrich_url: '{id}'+ title: Migrate legacy experiment+ description: >+ Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the+ user's reference first. Only for experiments where is_legacy is true.+++ Move a legacy experiment onto the new experiments engine. This creates a NEW experiment with the same+ configuration and its metrics converted to the new format, and returns it. The legacy experiment is left+ untouched and keeps its results, so the project ends up with two experiments. Both point at the same feature+ flag, so no new rollout is needed and users keep the variant they already have. Tell the user about the+ second experiment before you call this.+++ Legacy shared metrics used by the experiment are converted too. Each one gets a new shared metric, and the+ new experiment links to that. The legacy shared metrics stay where they are.+++ Calling this again returns the experiment created the first time instead of making another copy.+++ Returns 400 if the experiment already uses the new engine.+++ No request body needed.+ param_overrides:+ id:+ cast: string-int+ aliases:+ - experimentId+ - experiment_id+ ui_app: experiment+ feature_flag: experiment-migrate-mcp-tool+ feature_flag_behavior: enableexperiment-pause:operation: experiments_pause_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1114a43180a2..256e028b1013 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4550,6 +4550,22 @@"readOnlyHint": true}},+ "experiment-migrate": {+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Only for experiments where is_legacy is true.\n\nMove a legacy experiment onto the new experiments engine. This creates a NEW experiment with the same configuration and its metrics converted to the new format, and returns it. The legacy experiment is left untouched and keeps its results, so the project ends up with two experiments. Both point at the same feature flag, so no new rollout is needed and users keep the variant they already have. Tell the user about the second experiment before you call this.\n\nLegacy shared metrics used by the experiment are converted too. Each one gets a new shared metric, and the new experiment links to that. The legacy shared metrics stay where they are.\n\nCalling this again returns the experiment created the first time instead of making another copy.\n\nReturns 400 if the experiment already uses the new engine.\n\nNo request body needed.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Migrate legacy experiment",+ "title": "Migrate legacy experiment",+ "required_scopes": ["experiment:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "experiment-migrate-mcp-tool",+ "feature_flag_behavior": "enable"+ },"experiment-pause": {"description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nPause a running experiment by deactivating its feature flag (sets flag active=false). The flag is no longer returned by the /decide endpoint, so users fall back to the application default (typically control). No new exposure events are recorded while paused. The experiment stays in running status — it is not ended.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), already stopped (\"Experiment has already ended.\"), no linked flag (\"Experiment does not have a feature flag linked.\"), or already paused (\"Experiment is already paused.\").\n\nNo request body needed. Use resume to reactivate.","category": "Experiments",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex b348b7d0925b..4eecef330d7c 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4635,6 +4635,22 @@"readOnlyHint": true}},+ "experiment-migrate": {+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Only for experiments where is_legacy is true.\n\nMove a legacy experiment onto the new experiments engine. This creates a NEW experiment with the same configuration and its metrics converted to the new format, and returns it. The legacy experiment is left untouched and keeps its results, so the project ends up with two experiments. Both point at the same feature flag, so no new rollout is needed and users keep the variant they already have. Tell the user about the second experiment before you call this.\n\nLegacy shared metrics used by the experiment are converted too. Each one gets a new shared metric, and the new experiment links to that. The legacy shared metrics stay where they are.\n\nCalling this again returns the experiment created the first time instead of making another copy.\n\nReturns 400 if the experiment already uses the new engine.\n\nNo request body needed.",+ "category": "Experiments",+ "feature": "experiments",+ "summary": "Migrate legacy experiment",+ "title": "Migrate legacy experiment",+ "required_scopes": ["experiment:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "experiment-migrate-mcp-tool",+ "feature_flag_behavior": "enable"+ },"experiment-pause": {"description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nPause a running experiment by deactivating its feature flag (sets flag active=false). The flag is no longer returned by the /decide endpoint, so users fall back to the application default (typically control). No new exposure events are recorded while paused. The experiment stays in running status — it is not ended.\n\nReturns 400 if: experiment is in draft (\"Experiment has not been launched yet.\"), already stopped (\"Experiment has already ended.\"), no linked flag (\"Experiment does not have a feature flag linked.\"), or already paused (\"Experiment is already paused.\").\n\nNo request body needed. Use resume to reactivate.","category": "Experiments",diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 262251aad056..1026f265d5b9 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 40 enabled ops+ * PostHog API - MCP 41 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -18848,6 +18848,32 @@ export const ExperimentsMetricsRecalculationLatestRetrieveParams = () => zod.obj),})+/**+ * Move a legacy experiment onto the new experiments engine.+ *+ * Creates a new experiment with the same configuration and its metrics converted+ * to the new format, and returns it. The legacy experiment is left untouched and+ * keeps its results, so the project ends up with two experiments. Both point at+ * the same feature flag, so no new rollout is needed and users keep the variant+ * they already have.+ *+ * Legacy shared metrics used by the experiment are converted as part of the same+ * call. Each one gets a new shared metric, and the new experiment links to that.+ *+ * Calling this again returns the experiment created the first time instead of+ * making another copy.+ *+ * Returns 400 if the experiment already uses the new engine.+ */+export const ExperimentsMigrateCreateParams = () => zod.object({+ id: zod.number().describe('A unique integer value identifying this experiment.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})+/*** Pause a running experiment.*diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.tsindex e29bed41a092..d4242855c4da 100644--- a/services/mcp/src/lib/instructions.ts+++ b/services/mcp/src/lib/instructions.ts@@ -242,6 +242,7 @@ export class ToolDomainExtractor {'end','freeze','launch',+ 'migrate','move','patch','pause',diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex afb9ca1dfb5d..09a3b20d5318 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -935,6 +935,33 @@ const experimentMetricsRecalculationRetrieve = (): ToolBase<},})+const ExperimentMigrateSchema = () => {+ const ExperimentsMigrateCreateParams = orvalSchemas.ExperimentsMigrateCreateParams()+ return z.preprocess(+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),+ ExperimentsMigrateCreateParams.omit({ project_id: true }).extend({+ id: z.preprocess(castStringToInt, ExperimentsMigrateCreateParams.shape['id']),+ })+ )+}++const experimentMigrate = (): ToolBase<+ ReturnType<typeof ExperimentMigrateSchema>,+ WithPostHogUrl<Schemas.Experiment>+> =>+ withUiApp('experiment', {+ name: 'experiment-migrate',+ schema: ExperimentMigrateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof ExperimentMigrateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.Experiment>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/migrate/`,+ })+ return await withPostHogUrl(context, result, `/experiments/${result.id}`)+ },+ })+const ExperimentPauseSchema = () => {const ExperimentsPauseCreateParams = orvalSchemas.ExperimentsPauseCreateParams()return z.preprocess(@@ -1611,6 +1638,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'experiment-metrics-recalculation-create': experimentMetricsRecalculationCreate,'experiment-metrics-recalculation-latest-retrieve': experimentMetricsRecalculationLatestRetrieve,'experiment-metrics-recalculation-retrieve': experimentMetricsRecalculationRetrieve,+ 'experiment-migrate': experimentMigrate,'experiment-pause': experimentPause,'experiment-prompt-templates': experimentPromptTemplates,'experiment-reset': experimentReset,diff --git a/services/mcp/tests/fixtures/experiment-id-tools.ts b/services/mcp/tests/fixtures/experiment-id-tools.tsindex 1aea38a5d4e1..fadfaef9515d 100644--- a/services/mcp/tests/fixtures/experiment-id-tools.ts+++ b/services/mcp/tests/fixtures/experiment-id-tools.ts@@ -21,6 +21,7 @@ export const EXPERIMENT_ID_TOOLS = [['experiment-metrics-recalculation-create', {}],['experiment-metrics-recalculation-latest-retrieve', {}],['experiment-metrics-recalculation-retrieve', { recalculation_id: '0199a1c0-0000-7000-8000-000000000000' }],+ ['experiment-migrate', {}],['experiment-pause', {}],['experiment-reset', {}],['experiment-resume', {}],diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.tsindex bad0c0268a32..eb06d8062ed3 100644--- a/services/mcp/tests/unit/instructions.test.ts+++ b/services/mcp/tests/unit/instructions.test.ts@@ -167,6 +167,7 @@ describe('buildToolDomainsBlock', () => {'end','freeze','launch',+ 'migrate','move','patch','pause',diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 544a63d14567..d2143a1718d5 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1007,6 +1007,7 @@ describe('Tool Filtering - Feature Flags', () => {'streamlit-apps','posthog-connect','experiment-behavior-comparison',+ 'experiment-migrate-mcp-tool','experiment-setup-context','data-warehouse-scene','data-quality-checks',@@ -1014,7 +1015,7 @@ describe('Tool Filtering - Feature Flags', () => {'warehouse-multi-destination',]))- expect(flags).toHaveLength(36)+ expect(flags).toHaveLength(37)})it('every loops tool is gated on the loops flag', () => {