: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): track shared metrics metadata changes on the experiment activity log. (#58837)
Rodrigo Ilorocf5a143cda4f
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex a6ec3ce29d1a..dc03c954699a 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -90,6 +90,14 @@ ChangeAction = Literal["changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out", "copied"]+# Internal-only scope key. Used by `field_exclusions` and `changes_between` to address+# through-tables and other internal models that are never exposed as a top-level+# `scope` in stored activity logs. Keeping these out of `ActivityScope` prevents them+# from leaking into the generated `ActivityLogListScope` API enum, where filtering by+# them would always return zero results.+InternalActivityScope = Literal["ExperimentToSavedMetric",]+AuditableScope = Union[ActivityScope, InternalActivityScope]+@dataclasses.dataclass(frozen=True)class Change:@@ -219,7 +227,7 @@ common_field_exclusions = []-field_with_masked_contents: dict[ActivityScope, list[str]] = {+field_with_masked_contents: dict[AuditableScope, list[str]] = {"HogFunction": ["encrypted_inputs",],@@ -250,7 +258,7 @@ field_with_masked_contents: dict[ActivityScope, list[str]] = {],}-field_name_overrides: dict[ActivityScope, dict[str, str]] = {+field_name_overrides: dict[AuditableScope, dict[str, str]] = {"HogFunction": {"execution_order": "priority",},@@ -346,7 +354,7 @@ activity_visibility_restrictions: list[dict[str, Any]] = [},]-field_exclusions: dict[ActivityScope, list[str]] = {+field_exclusions: dict[AuditableScope, list[str]] = {"OrganizationDomain": ["organization","scim_provisioned_users",@@ -385,6 +393,10 @@ field_exclusions: dict[ActivityScope, list[str]] = {"experiments","experimenttosavedmetric_set",],+ "ExperimentToSavedMetric": [+ "experiment",+ "saved_metric",+ ],"ProjectSecretAPIKey": ["secure_value",],@@ -663,7 +675,7 @@ def safely_get_field_value(instance: models.Model | None, field: str):def changes_between(- model_type: ActivityScope,+ model_type: AuditableScope,previous: Optional[models.Model],current: Optional[models.Model],) -> list[Change]:@@ -731,7 +743,7 @@ def changes_between(def dict_changes_between(- model_type: ActivityScope,+ model_type: AuditableScope,previous: dict[Any, Any],new: dict[Any, Any],use_field_exclusions: bool = False,diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex e39312a8e8bd..da25dd0b2f5b 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -31,7 +31,11 @@ from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import Userfrom posthog.utils import get_ip_address, get_short_user_agent-from products.experiments.backend.models.experiment import ExperimentHoldout, ExperimentSavedMetric+from products.experiments.backend.models.experiment import (+ ExperimentHoldout,+ ExperimentSavedMetric,+ ExperimentToSavedMetric,+)logger = structlog.get_logger(__name__)@@ -367,3 +371,32 @@ def handle_experiment_holdout_delete(sender, instance, **kwargs):activity="deleted",detail=Detail(name=instance.name, type="holdout"),)+++@mutable_receiver(model_activity_signal, sender=ExperimentToSavedMetric)+def handle_experiment_to_saved_metric_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ instance = after_update or before_update+ if not instance:+ return++ log_activity(+ organization_id=instance.experiment.team.organization_id,+ team_id=instance.experiment.team_id,+ user=user or activity_storage.get_user(),+ was_impersonated=was_impersonated or activity_storage.get_was_impersonated(),+ item_id=instance.experiment_id,+ # Stored under the public Experiment scope so it shows up in the experiment+ # activity log feed. The describer arm on `type="saved_metric_config"`+ # renders the row.+ scope="Experiment",+ activity=activity,+ detail=Detail(+ # `"ExperimentToSavedMetric"` is an InternalActivityScope key used only for+ # field_exclusions / changes_between — never written to ActivityLog.scope.+ changes=changes_between("ExperimentToSavedMetric", previous=before_update, current=after_update),+ name=instance.saved_metric.name,+ type="saved_metric_config",+ ),+ )diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 71303b4b79e8..7b058d7f3383 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -700,6 +700,7 @@'__module__','__str__','_meta',+ 'activity_logging_on_delete','created_at','experiment_id','get_next_by_created_at',diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 35e54dcdbbe7..644da571d175 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -28,6 +28,7 @@ from posthog.models.cohort import Cohortfrom posthog.models.evaluation_context import FeatureFlagEvaluationContextfrom posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.filters.filter import Filter+from posthog.models.signals import mute_selected_signalsfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Teamfrom posthog.utils import str_to_bool@@ -2561,7 +2562,19 @@ class ExperimentService:old_saved_metric_uuids: dict[str, set[str]],saved_metrics_data: list[dict] | None,) -> None:- """Sync ordering arrays with saved metric changes during update."""+ """Sync ordering arrays with saved metric changes during update.++ When a saved metric is added or removed, the ordering arrays are kept in+ sync. The classification rule for the resulting write is:++ - If the user did not supply the ordering field, or supplied a value that+ equals what auto-sync would have produced, treat the write as bookkeeping+ and persist it via a muted ``experiment.save(update_fields=...)`` so only+ the add/remove appears in the activity log.+ - Otherwise the user layered an explicit reorder on top of the add/remove.+ Merge their order with the add/remove side effects and let the value flow+ through the normal ``experiment.save()`` so the reorder is logged.+ """if saved_metrics_data is None:return@@ -2591,29 +2604,63 @@ class ExperimentService:added_secondary = new_secondary_uuids - old_saved_metric_uuids["secondary"]removed_secondary = old_saved_metric_uuids["secondary"] - new_secondary_uuids- if added_primary or removed_primary:- if "primary_metrics_ordered_uuids" in update_data:- current_ordering = list(update_data["primary_metrics_ordered_uuids"] or [])+ # Fields whose new value is purely a side effect of add/remove — save these+ # via a muted save to avoid logging a spurious "reordered metrics" entry+ # alongside the add/remove entry.+ auto_synced_fields: list[str] = []++ def resolve_ordering(+ field: str,+ base_ordering: list[str],+ added: set[str],+ removed: set[str],+ ) -> None:+ auto_sync_result = [u for u in base_ordering if u not in removed]+ for uuid in added:+ if uuid not in auto_sync_result:+ auto_sync_result.append(uuid)++ user_supplied = field in update_data+ supplied_value = list(update_data.get(field) or []) if user_supplied else None++ if user_supplied and supplied_value != auto_sync_result:+ # Real user reorder layered on top of the add/remove. Fold in the+ # add/remove side effects so we don't lose newly-added UUIDs or+ # retain newly-removed ones, but keep the user's chosen order.+ merged = [u for u in supplied_value or [] if u not in removed]+ for uuid in added:+ if uuid not in merged:+ merged.append(uuid)+ update_data[field] = merged+ # leave it to flow through the normal save() — logged as reorderelse:- current_ordering = list(experiment.primary_metrics_ordered_uuids or [])+ update_data[field] = auto_sync_result+ auto_synced_fields.append(field)- current_ordering = [u for u in current_ordering if u not in removed_primary]- for uuid in added_primary:- if uuid not in current_ordering:- current_ordering.append(uuid)- update_data["primary_metrics_ordered_uuids"] = current_ordering+ if added_primary or removed_primary:+ resolve_ordering(+ "primary_metrics_ordered_uuids",+ list(experiment.primary_metrics_ordered_uuids or []),+ added_primary,+ removed_primary,+ )if added_secondary or removed_secondary:- if "secondary_metrics_ordered_uuids" in update_data:- current_ordering = list(update_data["secondary_metrics_ordered_uuids"] or [])- else:- current_ordering = list(experiment.secondary_metrics_ordered_uuids or [])+ resolve_ordering(+ "secondary_metrics_ordered_uuids",+ list(experiment.secondary_metrics_ordered_uuids or []),+ added_secondary,+ removed_secondary,+ )- current_ordering = [u for u in current_ordering if u not in removed_secondary]- for uuid in added_secondary:- if uuid not in current_ordering:- current_ordering.append(uuid)- update_data["secondary_metrics_ordered_uuids"] = current_ordering+ # Persist auto-synced ordering via a muted save so the add/remove of the+ # saved metric is the only activity log entry. The user-initiated reorder+ # path still flows through the normal save() at the end of update_experiment.+ if auto_synced_fields:+ for field in auto_synced_fields:+ setattr(experiment, field, update_data.pop(field))+ with mute_selected_signals():+ experiment.save(update_fields=[*auto_synced_fields, "updated_at"])def _validate_metric_ordering_on_update(self, experiment: Experiment, update_data: dict) -> None:"""Validate ordering arrays contain all metric UUIDs (update path)."""diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 3ac3124ed41d..79420060dafe 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -256,7 +256,9 @@ class ExperimentSavedMetric(ModelActivityMixin, RootTeamMixin, models.Model):db_table = "posthog_experimentsavedmetric"-class ExperimentToSavedMetric(models.Model):+class ExperimentToSavedMetric(ModelActivityMixin, models.Model):+ activity_logging_on_delete = True+experiment = models.ForeignKey("Experiment", on_delete=models.CASCADE)saved_metric = models.ForeignKey("ExperimentSavedMetric", on_delete=models.CASCADE)diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 79ef23204b53..eb394b75f515 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -5314,6 +5314,425 @@ class TestExperimentAuxiliaryEndpoints(ClickhouseTestMixin, APILicensedTest):# Verify the fix: the update activity log should NOT show the first userself.assertNotEqual(update_logs[0].user, self.user)+ def test_experiment_to_saved_metric_metadata_change_activity_logging(self):+ """Test that changes to ExperimentToSavedMetric metadata are logged under Experiment scope."""+ # Create a saved metric+ saved_metric_response = self.client.post(+ f"/api/projects/{self.team.id}/experiment_saved_metrics/",+ {+ "name": "Activity Test Metric",+ "description": "Testing metadata activity logging",+ "query": {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ },+ format="json",+ )+ self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)+ saved_metric_id = saved_metric_response.json()["id"]++ # Create experiment with saved metric including metadata+ experiment_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "Metadata Activity Test",+ "feature_flag_key": "metadata-activity-test",+ "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "primary"}}],+ },+ format="json",+ )+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)+ experiment_id = experiment_response.json()["id"]++ # Verify activity log was created for the saved metric config link+ created_logs = ActivityLog.objects.filter(+ scope="Experiment",+ item_id=str(experiment_id),+ activity="created",+ detail__type="saved_metric_config",+ )+ self.assertEqual(created_logs.count(), 1)+ self.assertEqual(created_logs[0].user, self.user)+ assert created_logs[0].detail is not None+ self.assertEqual(created_logs[0].detail["name"], "Activity Test Metric")++ # Update the metadata (add a breakdown)+ update_response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/",+ {+ "saved_metrics_ids": [+ {"id": saved_metric_id, "metadata": {"type": "primary", "breakdowns": [{"property": "country"}]}}+ ],+ },+ format="json",+ )+ self.assertEqual(update_response.status_code, status.HTTP_200_OK)++ # Verify an "updated" activity log was created with the metadata change+ updated_logs = ActivityLog.objects.filter(+ scope="Experiment",+ item_id=str(experiment_id),+ activity="updated",+ detail__type="saved_metric_config",+ )+ self.assertEqual(updated_logs.count(), 1)+ self.assertEqual(updated_logs[0].user, self.user)+ assert updated_logs[0].detail is not None+ self.assertEqual(updated_logs[0].detail["name"], "Activity Test Metric")++ # Verify the changes include the metadata field+ changes = updated_logs[0].detail.get("changes", [])+ metadata_change = next((c for c in changes if c.get("field") == "metadata"), None)+ assert metadata_change is not None+ self.assertEqual(metadata_change["before"], {"type": "primary"})+ self.assertEqual(metadata_change["after"], {"type": "primary", "breakdowns": [{"property": "country"}]})++ def test_saved_metric_add_remove_does_not_log_ordering_changes(self):+ """Adding/removing saved metrics should not create redundant ordering activity logs.++ When a saved metric is added or removed and the user did not supply an explicit+ ordering, the auto-synced ordering write is persisted via a muted+ ``experiment.save(update_fields=...)`` so the only log entry is the+ ``saved_metric_config`` add/remove.+ """+ # Create a saved metric+ saved_metric_response = self.client.post(+ f"/api/projects/{self.team.id}/experiment_saved_metrics/",+ {+ "name": "Ordering Test Metric",+ "query": {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "test-uuid-001",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ },+ format="json",+ )+ self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)+ saved_metric_id = saved_metric_response.json()["id"]++ # Create experiment without saved metrics+ experiment_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "Ordering Activity Test",+ "feature_flag_key": "ordering-activity-test",+ },+ format="json",+ )+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)+ experiment_id = experiment_response.json()["id"]++ # Count logs before adding saved metric+ logs_before_add = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()++ # Add a saved metric to the experiment+ update_response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/",+ {"saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "secondary"}}]},+ format="json",+ )+ self.assertEqual(update_response.status_code, status.HTTP_200_OK)++ # Verify ordering was updated in the database+ experiment = Experiment.objects.get(id=experiment_id)+ self.assertIn("test-uuid-001", experiment.secondary_metrics_ordered_uuids or [])++ # Exactly 1 new log should be created (the saved_metric_config, not ordering changes)+ logs_after_add = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()+ self.assertEqual(logs_after_add - logs_before_add, 1)++ # Verify the new log is for saved_metric_config, not ordering+ config_logs = ActivityLog.objects.filter(+ item_id=str(experiment_id),+ scope="Experiment",+ activity="created",+ detail__type="saved_metric_config",+ )+ self.assertEqual(config_logs.count(), 1)++ # Verify NO ordering change logs exist+ all_logs = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment")+ ordering_logs = [+ log+ for log in all_logs+ if log.detail+ and any(+ change.get("field") in ("primary_metrics_ordered_uuids", "secondary_metrics_ordered_uuids")+ for change in (log.detail.get("changes") or [])+ )+ ]+ self.assertEqual(len(ordering_logs), 0, "Ordering changes should not be logged")++ # Count logs before removing saved metric+ logs_before_remove = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()++ # Remove the saved metric+ remove_response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/",+ {"saved_metrics_ids": []},+ format="json",+ )+ self.assertEqual(remove_response.status_code, status.HTTP_200_OK)++ # Verify ordering was updated+ experiment.refresh_from_db()+ self.assertNotIn("test-uuid-001", experiment.secondary_metrics_ordered_uuids or [])++ # Exactly 1 new log should be created (the saved_metric_config deletion)+ logs_after_remove = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()+ self.assertEqual(logs_after_remove - logs_before_remove, 1)++ # Verify the new log is for saved_metric_config deletion+ delete_logs = ActivityLog.objects.filter(+ item_id=str(experiment_id),+ scope="Experiment",+ activity="deleted",+ detail__type="saved_metric_config",+ )+ self.assertEqual(delete_logs.count(), 1)++ def test_user_initiated_metric_reorder_is_logged(self):+ """A standalone reorder (no add/remove) must produce an activity log entry."""+ # Seed the experiment with two inline metrics so there is something to reorder+ experiment_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "allow_unknown_events": True,+ "name": "Reorder Activity Test",+ "feature_flag_key": "reorder-activity-test",+ "metrics": [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "reorder-uuid-a",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "reorder-uuid-b",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ ],+ "primary_metrics_ordered_uuids": ["reorder-uuid-a", "reorder-uuid-b"],+ },+ format="json",+ )+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)+ experiment_id = experiment_response.json()["id"]++ logs_before_reorder = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()++ reorder_response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/",+ {"primary_metrics_ordered_uuids": ["reorder-uuid-b", "reorder-uuid-a"]},+ format="json",+ )+ self.assertEqual(reorder_response.status_code, status.HTTP_200_OK)++ experiment = Experiment.objects.get(id=experiment_id)+ self.assertEqual(experiment.primary_metrics_ordered_uuids, ["reorder-uuid-b", "reorder-uuid-a"])++ logs_after_reorder = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()+ self.assertEqual(logs_after_reorder - logs_before_reorder, 1)++ reorder_log = (+ ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment", activity="updated")+ .order_by("-created_at")+ .first()+ )+ assert reorder_log is not None and reorder_log.detail is not None+ changes = reorder_log.detail.get("changes") or []+ ordering_change = next((c for c in changes if c.get("field") == "primary_metrics_ordered_uuids"), None)+ assert ordering_change is not None, "Explicit reorder must produce a primary_metrics_ordered_uuids change"+ self.assertEqual(ordering_change["before"], ["reorder-uuid-a", "reorder-uuid-b"])+ self.assertEqual(ordering_change["after"], ["reorder-uuid-b", "reorder-uuid-a"])++ def test_explicit_reorder_in_same_patch_as_saved_metric_add_is_logged(self):+ """If the user supplies ordering alongside an add/remove, the reorder must still be logged."""+ # Create a saved metric the experiment can later adopt+ saved_metric_response = self.client.post(+ f"/api/projects/{self.team.id}/experiment_saved_metrics/",+ {+ "name": "Combined PATCH Saved Metric",+ "query": {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "combined-saved-uuid",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ },+ format="json",+ )+ self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)+ saved_metric_id = saved_metric_response.json()["id"]++ # Start with one inline primary metric so we have an existing ordering to permute+ experiment_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "allow_unknown_events": True,+ "name": "Combined PATCH Activity Test",+ "feature_flag_key": "combined-patch-activity",+ "metrics": [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "combined-inline-uuid",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ ],+ "primary_metrics_ordered_uuids": ["combined-inline-uuid"],+ },+ format="json",+ )+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)+ experiment_id = experiment_response.json()["id"]++ logs_before = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()++ # Same PATCH: adds the saved metric AND explicitly reorders so the saved metric goes first.+ update_response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/",+ {+ "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "primary"}}],+ "primary_metrics_ordered_uuids": ["combined-saved-uuid", "combined-inline-uuid"],+ },+ format="json",+ )+ self.assertEqual(update_response.status_code, status.HTTP_200_OK)++ experiment = Experiment.objects.get(id=experiment_id)+ self.assertEqual(+ experiment.primary_metrics_ordered_uuids,+ ["combined-saved-uuid", "combined-inline-uuid"],+ )++ # Two new logs: the saved_metric_config add AND the experiment-level reorder.+ new_logs = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count() - logs_before+ self.assertEqual(new_logs, 2)++ # The saved metric add is captured+ config_logs = ActivityLog.objects.filter(+ item_id=str(experiment_id),+ scope="Experiment",+ activity="created",+ detail__type="saved_metric_config",+ )+ self.assertEqual(config_logs.count(), 1)++ # The user-supplied reorder is also captured in a separate Experiment update log+ reorder_logs = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment", activity="updated")+ ordering_changes = [+ change+ for log in reorder_logs+ if log.detail+ for change in (log.detail.get("changes") or [])+ if change.get("field") == "primary_metrics_ordered_uuids"+ ]+ self.assertEqual(len(ordering_changes), 1, "User-supplied reorder must be logged once")+ self.assertEqual(ordering_changes[0]["before"], ["combined-inline-uuid"])+ self.assertEqual(ordering_changes[0]["after"], ["combined-saved-uuid", "combined-inline-uuid"])++ @parameterized.expand(+ [+ ("primary", "primary_metrics_ordered_uuids", "secondary_metrics_ordered_uuids"),+ ("secondary", "secondary_metrics_ordered_uuids", "primary_metrics_ordered_uuids"),+ ]+ )+ def test_bulk_remove_shared_metrics_does_not_log_ordering_change(+ self, metric_type: str, ordering_field: str, other_ordering_field: str+ ):+ """Bulk-remove via the reorder dialog (saved_metrics_ids=[] + ordering=[]) must not log a reorder.++ The frontend sends the now-empty ordering array alongside the empty+ saved_metrics_ids on bulk remove. That mirrors auto-sync, so the ordering+ write is bookkeeping and must be muted. Only the per-link `saved_metric_config`+ deleted entries should appear.+ """+ saved_metric_uuids = ["bulk-remove-uuid-1", "bulk-remove-uuid-2"]+ saved_metric_ids: list[int] = []+ for index, uuid in enumerate(saved_metric_uuids):+ response = self.client.post(+ f"/api/projects/{self.team.id}/experiment_saved_metrics/",+ {+ "name": f"Bulk Remove Metric {index + 1}",+ "query": {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": uuid,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ saved_metric_ids.append(response.json()["id"])++ experiment_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "allow_unknown_events": True,+ "name": f"Bulk Remove Activity Test ({metric_type})",+ "feature_flag_key": f"bulk-remove-activity-{metric_type}",+ "saved_metrics_ids": [+ {"id": saved_metric_id, "metadata": {"type": metric_type}} for saved_metric_id in saved_metric_ids+ ],+ ordering_field: saved_metric_uuids,+ },+ format="json",+ )+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)+ experiment_id = experiment_response.json()["id"]++ logs_before = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()++ # Mirrors the curl payload from the reorder dialog: clear inline metrics,+ # clear the ordering array, and clear saved_metrics_ids in the same PATCH.+ inline_metrics_field = "metrics" if metric_type == "primary" else "metrics_secondary"+ remove_response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/",+ {+ inline_metrics_field: [],+ ordering_field: [],+ "saved_metrics_ids": [],+ },+ format="json",+ )+ self.assertEqual(remove_response.status_code, status.HTTP_200_OK)++ experiment = Experiment.objects.get(id=experiment_id)+ self.assertEqual(getattr(experiment, ordering_field) or [], [])++ # Two new logs expected: one saved_metric_config deleted per removed link.+ new_logs = list(+ ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").order_by("created_at")+ )+ added = new_logs[logs_before:]+ self.assertEqual(len(added), 2, "Two saved_metric_config deleted entries expected")+ for log in added:+ assert log.detail is not None+ self.assertEqual(log.activity, "deleted")+ self.assertEqual(log.detail["type"], "saved_metric_config")++ # No ordering change should be logged on any entry (existing or new).+ ordering_changes = [+ change+ for log in ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment")+ if log.detail+ for change in (log.detail.get("changes") or [])+ if change.get("field") in (ordering_field, other_ordering_field)+ ]+ self.assertEqual(+ ordering_changes,+ [],+ "Bulk-remove must not log a primary/secondary ordering change",+ )+def test_cannot_add_saved_metric_from_different_team(self):team_b = Team.objects.create(organization=self.organization, name="Team B")