Skip to content

: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.

fix(experiments): stop syncing metric ordering on every write (#107213)

Andersc5f0415c5a46
diff --git a/ee/clickhouse/views/test/test_experiment_saved_metrics.py b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
index cf1ef70e4a42..6cc6a0998b82 100644
--- a/ee/clickhouse/views/test/test_experiment_saved_metrics.py
+++ b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
@@ -216,7 +216,6 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
self.assertEqual(response.json()["feature_flag_key"], ff_key)
self.assertEqual(Experiment.objects.get(pk=exp_id).saved_metrics.count(), 1)
- self.assertEqual(Experiment.objects.get(pk=exp_id).secondary_metrics_ordered_uuids, [saved_metric_uuid])
experiment_to_saved_metric = Experiment.objects.get(pk=exp_id).experimenttosavedmetric_set.first()
assert experiment_to_saved_metric is not None
self.assertEqual(experiment_to_saved_metric.metadata, {"type": "secondary"})
@@ -355,7 +354,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["results"][0]["linked_experiments"], [])
- def test_create_saved_metric_without_uuid_added_to_experiment_is_ordered(self) -> None:
+ def test_create_saved_metric_without_uuid_gets_one_and_can_be_attached(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/experiment_saved_metrics/",
data={
@@ -386,7 +385,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
)
self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)
- self.assertIn(saved_metric_uuid, experiment_response.json()["primary_metrics_ordered_uuids"])
+ self.assertEqual(Experiment.objects.get(pk=experiment_response.json()["id"]).saved_metrics.count(), 1)
def test_update_saved_metric_tags(self) -> None:
response = self.client.post(
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
index bcaa977b7898..da5ad7d0db53 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
@@ -26,7 +26,6 @@ import { modalsLogic } from '../modalsLogic'
import {
getFlagVariants,
getOrderedMetricsWithResults,
- initializeMetricOrdering,
isExperimentConflictError,
toConcurrencyPayload,
} from '../utils'
@@ -651,7 +650,7 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
running_time_calculation: updatedRunningTimeCalculation,
}
)
- actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(response)))
+ actions.setUnmodifiedExperiment(structuredClone(response))
actions.setExperiment({
running_time_calculation: response.running_time_calculation ?? updatedRunningTimeCalculation,
})
@@ -667,7 +666,7 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
const fresh: Experiment = await api.get(
`api/projects/${currentProjectId}/experiments/${props.experiment.id}`
)
- actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(fresh)))
+ actions.setUnmodifiedExperiment(structuredClone(fresh))
actions.setExperiment({ running_time_calculation: fresh.running_time_calculation })
} catch {
// Leave state as-is; the next full experiment load resyncs the snapshot.
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 82fbedb58301..69e33abff71d 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -130,7 +130,6 @@ import {
getDisplayOrderedIndices,
getExperimentVariants,
getOrderedMetricsWithResults,
- initializeMetricOrdering,
conflictPreservedFields,
isExperimentConflictError,
isLegacyExperiment,
@@ -2301,12 +2300,11 @@ export const experimentLogic = kea<experimentLogicType>([
const experiment: Experiment = await api.create(
`/api/projects/${values.currentProjectId}/experiments/${values.experimentId}/launch`
)
- const experimentWithMetricOrdering = initializeMetricOrdering(experiment)
- actions.setExperiment(experimentWithMetricOrdering)
+ actions.setExperiment(experiment)
refreshTreeItem('experiment', String(values.experimentId))
// Trigger results refresh so the metrics table doesn't get stuck in "loading" state
actions.refreshExperimentResults(false, 'manual')
- actions.setUnmodifiedExperiment(structuredClone(experimentWithMetricOrdering))
+ actions.setUnmodifiedExperiment(structuredClone(experiment))
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.LaunchExperiment)
// Prefer the flag key — it's the shorter handle someone would actually type at an agent.
const experimentHandle = experiment.feature_flag_key || experiment.name
@@ -2797,7 +2795,7 @@ export const experimentLogic = kea<experimentLogicType>([
update_feature_flag_params: false,
}
)
- actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(response)))
+ actions.setUnmodifiedExperiment(structuredClone(response))
actions.setExperiment({
parameters: updatedParameters,
})
@@ -2828,7 +2826,7 @@ export const experimentLogic = kea<experimentLogicType>([
update_feature_flag_params: false,
}
)
- actions.setUnmodifiedExperiment(structuredClone(initializeMetricOrdering(response)))
+ actions.setUnmodifiedExperiment(structuredClone(response))
actions.setExperiment({
parameters: updatedParameters,
})
@@ -3256,11 +3254,10 @@ export const experimentLogic = kea<experimentLogicType>([
)
// A newer reorder may have started while this request was in flight.
breakpoint()
- const responseWithMetricsOrdering = initializeMetricOrdering(response)
// Refreshing unmodifiedExperiment too, so a later edit-cancel doesn't revert the
// order the user just set.
- actions.setUnmodifiedExperiment(structuredClone(responseWithMetricsOrdering))
- actions.setExperiment(responseWithMetricsOrdering)
+ actions.setUnmodifiedExperiment(structuredClone(response))
+ actions.setExperiment(response)
} catch (error) {
// Swallowing the breakpoint would roll a superseded reorder back over a newer one.
if (isBreakpoint(error as Error)) {
@@ -3306,13 +3303,17 @@ export const experimentLogic = kea<experimentLogicType>([
(m) => !(m.uuid && (moved.has(m.uuid) || removed.has(m.uuid)))
)
- // The backend appends moved metrics to the target section's ordering
- // from the metric list changes, so only the source ordering is sent.
+ // The ordering arrays are a display hint: a removed metric's stale entry matches nothing,
+ // and a moved metric needs no entry in the target section, where it renders last. The
+ // source array is pruned on a move so readers that rank across both sections do not keep
+ // placing the metric among its old neighbours.
const update: Partial<Experiment> & { update_feature_flag_params?: boolean } = {
[sourceField]: remainingInlineMetrics,
- [orderingField]: orderedUuids.filter((uuid) => !removed.has(uuid) && !moved.has(uuid)),
update_feature_flag_params: false,
}
+ if (moved.size > 0) {
+ update[orderingField] = orderedUuids.filter((uuid) => !removed.has(uuid) && !moved.has(uuid))
+ }
if (movedInlineMetrics.length > 0) {
update[targetField] = [...(values.experiment[targetField] || []), ...movedInlineMetrics]
}
@@ -3599,10 +3600,8 @@ export const experimentLogic = kea<experimentLogicType>([
`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`
)
- const responseWithMetricsOrdering = initializeMetricOrdering(response)
-
- actions.setUnmodifiedExperiment(structuredClone(responseWithMetricsOrdering))
- return responseWithMetricsOrdering
+ actions.setUnmodifiedExperiment(structuredClone(response))
+ return response
} catch (error: any) {
if (error.status === 404) {
actions.setExperimentMissing()
@@ -3629,12 +3628,11 @@ export const experimentLogic = kea<experimentLogicType>([
`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`,
{ ...toConcurrencyPayload(values.unmodifiedExperiment), ...update }
)
- const responseWithMetricsOrdering = initializeMetricOrdering(response)
refreshTreeItem('experiment', String(values.experimentId))
- actions.setUnmodifiedExperiment(structuredClone(responseWithMetricsOrdering))
+ actions.setUnmodifiedExperiment(structuredClone(response))
// Also update the main experiment state
- actions.setExperiment(responseWithMetricsOrdering)
- return responseWithMetricsOrdering
+ actions.setExperiment(response)
+ return response
} catch (error: any) {
if (isExperimentConflictError(error)) {
lemonToast.error(
@@ -3650,9 +3648,8 @@ export const experimentLogic = kea<experimentLogicType>([
const fresh: Experiment = await api.get(
`api/projects/${values.currentProjectId}/experiments/${values.experimentId}`
)
- const freshWithOrdering = initializeMetricOrdering(fresh)
- actions.setUnmodifiedExperiment(structuredClone(freshWithOrdering))
- actions.setExperiment({ ...freshWithOrdering, ...preserved })
+ actions.setUnmodifiedExperiment(structuredClone(fresh))
+ actions.setExperiment({ ...fresh, ...preserved })
} catch {
actions.loadExperiment()
}
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index d5a58de5211e..9746541b9004 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -969,42 +969,6 @@ export function getEventCountQuery(metric: ExperimentMetric, filterTestAccounts:
}
}
-/**
- * Initialize ordering arrays for metrics if they're null
- * Returns a new experiment object with initialized ordering arrays
- */
-export function initializeMetricOrdering(experiment: Experiment): Experiment {
- const newExperiment = { ...experiment }
-
- // Initialize primary_metrics_ordered_uuids if it's null
- if (newExperiment.primary_metrics_ordered_uuids === null) {
- const primaryMetrics = newExperiment.metrics || []
- const sharedPrimaryMetrics = (newExperiment.saved_metrics || []).filter(
- (sharedMetric: any) => sharedMetric.metadata.type === 'primary'
- )
-
- const allMetrics = [...primaryMetrics, ...sharedPrimaryMetrics]
- newExperiment.primary_metrics_ordered_uuids = allMetrics
- .map((metric: any) => metric.uuid || metric.query?.uuid)
- .filter(Boolean)
- }
-
- // Initialize secondary_metrics_ordered_uuids if it's null
- if (newExperiment.secondary_metrics_ordered_uuids === null) {
- const secondaryMetrics = newExperiment.metrics_secondary || []
- const sharedSecondaryMetrics = (newExperiment.saved_metrics || []).filter(
- (sharedMetric: any) => sharedMetric.metadata.type === 'secondary'
- )
-
- const allMetrics = [...secondaryMetrics, ...sharedSecondaryMetrics]
- newExperiment.secondary_metrics_ordered_uuids = allMetrics
- .map((metric: any) => metric.uuid || metric.query?.uuid)
- .filter(Boolean)
- }
-
- return newExperiment
-}
-
/**
* Returns metric indices in display order. Metrics whose UUID appears in
* orderedUuids come first (in that order), followed by any remaining metrics
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 90bb231924c6..06561d7fe018 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -50,7 +50,6 @@ from posthog.models.activity_logging.model_activity import is_impersonated_sessi
from posthog.models.activity_logging.utils import get_changed_fields_local
from posthog.models.filters.filter import Filter
from posthog.models.person.util import get_person_ids_and_uuids_by_uuids
-from posthog.models.signals import mute_selected_signals
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -348,7 +347,7 @@ class ExperimentVersionConflict(APIException):
# Fields a stale write may still change. The metric collections merge per uuid — each metric
# carries a stable server-assigned uuid, so concurrent intent is preserved — and the ordering
-# arrays are re-derived by the ordering syncs. A stale write touching anything else conflicts
+# arrays are a display hint, so the client's array is taken as sent. A stale write touching anything else conflicts
# outright: scalar fields have no sub-identity to merge on, and the edit was likely written
# against context that has since changed (e.g. a description phrased for metrics someone
# edited meanwhile).
@@ -1398,22 +1397,6 @@ class ExperimentService:
self.validate_no_duplicate_metric_uuids(metrics, metrics_secondary)
- if metrics is not None:
- primary_ordering = list(primary_metrics_ordered_uuids or [])
- for metric in metrics:
- if uuid := metric.get("uuid"):
- if uuid not in primary_ordering:
- primary_ordering.append(uuid)
- primary_metrics_ordered_uuids = primary_ordering
-
- if metrics_secondary is not None:
- secondary_ordering = list(secondary_metrics_ordered_uuids or [])
- for metric in metrics_secondary:
- if uuid := metric.get("uuid"):
- if uuid not in secondary_ordering:
- secondary_ordering.append(uuid)
- secondary_metrics_ordered_uuids = secondary_ordering
-
create_kwargs: dict[str, Any] = {
"team": self.team,
"created_by": self.user,
@@ -1456,7 +1439,6 @@ class ExperimentService:
if saved_metrics_ids:
self._sync_saved_metrics(experiment, saved_metrics_ids, serializer_context)
- self._validate_metric_ordering_on_create(experiment)
# Defer the analytics capture until after commit so create_experiment's @transaction.atomic
# doesn't hold posthog_experiment / posthog_filesystem locks open across an external SDK call.
transaction.on_commit(
@@ -1721,11 +1703,9 @@ class ExperimentService:
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``.
+ Ordering arrays need no remap from this function: the first occurrence of a
+ duplicated uuid keeps its original value, so existing ordering entries stay
+ valid, and a regenerated duplicate ranks last until someone reorders.
Callers pass dicts by reference, so we deepcopy to avoid leaking the
generated uuid back into their data.
@@ -1874,7 +1854,7 @@ class ExperimentService:
saved_metrics_ids: list[dict],
serializer_context: dict | None,
) -> None:
- """Create saved metric junction records and sync ordering."""
+ """Create saved metric junction records."""
context = serializer_context or self._build_serializer_context()
for saved_metric_data in saved_metrics_ids:
@@ -1889,106 +1869,6 @@ class ExperimentService:
saved_metric_serializer.is_valid(raise_exception=True)
saved_metric_serializer.save()
- primary_ordering = list(experiment.primary_metrics_ordered_uuids or [])
- secondary_ordering = list(experiment.secondary_metrics_ordered_uuids or [])
- ordering_changed = False
-
- saved_metric_id_list = [sm["id"] for sm in saved_metrics_ids]
- saved_metrics_map = {
- sm.id: sm for sm in ExperimentSavedMetric.objects.filter(id__in=saved_metric_id_list, team_id=self.team.id)
- }
-
- for sm_data in saved_metrics_ids:
- saved_metric = saved_metrics_map.get(sm_data["id"])
- if saved_metric and saved_metric.query:
- if uuid := saved_metric.query.get("uuid"):
- metric_type = (sm_data.get("metadata") or {}).get("type", "primary")
- if metric_type == "primary":
- if uuid not in primary_ordering:
- primary_ordering.append(uuid)
- ordering_changed = True
- else:
- if uuid not in secondary_ordering:
- secondary_ordering.append(uuid)
- ordering_changed = True
-
- if ordering_changed:
- experiment.primary_metrics_ordered_uuids = primary_ordering
- experiment.secondary_metrics_ordered_uuids = secondary_ordering
- experiment.save(update_fields=["primary_metrics_ordered_uuids", "secondary_metrics_ordered_uuids"])
-
- @staticmethod
- def _saved_metric_uuids_by_type(
- query_metadata_pairs: Iterable[tuple[dict | None, dict | None]],
- ) -> dict[str, set[str]]:
- """Group saved-metric query uuids into ``{"primary": set, "secondary": set}``.
-
- A link's metric type comes from its metadata (``metadata["type"]``), defaulting to
- ``"primary"``; anything that isn't ``"primary"`` counts as secondary. Pairs with no query
- or no uuid are skipped.
- """
- by_type: dict[str, set[str]] = {"primary": set(), "secondary": set()}
- for query, metadata in query_metadata_pairs:
- if not query:
- continue
- uuid = query.get("uuid")
- if not uuid:
- continue
- metric_type = (metadata or {}).get("type", "primary")
- by_type["primary" if metric_type == "primary" else "secondary"].add(uuid)
- return by_type
-
- def _assert_ordering_covers_metrics(
- self,
- *,
- primary_metrics: list[dict],
- secondary_metrics: list[dict],
- saved_metric_links: list,
- primary_ordering: list[str] | None,
- secondary_ordering: list[str] | None,
- ) -> None:
- """Assert each ordering array contains every UUID of its metrics (inline + saved).
-
- Shared by the create and update paths, which differ only in where the metrics and
- ordering arrays are sourced from.
- """
- expected_primary = {uuid for m in primary_metrics if (uuid := m.get("uuid"))}
- expected_secondary = {uuid for m in secondary_metrics if (uuid := m.get("uuid"))}
-
- saved_by_type = self._saved_metric_uuids_by_type(
- (link.saved_metric.query, link.metadata) for link in saved_metric_links
- )
- expected_primary |= saved_by_type["primary"]
- expected_secondary |= saved_by_type["secondary"]
-
- for field_name, metric_label, expected_uuids, ordering in (
- ("primary_metrics_ordered_uuids", "primary", expected_primary, primary_ordering),
- ("secondary_metrics_ordered_uuids", "secondary", expected_secondary, secondary_ordering),
- ):
- if not expected_uuids:
- continue
- if ordering is None:
- raise ValidationError(
- f"{field_name} is null but {metric_label} metrics exist. "
- "This is likely a frontend bug - please refresh and try again."
- )
- missing = expected_uuids - set(ordering)
- if missing:
- raise ValidationError(
- f"{field_name} is missing UUIDs: {sorted(missing)}. "
- "This is likely a frontend bug - please refresh and try again."
- )
-
- def _validate_metric_ordering_on_create(self, experiment: Experiment) -> None:
- """Validate that ordering arrays contain all metric UUIDs (create path)."""
- self._assert_ordering_covers_metrics(
- primary_metrics=experiment.metrics or [],
- secondary_metrics=experiment.metrics_secondary or [],
- saved_metric_links=list(experiment.experimenttosavedmetric_set.select_related("saved_metric").all()),
- primary_ordering=experiment.primary_metrics_ordered_uuids,
- secondary_ordering=experiment.secondary_metrics_ordered_uuids,
- )
-
# ------------------------------------------------------------------
# Launch
# ------------------------------------------------------------------
@@ -3466,7 +3346,7 @@ class ExperimentService:
):
return False
for field in ("primary_metrics_ordered_uuids", "secondary_metrics_ordered_uuids"):
- if field in update_data and update_data[field] != getattr(experiment, field):
+ if field in update_data and list(update_data[field] or []) != list(getattr(experiment, field) or []):
return False
if saved_metrics_data is not None and _links_by_id(saved_metrics_data) != _links_by_id(
self._current_saved_metric_link_dicts(experiment)
@@ -3484,8 +3364,8 @@ class ExperimentService:
"""Resolve a stale write (client version behind the row) against the current state.
The metric collections merge per uuid (each metric's server-assigned uuid preserves
- intent across concurrent edits), and client-supplied ordering arrays are reconciled
- to the current state — the ordering syncs re-derive the rest. Scalar fields merge
+ intent across concurrent edits), and a client-supplied ordering array is taken as sent,
+ because it is a display hint that ranks unknown uuids last. Scalar fields merge
per field against their base value in ``original`` (see ``_resolve_scalar_updates``):
only a same-field double edit conflicts, so background writers bumping the version
(e.g. the running-time calculator auto-save) don't fail unrelated scalar saves.
@@ -3532,19 +3412,6 @@ class ExperimentService:
conflicting_metric_uuids=conflict_uuids,
)
- for ordering_field in ("primary_metrics_ordered_uuids", "secondary_metrics_ordered_uuids"):
- client_order = update_data.get(ordering_field)
- if ordering_field in update_data and client_order is not None:
- current_order = list(getattr(experiment, ordering_field) or [])
- current_set = set(current_order)
- # Keep the client's relative order for uuids that still exist, then append
- # concurrently-added ones. The ordering syncs layer this request's own
- # adds/removes on top of this reconciled value.
- update_data[ordering_field] = [
- *(u for u in client_order if u in current_set),
- *(u for u in current_order if u not in client_order),
- ]
-
def update_experiment(
self,
experiment: Experiment,
@@ -3637,9 +3504,8 @@ class ExperimentService:
if field not in update_data and any(m.get("uuid") in saved_metric_uuids for m in stored_metrics):
update_data[field] = deepcopy(stored_metrics)
- # 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:
+ # Seed the uniqueness set with uuids an inline metric must not reuse, because results,
+ # fingerprints and the ordering are keyed by uuid:
# - 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
@@ -3661,12 +3527,8 @@ class ExperimentService:
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.
+ # Regenerated dups need no ordering remap: the incumbent keeps the original uuid, so an
+ # ordering entry for it stays valid, and the ordering ranks a uuid it does not list last.
# `metrics`/`metrics_secondary` are whole-array fields, so changing one metric
# means resending them all. A metric already on the experiment has been through
@@ -3881,17 +3743,12 @@ class ExperimentService:
update_data["version"] = locked_version + 1
# --- saved metrics sync (update-in-place) -----------
- old_saved_metric_uuids: dict[str, set[str]] = {"primary": set(), "secondary": set()}
if update_saved_metrics:
existing_links = {
link.saved_metric_id: link
for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all()
}
- old_saved_metric_uuids = self._saved_metric_uuids_by_type(
- (link.saved_metric.query, link.metadata) for link in existing_links.values()
- )
-
new_saved_metric_ids = {sm["id"] for sm in saved_metrics_data}
existing_saved_metric_ids = set(existing_links.keys())
@@ -3951,21 +3808,6 @@ class ExperimentService:
excluded_variants=excluded_variants,
)
- # --- metric ordering sync + validation -----------------------------
- # Unlike the pure validations hoisted above the flag write, ordering
- # validation is coupled to the saved-metrics DB sync (it consumes
- # old_saved_metric_uuids and the ordering mutations above), so it stays
- # here. The residual — an invalid explicit ordering array combined with a
- # flag change in the same request — is far narrower than the hoisted cases.
- self._sync_ordering_with_metric_changes(experiment, update_data)
- self._sync_ordering_for_saved_metrics_on_update(
- experiment,
- update_data,
- old_saved_metric_uuids,
- saved_metrics_data if update_saved_metrics else None,
- )
- self._validate_metric_ordering_on_update(experiment, update_data)
-
# --- apply changes and save ----------------------------------------
# Feature-flag config was already synced to the flag above; strip it so it is not mirrored
# into the deprecated `parameters` column. Reads re-derive it from the flag.
@@ -4925,190 +4767,6 @@ class ExperimentService:
"completed_last_30d": completed_last_30d,
}
- # ------------------------------------------------------------------
- # Private helpers — update ordering
- # ------------------------------------------------------------------
-
- def _sync_ordering_with_metric_changes(self, experiment: Experiment, update_data: dict) -> None:
- """Sync ordering arrays with inline metric changes during update."""
- if "metrics" not in update_data and "metrics_secondary" not in update_data:
- return
-
- # A stored inline metric can share its uuid with a linked shared metric. When dedup gives the
- # inline copy a fresh uuid, the old uuid still belongs to the shared metric, so keep it in the ordering.
- saved_uuids = self._saved_metric_uuids_by_type(
- (link.saved_metric.query, link.metadata)
- for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all()
- )
-
- if "metrics" in update_data:
- old_uuids = {m.get("uuid") for m in experiment.metrics or [] if m.get("uuid")}
- new_uuids = {m.get("uuid") for m in update_data.get("metrics") or [] if m.get("uuid")}
-
- added = new_uuids - old_uuids
- removed = old_uuids - new_uuids - saved_uuids["primary"]
-
- if added or removed:
- if "primary_metrics_ordered_uuids" in update_data:
- current_ordering = list(update_data["primary_metrics_ordered_uuids"] or [])
- else:
- current_ordering = list(experiment.primary_metrics_ordered_uuids or [])
-
- current_ordering = [u for u in current_ordering if u not in removed]
- for uuid in added:
- if uuid not in current_ordering:
- current_ordering.append(uuid)
-
- update_data["primary_metrics_ordered_uuids"] = current_ordering
-
- if "metrics_secondary" in update_data:
- old_uuids = {m.get("uuid") for m in experiment.metrics_secondary or [] if m.get("uuid")}
- new_uuids = {m.get("uuid") for m in update_data.get("metrics_secondary") or [] if m.get("uuid")}
-
- added = new_uuids - old_uuids
- removed = old_uuids - new_uuids - saved_uuids["secondary"]
-
- if added or removed:
- 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 [])
-
- current_ordering = [u for u in current_ordering if u not in removed]
- for uuid in added:
- if uuid not in current_ordering:
- current_ordering.append(uuid)
-
- update_data["secondary_metrics_ordered_uuids"] = current_ordering
-
- def _sync_ordering_for_saved_metrics_on_update(
- self,
- experiment: Experiment,
- update_data: dict,
- old_saved_metric_uuids: dict[str, set[str]],
- saved_metrics_data: list[dict] | None,
- ) -> None:
- """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
-
- new_primary_uuids: set[str] = set()
- new_secondary_uuids: set[str] = set()
-
- saved_metric_ids_list = [sm["id"] for sm in saved_metrics_data]
- if saved_metric_ids_list:
- saved_metrics = {
- sm.id: sm
- for sm in ExperimentSavedMetric.objects.filter(id__in=saved_metric_ids_list, team_id=self.team.id)
- }
- new_uuids = self._saved_metric_uuids_by_type(
- (
- saved_metric.query if (saved_metric := saved_metrics.get(sm_data["id"])) else None,
- sm_data.get("metadata"),
- )
- for sm_data in saved_metrics_data
- )
- new_primary_uuids = new_uuids["primary"]
- new_secondary_uuids = new_uuids["secondary"]
-
- # An inline metric can share its uuid with a detached shared metric. The ordering entry
- # still belongs to the inline metric, so keep it.
- inline_primary_uuids = {
- uuid for m in update_data.get("metrics", experiment.metrics) or [] if (uuid := m.get("uuid"))
- }
- inline_secondary_uuids = {
- uuid
- for m in update_data.get("metrics_secondary", experiment.metrics_secondary) or []
- if (uuid := m.get("uuid"))
- }
-
- added_primary = new_primary_uuids - old_saved_metric_uuids["primary"]
- removed_primary = old_saved_metric_uuids["primary"] - new_primary_uuids - inline_primary_uuids
- added_secondary = new_secondary_uuids - old_saved_metric_uuids["secondary"]
- removed_secondary = old_saved_metric_uuids["secondary"] - new_secondary_uuids - inline_secondary_uuids
-
- # 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 reorder
- else:
- update_data[field] = auto_sync_result
- auto_synced_fields.append(field)
-
- 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:
- resolve_ordering(
- "secondary_metrics_ordered_uuids",
- list(experiment.secondary_metrics_ordered_uuids or []),
- added_secondary,
- removed_secondary,
- )
-
- # 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)."""
- self._assert_ordering_covers_metrics(
- primary_metrics=update_data.get("metrics", experiment.metrics) or [],
- secondary_metrics=update_data.get("metrics_secondary", experiment.metrics_secondary) or [],
- saved_metric_links=list(experiment.experimenttosavedmetric_set.select_related("saved_metric").all()),
- primary_ordering=update_data.get("primary_metrics_ordered_uuids", experiment.primary_metrics_ordered_uuids),
- secondary_ordering=update_data.get(
- "secondary_metrics_ordered_uuids", experiment.secondary_metrics_ordered_uuids
- ),
- )
-
def _build_serializer_context(self) -> dict:
"""Build minimal DRF serializer context for internal service use."""
return {
diff --git a/products/experiments/backend/legacy_migration.py b/products/experiments/backend/legacy_migration.py
index c9c41c0058b7..8cf619bcf09b 100644
--- a/products/experiments/backend/legacy_migration.py
+++ b/products/experiments/backend/legacy_migration.py
@@ -97,7 +97,6 @@ def migrate_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:
@@ -174,9 +173,8 @@ def _migrated_target(metric: ExperimentSavedMetric, team_id: int) -> ExperimentS
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.
+ The conversion drops the legacy uuid and never had a fingerprint. Results, reorders and the
+ activity log all key on the uuid, so a metric without one has no identity in the new engine.
"""
stats_method = (experiment.stats_config or {}).get("method", "bayesian")
for metric in metrics:
@@ -190,20 +188,3 @@ def _prepare_metrics(metrics: list[dict], experiment: Experiment) -> list[dict]:
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/serializers.py b/products/experiments/backend/presentation/serializers.py
index 329d5c444263..5709c8904c01 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -359,6 +359,13 @@ class ExperimentBaseSerializer(
data["parameters"] = parameters
+def _dedupe_metric_ordering(value: list[str] | None) -> list[str] | None:
+ """Keep the first occurrence of each uuid. The ordering is a display hint, so a repeat carries no meaning."""
+ if value is None:
+ return None
+ return list(dict.fromkeys(value))
+
+
class ExperimentSerializer(ExperimentBaseSerializer):
"""Full experiment representation for the detail, create, and update endpoints.
@@ -382,6 +389,26 @@ class ExperimentSerializer(ExperimentBaseSerializer):
allow_null=True,
help_text="IDs of shared saved metrics to attach to this experiment. Each item has 'id' (saved metric ID) and 'metadata' with 'type' (primary or secondary).",
)
+ primary_metrics_ordered_uuids = serializers.ListField(
+ child=serializers.CharField(allow_blank=False),
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Display order of the primary metrics, as metric uuids. This is a display hint only: a metric "
+ "not in the list renders after the listed ones in stored order, and an entry that matches no "
+ "metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it."
+ ),
+ )
+ secondary_metrics_ordered_uuids = serializers.ListField(
+ child=serializers.CharField(allow_blank=False),
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric "
+ "not in the list renders after the listed ones in stored order, and an entry that matches no "
+ "metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it."
+ ),
+ )
allow_unknown_events = serializers.BooleanField(
required=False,
default=False,
@@ -787,6 +814,12 @@ class ExperimentSerializer(ExperimentBaseSerializer):
ExperimentService.validate_excluded_variants(value)
return value
+ def validate_primary_metrics_ordered_uuids(self, value: list[str] | None) -> list[str] | None:
+ return _dedupe_metric_ordering(value)
+
+ def validate_secondary_metrics_ordered_uuids(self, value: list[str] | None) -> list[str] | None:
+ return _dedupe_metric_ordering(value)
+
def validate_exposure_criteria(self, exposure_criteria: dict | None):
ExperimentService.validate_experiment_exposure_criteria(exposure_criteria)
return exposure_criteria
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 2cbda04d1ee2..b7d0957dda28 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -450,56 +450,6 @@ class TestExperimentService(APIBaseTest):
# Metric ordering
# ------------------------------------------------------------------
- def test_metric_ordering_synced(self):
- self._create_flag(key="ordering-test")
- service = self._service()
-
- metrics = [
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "aaa",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "bbb",
- "source": {"kind": "EventsNode", "event": "$pageleave"},
- },
- ]
-
- experiment = service.create_experiment(
- name="Ordering Test",
- feature_flag_key="ordering-test",
- allow_unknown_events=True,
- metrics=metrics,
- )
-
- assert experiment.primary_metrics_ordered_uuids == ["aaa", "bbb"]
-
- def test_secondary_metric_ordering_synced(self):
- self._create_flag(key="sec-ordering")
- service = self._service()
-
- metrics_secondary = [
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "sec-1",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
- ]
-
- experiment = service.create_experiment(
- name="Secondary Ordering",
- feature_flag_key="sec-ordering",
- allow_unknown_events=True,
- metrics_secondary=metrics_secondary,
- )
-
- assert experiment.secondary_metrics_ordered_uuids == ["sec-1"]
-
# ------------------------------------------------------------------
# Web experiment variants
# ------------------------------------------------------------------
@@ -779,7 +729,7 @@ class TestExperimentService(APIBaseTest):
links = list(experiment.experimenttosavedmetric_set.all())
assert len(links) == 1
assert links[0].saved_metric_id == saved_metric.id
- assert experiment.primary_metrics_ordered_uuids == ["sm-uuid"]
+ assert experiment.primary_metrics_ordered_uuids is None
@parameterized.expand(
[
@@ -1549,31 +1499,30 @@ class TestExperimentService(APIBaseTest):
"variant-b": {"rollout_percentage": 33},
}
- assert set(experiment.primary_metrics_ordered_uuids or []) == {
- "manual-primary",
- primary_metric_uuid,
- "saved-primary",
- }
- assert set(experiment.secondary_metrics_ordered_uuids or []) == {
- "manual-secondary",
- secondary_metric_uuid,
- "saved-secondary",
- }
+ # Stored as sent: the ordering is a display hint, so create does not fill in the other uuids.
+ assert experiment.primary_metrics_ordered_uuids == ["manual-primary"]
+ assert experiment.secondary_metrics_ordered_uuids == ["manual-secondary"]
def test_create_experiment_rolls_back_when_late_validation_fails(self):
service = self._service()
+ saved_metric = ExperimentSavedMetric.objects.create(
+ team=self.team,
+ name="Late failure",
+ query={"kind": "ExperimentMetric", "metric_type": "count", "uuid": "late-uuid", "event": "$pageview"},
+ )
with (
patch.object(
ExperimentService,
- "_validate_metric_ordering_on_create",
- side_effect=ValidationError("ordering invalid"),
+ "_sync_saved_metrics",
+ side_effect=ValidationError("link invalid"),
),
self.assertRaises(ValidationError),
):
service.create_experiment(
name="Rollback Create",
feature_flag_key="rollback-create-flag",
+ saved_metrics_ids=[{"id": saved_metric.id, "metadata": {"type": "primary"}}],
)
assert not Experiment.objects.filter(name="Rollback Create").exists()
@@ -2000,83 +1949,13 @@ class TestExperimentService(APIBaseTest):
assert updated.metrics is not None
assert updated.metrics[0]["fingerprint"] != original_fingerprint
- def test_update_experiment_syncs_ordering_on_metric_add(self):
- experiment = self._create_draft_experiment()
- service = self._service()
-
- updated = service.update_experiment(
- experiment,
- {
- "metrics": [
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "m1",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "m2",
- "source": {"kind": "EventsNode", "event": "$pageleave"},
- },
- ],
- },
- allow_unknown_events=True,
- )
-
- assert updated.primary_metrics_ordered_uuids is not None
- assert "m1" in updated.primary_metrics_ordered_uuids
- assert "m2" in updated.primary_metrics_ordered_uuids
-
- def test_update_experiment_syncs_ordering_on_metric_remove(self):
- self._create_flag(key="remove-test")
- service = self._service()
- experiment = service.create_experiment(
- name="Remove Test",
- feature_flag_key="remove-test",
- allow_unknown_events=True,
- metrics=[
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "m1",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "m2",
- "source": {"kind": "EventsNode", "event": "$pageleave"},
- },
- ],
- primary_metrics_ordered_uuids=["m1", "m2"],
- )
-
- updated = service.update_experiment(
- experiment,
- {
- "metrics": [
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "m1",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
- ],
- },
- allow_unknown_events=True,
- )
-
- assert updated.primary_metrics_ordered_uuids == ["m1"]
-
@parameterized.expand(
[
- ("primary", "metrics", "primary_metrics_ordered_uuids"),
- ("secondary", "metrics_secondary", "secondary_metrics_ordered_uuids"),
+ ("primary", "metrics"),
+ ("secondary", "metrics_secondary"),
]
)
- def test_update_experiment_auto_generates_uuids(self, _name, field, ordering_attr):
+ def test_update_experiment_auto_generates_uuids(self, _name, field):
experiment = self._create_draft_experiment()
service = self._service()
@@ -2098,15 +1977,14 @@ class TestExperimentService(APIBaseTest):
assert len(metrics) == 1
generated_uuid = metrics[0].get("uuid")
assert generated_uuid, "UUID should be auto-generated for metrics without one"
- assert getattr(updated, ordering_attr) == [generated_uuid]
@parameterized.expand(
[
- ("primary", "metrics", "primary_metrics_ordered_uuids"),
- ("secondary", "metrics_secondary", "secondary_metrics_ordered_uuids"),
+ ("primary", "metrics"),
+ ("secondary", "metrics_secondary"),
]
)
- def test_update_experiment_preserves_provided_metric_uuids(self, _name, field, ordering_attr):
+ def test_update_experiment_preserves_provided_metric_uuids(self, _name, field):
experiment = self._create_draft_experiment()
service = self._service()
@@ -2127,7 +2005,60 @@ class TestExperimentService(APIBaseTest):
metrics = getattr(updated, field)
assert metrics[0]["uuid"] == "explicit-uuid"
- assert "explicit-uuid" in (getattr(updated, ordering_attr) or [])
+
+ @parameterized.expand(
+ [
+ ("inline_add", {"metrics": ["p1", "p2", "p3"]}),
+ ("inline_remove", {"metrics_secondary": []}),
+ ("shared_attach", {"saved_metrics_ids": ["sm-1:primary", "sm-2:secondary"]}),
+ ("shared_detach", {"saved_metrics_ids": []}),
+ ("move_between_sections", {"metrics": ["p1"], "metrics_secondary": ["s1", "p2"]}),
+ ]
+ )
+ def test_metric_changes_leave_ordering_untouched(self, _name: str, spec: dict) -> None:
+ self._create_flag(key="ordering-untouched")
+ saved = {
+ name: ExperimentSavedMetric.objects.create(
+ team=self.team,
+ name=name,
+ query={"kind": "ExperimentMetric", "metric_type": "mean", "uuid": f"{name}-uuid", "event": "$pageview"},
+ )
+ for name in ("sm-1", "sm-2")
+ }
+
+ def inline(uuid: str) -> dict:
+ return {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": uuid,
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ }
+
+ service = self._service()
+ experiment = service.create_experiment(
+ name="Ordering untouched",
+ feature_flag_key="ordering-untouched",
+ allow_unknown_events=True,
+ metrics=[inline("p1"), inline("p2")],
+ metrics_secondary=[inline("s1")],
+ saved_metrics_ids=[{"id": saved["sm-1"].id, "metadata": {"type": "primary"}}],
+ primary_metrics_ordered_uuids=["sm-1-uuid", "p2", "p1"],
+ secondary_metrics_ordered_uuids=["s1"],
+ )
+
+ update: dict = {}
+ for field, value in spec.items():
+ if field == "saved_metrics_ids":
+ update[field] = [
+ {"id": saved[ref.split(":")[0]].id, "metadata": {"type": ref.split(":")[1]}} for ref in value
+ ]
+ else:
+ update[field] = [inline(uuid) for uuid in value]
+
+ updated = service.update_experiment(experiment, update, allow_unknown_events=True)
+
+ assert updated.primary_metrics_ordered_uuids == ["sm-1-uuid", "p2", "p1"]
+ assert updated.secondary_metrics_ordered_uuids == ["s1"]
@parameterized.expand(
[
@@ -2541,8 +2472,7 @@ class TestExperimentService(APIBaseTest):
assert link_ids == [sm1.id]
fresh_experiment = Experiment.objects.get(id=experiment.id)
- assert fresh_experiment.primary_metrics_ordered_uuids == ["sm-1"]
- assert fresh_experiment.secondary_metrics_ordered_uuids == []
+ assert fresh_experiment.primary_metrics_ordered_uuids is None
def test_update_experiment_validates_saved_metrics_before_mutation(self) -> None:
self._create_flag(key="saved-metrics-update-validate")
@@ -5807,8 +5737,7 @@ class TestExperimentService(APIBaseTest):
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.
+ First occurrence keeps the supplied uuid; later occurrences get fresh ones.
"""
shared_uuid = "11bfb66a-51f5-48d0-a87e-bde2b4c958a6"
service = self._service()
@@ -5837,8 +5766,6 @@ class TestExperimentService(APIBaseTest):
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_are_regenerated(self):
"""Cross-list collisions are deduped — secondary gets a fresh uuid."""
@@ -6068,6 +5995,11 @@ class TestExperimentService(APIBaseTest):
assert source.metrics_secondary is not None
source_primary_uuid = source.metrics[0]["uuid"]
source_secondary_uuid = source.metrics_secondary[0]["uuid"]
+ Experiment.objects.filter(id=source.id).update(
+ primary_metrics_ordered_uuids=[source_primary_uuid],
+ secondary_metrics_ordered_uuids=[source_secondary_uuid],
+ )
+ source.refresh_from_db()
dup = service.duplicate_experiment(source)
@@ -6085,11 +6017,7 @@ class TestExperimentService(APIBaseTest):
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.
+ the inline copy so the two metrics stop sharing results.
"""
self._create_flag(key="dedup-with-saved")
saved_metric_uuid = "33bfb66a-51f5-48d0-a87e-bde2b4c958a6"
@@ -6110,9 +6038,6 @@ class TestExperimentService(APIBaseTest):
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).
@@ -6145,19 +6070,14 @@ class TestExperimentService(APIBaseTest):
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]
@parameterized.expand(
[
- ("primary", "metrics", "metrics_secondary", "primary_metrics_ordered_uuids", "primary", True),
- ("secondary", "metrics_secondary", "metrics", "secondary_metrics_ordered_uuids", "secondary", True),
- ("no_collision", "metrics", "metrics_secondary", "primary_metrics_ordered_uuids", "primary", False),
+ ("primary", "metrics", "metrics_secondary", "primary", True),
+ ("secondary", "metrics_secondary", "metrics", "secondary", True),
+ ("no_collision", "metrics", "metrics_secondary", "primary", False),
]
)
def test_attaching_saved_metric_regenerates_stored_inline_uuid_that_collides(
@@ -6165,7 +6085,6 @@ class TestExperimentService(APIBaseTest):
_name: str,
field: str,
other_field: str,
- ordering_attr: str,
metric_type: str,
collides: bool,
) -> None:
@@ -6221,7 +6140,6 @@ class TestExperimentService(APIBaseTest):
if collides:
assert new_inline_uuid != inline_uuid
UUID(new_inline_uuid)
- assert {new_inline_uuid, saved_metric_uuid} <= set(getattr(updated, ordering_attr))
else:
assert getattr(updated, field) == stored_before[field]
@@ -6231,7 +6149,7 @@ class TestExperimentService(APIBaseTest):
("resend_inline_secondary", "metrics_secondary", "secondary_metrics_ordered_uuids", "secondary", False),
]
)
- def test_update_keeps_saved_metric_uuid_in_ordering_when_stored_inline_copy_collides(
+ def test_update_regenerates_stored_inline_copy_that_collides_with_saved_metric_uuid(
self, _name: str, field: str, ordering_attr: str, metric_type: str, attach_another: bool
) -> None:
self._create_flag(key="stored-collision")
@@ -6279,7 +6197,8 @@ class TestExperimentService(APIBaseTest):
new_inline_uuid = getattr(updated, field)[0]["uuid"]
assert new_inline_uuid != shared_uuid
- assert {shared_uuid, new_inline_uuid} <= set(getattr(updated, ordering_attr))
+ # The ordering is a display hint and is not rewritten: the shared uuid stays, the new one renders last.
+ assert getattr(updated, ordering_attr) == [shared_uuid]
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."""
@@ -6314,9 +6233,6 @@ class TestExperimentService(APIBaseTest):
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
@parameterized.expand(
[
@@ -6391,10 +6307,6 @@ class TestExperimentService(APIBaseTest):
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]
diff --git a/products/experiments/backend/test/test_legacy_migration.py b/products/experiments/backend/test/test_legacy_migration.py
index 3357e9c7ef81..122a88924ce8 100644
--- a/products/experiments/backend/test/test_legacy_migration.py
+++ b/products/experiments/backend/test/test_legacy_migration.py
@@ -68,15 +68,15 @@ class TestExperimentMigrateEndpoint(APILicensedTest):
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.
+ def test_migrated_metrics_get_uuids_and_fingerprints(self) -> None:
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]["uuid"]
assert migrated.metrics[0]["fingerprint"]
+ # No ordering is written: the results page renders stored order until someone reorders.
+ assert migrated.primary_metrics_ordered_uuids is None
+ assert migrated.secondary_metrics_ordered_uuids is None
def test_the_copy_starts_unlinked_from_the_source_flag_rule(self) -> None:
rule_id = uuid4()
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 1b4af3183608..68f14a10dce1 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -7627,13 +7627,6 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
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/",
@@ -7649,7 +7642,6 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
)
self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)
saved_metric_id = saved_metric_response.json()["id"]
- saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
# Create experiment without saved metrics
experiment_response = self.client.post(
@@ -7674,9 +7666,9 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
)
self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- # Verify ordering was updated in the database
+ # Adding a metric leaves the ordering alone: it is a display hint the client sends only on reorder.
experiment = Experiment.objects.get(id=experiment_id)
- self.assertIn(saved_metric_uuid, experiment.secondary_metrics_ordered_uuids or [])
+ self.assertIsNone(experiment.secondary_metrics_ordered_uuids)
# 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()
@@ -7715,9 +7707,8 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
)
self.assertEqual(remove_response.status_code, status.HTTP_200_OK)
- # Verify ordering was updated
experiment.refresh_from_db()
- self.assertNotIn(saved_metric_uuid, experiment.secondary_metrics_ordered_uuids or [])
+ self.assertIsNone(experiment.secondary_metrics_ordered_uuids)
# 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()
@@ -7732,807 +7723,116 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
)
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
+ @parameterized.expand(
+ [
+ ("duplicates_deduped", ["uuid-a", "uuid-a", "uuid-b"], status.HTTP_200_OK, ["uuid-a", "uuid-b"]),
+ ("missing_metric_uuid_accepted", ["not-a-metric"], status.HTTP_200_OK, ["not-a-metric"]),
+ ("null_stored", None, status.HTTP_200_OK, None),
+ ("blank_entry_rejected", ["uuid-a", ""], status.HTTP_400_BAD_REQUEST, ["uuid-a"]),
+ ("non_list_rejected", "uuid-a", status.HTTP_400_BAD_REQUEST, ["uuid-a"]),
+ ]
+ )
+ def test_ordering_field_is_normalized_not_checked_against_metrics(
+ self, _name: str, payload: object, expected_status: int, expected_stored: list[str] | None
+ ):
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",
+ "name": "Ordering Normalization",
+ "feature_flag_key": "ordering-normalization",
"metrics": [
{
"kind": "ExperimentMetric",
"metric_type": "mean",
- "uuid": "reorder-uuid-a",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": "reorder-uuid-b",
+ "uuid": "uuid-a",
"source": {"kind": "EventsNode", "event": "$pageview"},
},
],
- "primary_metrics_ordered_uuids": ["reorder-uuid-a", "reorder-uuid-b"],
+ "primary_metrics_ordered_uuids": ["uuid-a"],
},
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(
+ response = self.client.patch(
f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {"primary_metrics_ordered_uuids": ["reorder-uuid-b", "reorder-uuid-a"]},
+ {"primary_metrics_ordered_uuids": payload},
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",
- "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"]
- saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
+ self.assertEqual(response.status_code, expected_status, response.json())
+ self.assertEqual(Experiment.objects.get(id=experiment_id).primary_metrics_ordered_uuids, expected_stored)
- # Start with one inline primary metric so we have an existing ordering to permute
+ 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": "Combined PATCH Activity Test",
- "feature_flag_key": "combined-patch-activity",
+ "name": "Reorder Activity Test",
+ "feature_flag_key": "reorder-activity-test",
"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": [saved_metric_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,
- [saved_metric_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"], [saved_metric_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: list[str] = []
- saved_metric_ids: list[int] = []
- for index in range(2):
- 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",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- saved_metric_ids.append(response.json()["id"])
- saved_metric_uuids.append(response.json()["query"]["uuid"])
-
- 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")
-
- # Create a saved metric in team A (self.team)
- saved_metric_response = self.client.post(
- f"/api/projects/{self.team.id}/experiment_saved_metrics/",
- {
- "name": "Team A Metric",
- "description": "This metric belongs to Team A",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- },
- format="json",
- )
- self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)
- team_a_metric_id = saved_metric_response.json()["id"]
-
- # Create an experiment in team B
- experiment_response = self.client.post(
- f"/api/projects/{team_b.id}/experiments/",
- {
- "name": "Team B Experiment",
- "feature_flag_key": "team-b-flag",
- "parameters": None,
- },
- format="json",
- )
- self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)
- team_b_experiment_id = experiment_response.json()["id"]
-
- # Try to add Team A's saved metric to Team B's experiment
- # This should fail with validation error
- update_response = self.client.patch(
- f"/api/projects/{team_b.id}/experiments/{team_b_experiment_id}/",
- {
- "saved_metrics_ids": [{"id": team_a_metric_id, "metadata": {"type": "primary"}}],
- },
- format="json",
- )
-
- self.assertEqual(update_response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn("does not exist or does not belong to this project", str(update_response.json()))
-
- def test_update_auto_syncs_ordering_when_inline_metric_added_with_empty_ordering(self):
- """Test that adding a metric with an empty ordering array auto-populates the ordering"""
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-ordering-validation",
- "parameters": None,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- # Add a metric with an empty ordering array - backend should auto-populate
- metric_uuid = "test-metric-uuid-123"
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "allow_unknown_events": True,
- "metrics": [
- {
- "uuid": metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
- ],
- "primary_metrics_ordered_uuids": [],
- },
- format="json",
- )
-
- # Should succeed and the UUID should be in the ordering
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- self.assertIn(metric_uuid, update_response.json()["primary_metrics_ordered_uuids"])
-
- def test_update_auto_syncs_ordering_when_saved_metric_added_with_empty_ordering(self):
- """Test that adding a saved metric with empty ordering auto-populates the ordering"""
- saved_metric_response = self.client.post(
- f"/api/projects/{self.team.id}/experiment_saved_metrics/",
- {
- "name": "Test Saved Metric",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"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"]
- saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-saved-metric-ordering",
- "parameters": None,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- # Add a saved metric with empty ordering - backend should auto-populate
- 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": [],
- },
- format="json",
- )
-
- # Should succeed and the UUID should be in the ordering
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- self.assertIn(saved_metric_uuid, update_response.json()["primary_metrics_ordered_uuids"])
-
- def test_update_succeeds_when_ordering_arrays_are_correct(self):
- """Test that updating an experiment succeeds when ordering arrays contain all metric UUIDs"""
- saved_metric_response = self.client.post(
- f"/api/projects/{self.team.id}/experiment_saved_metrics/",
- {
- "name": "Test Saved Metric",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"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"]
- saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-correct-ordering",
- "parameters": None,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- inline_metric_uuid = "inline-metric-uuid-abc"
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "allow_unknown_events": True,
- "metrics": [
- {
- "uuid": inline_metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
- ],
- "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "primary"}}],
- "primary_metrics_ordered_uuids": [inline_metric_uuid, saved_metric_uuid],
- },
- format="json",
- )
-
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
-
- def test_create_auto_syncs_ordering_when_inline_metric_added_with_empty_ordering(self):
- """Test that creating an experiment with metrics and empty ordering auto-populates the ordering"""
- metric_uuid = "create-metric-uuid-123"
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "allow_unknown_events": True,
- "name": "Test Experiment",
- "feature_flag_key": "test-create-ordering-validation",
- "parameters": None,
- "metrics": [
- {
- "uuid": metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
- ],
- "primary_metrics_ordered_uuids": [],
- },
- format="json",
- )
-
- # Should succeed and the UUID should be in the ordering
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertIn(metric_uuid, response.json()["primary_metrics_ordered_uuids"])
-
- def test_update_auto_syncs_ordering_when_inline_metric_added_without_ordering(self):
- """Test that adding a metric without sending ordering at all auto-populates the ordering"""
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-ordering-auto-sync",
- "parameters": None,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- # Add a metric WITHOUT sending ordering - backend should auto-populate
- metric_uuid = "auto-sync-metric-uuid-123"
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "allow_unknown_events": True,
- "metrics": [
- {
- "uuid": metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
- ],
- },
- format="json",
- )
-
- # Should succeed and the UUID should be in the ordering
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- self.assertIn(metric_uuid, update_response.json()["primary_metrics_ordered_uuids"])
-
- def test_update_removes_uuid_from_ordering_when_metric_removed(self):
- """Test that removing a metric also removes its UUID from the ordering array"""
- metric_uuid_1 = "remove-test-uuid-1"
- metric_uuid_2 = "remove-test-uuid-2"
-
- # Create experiment with two metrics
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "allow_unknown_events": True,
- "name": "Test Experiment",
- "feature_flag_key": "test-remove-sync",
- "parameters": None,
- "metrics": [
- {
- "uuid": metric_uuid_1,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- {
- "uuid": metric_uuid_2,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageleave"}],
- },
- ],
- "primary_metrics_ordered_uuids": [metric_uuid_1, metric_uuid_2],
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- # Remove one metric - backend should auto-remove from ordering
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "allow_unknown_events": True,
- "metrics": [
- {
- "uuid": metric_uuid_1,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- ],
- },
- format="json",
- )
-
- # Should succeed, only metric_uuid_1 should remain in ordering
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- ordering = update_response.json()["primary_metrics_ordered_uuids"]
- self.assertIn(metric_uuid_1, ordering)
- self.assertNotIn(metric_uuid_2, ordering)
-
- def test_update_auto_syncs_secondary_metrics_ordering(self):
- """Test that adding a secondary metric auto-populates the secondary ordering array"""
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-secondary-sync",
- "parameters": None,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- # Add a secondary metric without ordering
- metric_uuid = "secondary-metric-uuid-123"
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "allow_unknown_events": True,
- "metrics_secondary": [
- {
- "uuid": metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
- ],
- },
- format="json",
- )
-
- # Should succeed and the UUID should be in the secondary ordering
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- self.assertIn(metric_uuid, update_response.json()["secondary_metrics_ordered_uuids"])
-
- def test_update_ordering_unchanged_when_no_metrics_change(self):
- """Test that ordering arrays are not modified when only name is updated"""
- metric_uuid = "unchanged-metric-uuid"
-
- # Create experiment with a metric
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "allow_unknown_events": True,
- "name": "Test Experiment",
- "feature_flag_key": "test-unchanged-ordering",
- "parameters": None,
- "metrics": [
- {
- "uuid": metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
- ],
- "primary_metrics_ordered_uuids": [metric_uuid],
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
- original_ordering = response.json()["primary_metrics_ordered_uuids"]
-
- # Update only the name - ordering should remain unchanged
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "name": "Updated Experiment Name",
- },
- format="json",
- )
-
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- self.assertEqual(update_response.json()["primary_metrics_ordered_uuids"], original_ordering)
-
- def test_update_preserves_existing_order_when_adding_metrics(self):
- """Test that existing metric order is preserved when adding new metrics"""
- metric_uuid_1 = "preserve-order-uuid-1"
- metric_uuid_2 = "preserve-order-uuid-2"
- metric_uuid_3 = "preserve-order-uuid-3"
-
- # Create experiment with two metrics in specific order
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "allow_unknown_events": True,
- "name": "Test Experiment",
- "feature_flag_key": "test-preserve-order",
- "parameters": None,
- "metrics": [
- {
- "uuid": metric_uuid_1,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- {
- "uuid": metric_uuid_2,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageleave"}],
- },
- ],
- "primary_metrics_ordered_uuids": [metric_uuid_2, metric_uuid_1],
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- # Add a third metric - existing order should be preserved, new one appended
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "allow_unknown_events": True,
- "metrics": [
- {
- "uuid": metric_uuid_1,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- {
- "uuid": metric_uuid_2,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageleave"}],
- },
- {
- "uuid": metric_uuid_3,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$custom"}],
- },
- ],
- },
- format="json",
- )
-
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- ordering = update_response.json()["primary_metrics_ordered_uuids"]
- # Original order preserved, new metric appended
- self.assertEqual(ordering, [metric_uuid_2, metric_uuid_1, metric_uuid_3])
-
- def test_update_auto_syncs_ordering_when_saved_metric_added_without_ordering(self):
- """Test that adding a saved metric without sending ordering auto-populates the ordering"""
- saved_metric_response = self.client.post(
- f"/api/projects/{self.team.id}/experiment_saved_metrics/",
- {
- "name": "Test Saved Metric",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"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"]
- saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-saved-metric-no-ordering",
- "parameters": None,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
-
- # Add a saved metric WITHOUT sending ordering - backend should auto-populate
- update_response = self.client.patch(
- f"/api/projects/{self.team.id}/experiments/{experiment_id}/",
- {
- "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "primary"}}],
- },
- format="json",
- )
-
- # Should succeed and the UUID should be in the ordering
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- self.assertIn(saved_metric_uuid, update_response.json()["primary_metrics_ordered_uuids"])
-
- def test_update_removes_saved_metric_uuid_from_ordering_when_removed(self):
- """Test that removing a saved metric also removes its UUID from the ordering array"""
-
- # Create two saved metrics
- saved_metric_response_1 = self.client.post(
- f"/api/projects/{self.team.id}/experiment_saved_metrics/",
- {
- "name": "Saved Metric 1",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- },
- format="json",
- )
- saved_metric_id_1 = saved_metric_response_1.json()["id"]
- saved_metric_uuid_1 = saved_metric_response_1.json()["query"]["uuid"]
-
- saved_metric_response_2 = self.client.post(
- f"/api/projects/{self.team.id}/experiment_saved_metrics/",
- {
- "name": "Saved Metric 2",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageleave"}],
- },
- },
- format="json",
- )
- saved_metric_id_2 = saved_metric_response_2.json()["id"]
- saved_metric_uuid_2 = saved_metric_response_2.json()["query"]["uuid"]
-
- # Create experiment with both saved metrics
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-remove-saved-metric",
- "parameters": None,
- "saved_metrics_ids": [
- {"id": saved_metric_id_1, "metadata": {"type": "primary"}},
- {"id": saved_metric_id_2, "metadata": {"type": "primary"}},
+ {
+ "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": [saved_metric_uuid_1, saved_metric_uuid_2],
+ "primary_metrics_ordered_uuids": ["reorder-uuid-a", "reorder-uuid-b"],
},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)
+ experiment_id = experiment_response.json()["id"]
- # Remove one saved metric - backend should auto-remove from ordering
- update_response = self.client.patch(
+ 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}/",
- {
- "saved_metrics_ids": [{"id": saved_metric_id_1, "metadata": {"type": "primary"}}],
- },
+ {"primary_metrics_ordered_uuids": ["reorder-uuid-b", "reorder-uuid-a"]},
format="json",
)
+ self.assertEqual(reorder_response.status_code, status.HTTP_200_OK)
- # Should succeed, only saved_metric_uuid_1 should remain in ordering
- self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- ordering = update_response.json()["primary_metrics_ordered_uuids"]
- self.assertIn(saved_metric_uuid_1, ordering)
- self.assertNotIn(saved_metric_uuid_2, ordering)
+ 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_update_auto_syncs_secondary_saved_metric_ordering(self):
- """Test that adding a secondary saved metric auto-populates the secondary ordering array"""
+ 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": "Secondary Saved Metric",
+ "name": "Combined PATCH Saved Metric",
"query": {
"kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
},
},
format="json",
@@ -8541,125 +7841,168 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
saved_metric_id = saved_metric_response.json()["id"]
saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
- response = self.client.post(
+ # 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/",
{
- "name": "Test Experiment",
- "feature_flag_key": "test-secondary-saved-metric",
- "parameters": None,
+ "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(response.status_code, status.HTTP_201_CREATED)
- experiment_id = response.json()["id"]
+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)
+ experiment_id = experiment_response.json()["id"]
- # Add a secondary saved metric without ordering
+ 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": "secondary"}}],
+ "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "primary"}}],
+ "primary_metrics_ordered_uuids": [saved_metric_uuid, "combined-inline-uuid"],
},
format="json",
)
-
- # Should succeed and the UUID should be in the secondary ordering
self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- self.assertIn(saved_metric_uuid, update_response.json()["secondary_metrics_ordered_uuids"])
- def test_create_auto_syncs_ordering_when_inline_metric_added_without_ordering(self):
- """Test that creating an experiment with metrics but no ordering auto-populates the ordering"""
- metric_uuid = "create-no-ordering-uuid"
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "allow_unknown_events": True,
- "name": "Test Experiment",
- "feature_flag_key": "test-create-no-ordering",
- "parameters": None,
- "metrics": [
- {
- "uuid": metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
- ],
- },
- format="json",
+ experiment = Experiment.objects.get(id=experiment_id)
+ self.assertEqual(
+ experiment.primary_metrics_ordered_uuids,
+ [saved_metric_uuid, "combined-inline-uuid"],
)
- # Should succeed and the UUID should be in the ordering
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertIn(metric_uuid, response.json()["primary_metrics_ordered_uuids"])
+ # 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)
- def test_create_auto_syncs_ordering_for_secondary_inline_metrics(self):
- """Test that creating an experiment with secondary metrics auto-populates secondary ordering"""
- metric_uuid = "create-secondary-uuid"
- response = self.client.post(
+ # 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"], [saved_metric_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_touch_ordering(
+ self, metric_type: str, ordering_field: str, other_ordering_field: str
+ ):
+ saved_metric_uuids: list[str] = []
+ saved_metric_ids: list[int] = []
+ for index in range(2):
+ 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",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ },
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ saved_metric_ids.append(response.json()["id"])
+ saved_metric_uuids.append(response.json()["query"]["uuid"])
+
+ experiment_response = self.client.post(
f"/api/projects/{self.team.id}/experiments/",
{
"allow_unknown_events": True,
- "name": "Test Experiment",
- "feature_flag_key": "test-create-secondary",
- "parameters": None,
- "metrics_secondary": [
- {
- "uuid": metric_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- }
+ "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"]
- # Should succeed and the UUID should be in the secondary ordering
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertIn(metric_uuid, response.json()["secondary_metrics_ordered_uuids"])
+ logs_before = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()
- def test_create_auto_syncs_ordering_for_saved_metrics(self):
- """Test that creating an experiment with saved metrics auto-populates ordering"""
- saved_metric_response = self.client.post(
- f"/api/projects/{self.team.id}/experiment_saved_metrics/",
+ # A removal sends no ordering: the stale entries match nothing and are ignored on read.
+ 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}/",
{
- "name": "Test Saved Metric",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
+ inline_metrics_field: [],
+ "saved_metrics_ids": [],
},
format="json",
)
- self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)
- saved_metric_id = saved_metric_response.json()["id"]
- saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
+ self.assertEqual(remove_response.status_code, status.HTTP_200_OK)
- # Create experiment with saved metric but no ordering
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
- {
- "name": "Test Experiment",
- "feature_flag_key": "test-create-saved-metric",
- "parameters": None,
- "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "primary"}}],
- },
- format="json",
+ experiment = Experiment.objects.get(id=experiment_id)
+ self.assertEqual(getattr(experiment, ordering_field), saved_metric_uuids)
+
+ # 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")
- # Should succeed and the saved metric UUID should be in the ordering
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertIn(saved_metric_uuid, response.json()["primary_metrics_ordered_uuids"])
+ # 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_create_auto_syncs_ordering_for_mixed_metrics(self):
- """Test that creating an experiment with both inline and saved metrics auto-populates ordering"""
- inline_uuid = "create-mixed-inline-uuid"
+ def test_cannot_add_saved_metric_from_different_team(self):
+ team_b = Team.objects.create(organization=self.organization, name="Team B")
+ # Create a saved metric in team A (self.team)
saved_metric_response = self.client.post(
f"/api/projects/{self.team.id}/experiment_saved_metrics/",
{
- "name": "Test Saved Metric",
+ "name": "Team A Metric",
+ "description": "This metric belongs to Team A",
"query": {
"kind": "ExperimentMetric",
"metric_type": "funnel",
@@ -8668,35 +8011,34 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
},
format="json",
)
- saved_metric_id = saved_metric_response.json()["id"]
- saved_metric_uuid = saved_metric_response.json()["query"]["uuid"]
+ self.assertEqual(saved_metric_response.status_code, status.HTTP_201_CREATED)
+ team_a_metric_id = saved_metric_response.json()["id"]
- # Create experiment with both inline and saved metrics, no ordering
- response = self.client.post(
- f"/api/projects/{self.team.id}/experiments/",
+ # Create an experiment in team B
+ experiment_response = self.client.post(
+ f"/api/projects/{team_b.id}/experiments/",
{
- "allow_unknown_events": True,
- "name": "Test Experiment",
- "feature_flag_key": "test-create-mixed",
+ "name": "Team B Experiment",
+ "feature_flag_key": "team-b-flag",
"parameters": None,
- "metrics": [
- {
- "uuid": inline_uuid,
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "series": [{"kind": "EventsNode", "event": "$pageleave"}],
- }
- ],
- "saved_metrics_ids": [{"id": saved_metric_id, "metadata": {"type": "primary"}}],
+ },
+ format="json",
+ )
+ self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)
+ team_b_experiment_id = experiment_response.json()["id"]
+
+ # Try to add Team A's saved metric to Team B's experiment
+ # This should fail with validation error
+ update_response = self.client.patch(
+ f"/api/projects/{team_b.id}/experiments/{team_b_experiment_id}/",
+ {
+ "saved_metrics_ids": [{"id": team_a_metric_id, "metadata": {"type": "primary"}}],
},
format="json",
)
- # Should succeed and both UUIDs should be in the ordering
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- ordering = response.json()["primary_metrics_ordered_uuids"]
- self.assertIn(inline_uuid, ordering)
- self.assertIn(saved_metric_uuid, ordering)
+ self.assertEqual(update_response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("does not exist or does not belong to this project", str(update_response.json()))
class TestExperimentParametersFieldMutation(APILicensedTest):
@@ -9699,10 +9041,6 @@ class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(stale_delete.status_code, status.HTTP_200_OK, stale_delete.json())
result = stale_delete.json()
self.assertEqual(self._events(result["metrics_secondary"]), {"e2", "e3", "e4", "e5", "e6", "e7"})
- self.assertEqual(
- set(result["secondary_metrics_ordered_uuids"]),
- {metric["uuid"] for metric in result["metrics_secondary"]},
- )
def test_concurrent_additions_of_different_metrics_both_survive(self) -> None:
snapshot = self._create_experiment("both-add", metrics=[self._metric("base")])
@@ -9957,11 +9295,10 @@ class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(result["parameters"]["variant_notes"], {"control": "baseline notes"})
self.assertEqual(result["running_time_calculation"]["recommended_running_time"], 9)
- def test_stale_reorder_keeps_relative_order_and_appends_concurrent_addition(self) -> None:
+ def test_stale_reorder_is_stored_as_sent_and_keeps_the_concurrent_addition(self) -> None:
snapshot = self._create_experiment("reorder", metrics=[self._metric("m1"), self._metric("m2")])
added = self._patch(snapshot["id"], {"metrics": [*snapshot["metrics"], self._metric("m3")]})
self.assertEqual(added.status_code, status.HTTP_200_OK)
- added_uuid = next(m["uuid"] for m in added.json()["metrics"] if m["source"]["event"] == "m3")
uuid_1, uuid_2 = (metric["uuid"] for metric in snapshot["metrics"])
stale_reorder = self._patch(
@@ -9975,7 +9312,9 @@ class TestExperimentConcurrency(_HoistFlagConfigClientMixin, APILicensedTest):
)
self.assertEqual(stale_reorder.status_code, status.HTTP_200_OK, stale_reorder.json())
- self.assertEqual(stale_reorder.json()["primary_metrics_ordered_uuids"], [uuid_2, uuid_1, added_uuid])
+ # The ordering is a display hint, so the unlisted m3 renders last without an entry.
+ self.assertEqual(stale_reorder.json()["primary_metrics_ordered_uuids"], [uuid_2, uuid_1])
+ self.assertEqual(self._events(stale_reorder.json()["metrics"]), {"m1", "m2", "m3"})
def test_stale_shared_metric_removal_keeps_concurrently_linked_metric(self) -> None:
saved_1 = ExperimentSavedMetric.objects.create(
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 80f2abe0ea14..f30663a4d789 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1601,8 +1601,16 @@ export interface ExperimentWriteApi {
* @nullable
*/
repository?: string | null
- primary_metrics_ordered_uuids?: unknown
- secondary_metrics_ordered_uuids?: unknown
+ /**
+ * Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ primary_metrics_ordered_uuids?: string[] | null
+ /**
+ * Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ secondary_metrics_ordered_uuids?: string[] | null
only_count_matured_users?: boolean
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean
@@ -1744,8 +1752,16 @@ export interface ExperimentApi {
* @nullable
*/
repository?: string | null
- primary_metrics_ordered_uuids?: unknown
- secondary_metrics_ordered_uuids?: unknown
+ /**
+ * Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ primary_metrics_ordered_uuids?: string[] | null
+ /**
+ * Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ secondary_metrics_ordered_uuids?: string[] | null
only_count_matured_users?: boolean
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean
@@ -1883,8 +1899,16 @@ export interface PatchedExperimentWriteApi {
* @nullable
*/
repository?: string | null
- primary_metrics_ordered_uuids?: unknown
- secondary_metrics_ordered_uuids?: unknown
+ /**
+ * Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ primary_metrics_ordered_uuids?: string[] | null
+ /**
+ * Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ secondary_metrics_ordered_uuids?: string[] | null
only_count_matured_users?: boolean
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean
diff --git a/products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic.ts b/products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic.ts
index e3906b808d62..d17d367cff29 100644
--- a/products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic.ts
+++ b/products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic.ts
@@ -9,12 +9,10 @@ export const METRIC_CONTEXTS = {
primary: {
type: 'primary' as const,
field: 'metrics' as const,
- orderingField: 'primary_metrics_ordered_uuids' as const,
},
secondary: {
type: 'secondary' as const,
field: 'metrics_secondary' as const,
- orderingField: 'secondary_metrics_ordered_uuids' as const,
},
} as const
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4497cb55fcbb..dc50a0a88300 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40428,8 +40428,16 @@ export namespace Schemas {
* @nullable
*/
repository?: string | null;
- primary_metrics_ordered_uuids?: unknown;
- secondary_metrics_ordered_uuids?: unknown;
+ /**
+ * Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ primary_metrics_ordered_uuids?: string[] | null;
+ /**
+ * Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ secondary_metrics_ordered_uuids?: string[] | null;
only_count_matured_users?: boolean;
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean;
@@ -42368,8 +42376,16 @@ export namespace Schemas {
* @nullable
*/
repository?: string | null;
- primary_metrics_ordered_uuids?: unknown;
- secondary_metrics_ordered_uuids?: unknown;
+ /**
+ * Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ primary_metrics_ordered_uuids?: string[] | null;
+ /**
+ * Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ secondary_metrics_ordered_uuids?: string[] | null;
only_count_matured_users?: boolean;
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean;
@@ -73143,8 +73159,16 @@ export namespace Schemas {
* @nullable
*/
repository?: string | null;
- primary_metrics_ordered_uuids?: unknown;
- secondary_metrics_ordered_uuids?: unknown;
+ /**
+ * Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ primary_metrics_ordered_uuids?: string[] | null;
+ /**
+ * Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.
+ * @nullable
+ */
+ secondary_metrics_ordered_uuids?: string[] | null;
only_count_matured_users?: boolean;
/** When true, sync the flag config sent in this request (via the `feature_flag` object) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */
update_feature_flag_params?: boolean;
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index c546e090162a..de5f282b8958 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -6714,8 +6714,18 @@ export const ExperimentsCreateBody = () => zod
.describe(
"GitHub repository holding this experiment's feature-flag code, in `organization\/repository` format. Used as the target of the flag-cleanup pull request opened via open_cleanup_pr on end\/ship_variant. When not set, cleanup targets the team's only connected repository and is skipped if the team has several."
),
- primary_metrics_ordered_uuids: zod.unknown().optional(),
- secondary_metrics_ordered_uuids: zod.unknown().optional(),
+ primary_metrics_ordered_uuids: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.'
+ ),
+ secondary_metrics_ordered_uuids: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.'
+ ),
only_count_matured_users: zod.boolean().optional(),
update_feature_flag_params: zod
.boolean()
@@ -12685,8 +12695,18 @@ export const ExperimentsPartialUpdateBody = () => zod
.describe(
"GitHub repository holding this experiment's feature-flag code, in `organization\/repository` format. Used as the target of the flag-cleanup pull request opened via open_cleanup_pr on end\/ship_variant. When not set, cleanup targets the team's only connected repository and is skipped if the team has several."
),
- primary_metrics_ordered_uuids: zod.unknown().optional(),
- secondary_metrics_ordered_uuids: zod.unknown().optional(),
+ primary_metrics_ordered_uuids: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.'
+ ),
+ secondary_metrics_ordered_uuids: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.'
+ ),
only_count_matured_users: zod.boolean().optional(),
update_feature_flag_params: zod
.boolean()
@@ -18627,8 +18647,18 @@ export const ExperimentsDuplicateCreateBody = () => zod
.describe(
"GitHub repository holding this experiment's feature-flag code, in `organization\/repository` format. Used as the target of the flag-cleanup pull request opened via open_cleanup_pr on end\/ship_variant. When not set, cleanup targets the team's only connected repository and is skipped if the team has several."
),
- primary_metrics_ordered_uuids: zod.unknown().optional(),
- secondary_metrics_ordered_uuids: zod.unknown().optional(),
+ primary_metrics_ordered_uuids: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Display order of the primary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.'
+ ),
+ secondary_metrics_ordered_uuids: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Display order of the secondary metrics, as metric uuids. This is a display hint only: a metric not in the list renders after the listed ones in stored order, and an entry that matches no metric is ignored. Send it only to reorder metrics. Adding or removing metrics does not need it.'
+ ),
only_count_matured_users: zod.boolean().optional(),
update_feature_flag_params: zod
.boolean()