:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): metric recalculation service and endpoints (#61530)
Rodrigo Iloro9aabeb560ce5
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 47afcb178ae1..6f927a31dab4 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -45,6 +45,7 @@ from products.experiments.backend.models.experiment import (holdout_filters_for_flag,)from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.experiments.backend.result_serialization import strip_step_sessionsfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -72,29 +73,6 @@ DEFAULT_VARIANTS = []-def _strip_step_sessions(result: Any) -> Any:- """Remove the per-session funnel actors payload from a stored experiment metric result.-- `step_sessions` powers the frontend's "view sessions per step" affordance off- a separate per-metric query, not this timeseries endpoint. Carrying it through- here multiplies the response by sessions × steps × variants and pushes MCP- consumers past their context window with no benefit.- """- if not isinstance(result, Mapping):- return result- cleaned = {k: v for k, v in result.items() if k != "step_sessions"}- baseline = cleaned.get("baseline")- if isinstance(baseline, dict):- cleaned["baseline"] = {k: v for k, v in baseline.items() if k != "step_sessions"}- variants = cleaned.get("variant_results")- if isinstance(variants, list):- cleaned["variant_results"] = [- {k: v for k, v in variant.items() if k != "step_sessions"} if isinstance(variant, dict) else variant- for variant in variants- ]- return cleaned--class ExperimentQueryStatus(str, Enum):"""Filter values for the experiment list endpoint.@@ -2721,7 +2699,7 @@ class ExperimentService:metric_result = results_by_date[experiment_date]if metric_result.status == "completed":- timeseries[date_key] = _strip_step_sessions(metric_result.result)+ timeseries[date_key] = strip_step_sessions(metric_result.result)completed_count += 1elif metric_result.status == "failed":if metric_result.error_message:diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 03b928e310be..3c13585f4d65 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -632,6 +632,38 @@ class CreateFromPromptInputSerializer(serializers.Serializer):return attrs+class MetricRecalculationResultSerializer(serializers.Serializer):+ """One metric's recalculated result row, read back from ExperimentMetricResult."""++ metric_uuid = serializers.CharField(read_only=True, help_text="UUID of the metric this result belongs to")+ status = serializers.ChoiceField(+ choices=["pending", "completed", "failed"],+ read_only=True,+ help_text="Status of this metric's calculation in the run",+ )+ # JSONField mirrors the ExperimentMetricResult.result column; concrete shape comes from+ # posthog.schema.ExperimentQueryResponse (variants/baseline/credible intervals/etc., depending on metric type).+ result = serializers.JSONField(+ read_only=True,+ allow_null=True,+ help_text="The computed metric result (ExperimentQueryResponse shape); null when status is pending or failed",+ )+ error_message = serializers.CharField(+ read_only=True, allow_null=True, help_text="Error message when status is failed; otherwise null"+ )+++class RecalculateMetricsRequestSerializer(serializers.Serializer):+ """Request body for triggering a metrics recalculation."""++ trigger = serializers.ChoiceField(+ choices=["manual", "experiment_launch", "experiment_stop", "experiment_update"],+ required=False,+ default="manual",+ help_text="What triggered this recalculation (manual is the default for user-initiated runs)",+ )++class ExperimentMetricsRecalculationSerializer(serializers.Serializer):"""Serializer for metrics recalculation status responses."""@@ -643,6 +675,17 @@ class ExperimentMetricsRecalculationSerializer(serializers.Serializer):help_text="Current status of the recalculation job",)total_metrics = serializers.IntegerField(read_only=True, help_text="Total number of metrics to recalculate")+ completed_metrics = serializers.IntegerField(+ read_only=True,+ help_text="Number of metrics with a COMPLETED result row in this run (derived, not stored)",+ )+ failed_metrics = serializers.IntegerField(+ read_only=True,+ help_text=(+ "Number of failed metrics in this run (derived): FAILED result rows plus discovery-step failures "+ "that never made it to a result row"+ ),+ )# Named metric_errors (not errors) to avoid shadowing DRF's reserved Serializer.errors property.metric_errors = serializers.JSONField(read_only=True, help_text="Map of metric_uuid to error details")trigger = serializers.ChoiceField(@@ -656,3 +699,11 @@ class ExperimentMetricsRecalculationSerializer(serializers.Serializer):is_existing = serializers.BooleanField(read_only=True, required=False, help_text="True if returning an existing job rather than a newly created one")+ # Populated by the GET endpoints (latest / by-id). Omitted from the POST response payload (which doesn't carry+ # per-metric results yet — the workflow has just started).+ results = MetricRecalculationResultSerializer(+ many=True,+ read_only=True,+ required=False,+ help_text="Per-metric results computed by this run, scoped by the run's recalc fingerprint",+ )diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 69dca7dfa123..f939513d6486 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -43,6 +43,7 @@ from products.experiments.backend.llm_metric_templates import build_template, li# TODO: Route through facade instead of direct importfrom products.experiments.backend.models.experiment import (Experiment,+ ExperimentMetricsRecalculation,ExperimentTimeseriesRecalculation,experiment_has_legacy_metrics,)@@ -50,9 +51,21 @@ from products.experiments.backend.presentation.serializers import (CopyExperimentToProjectSerializer,CreateFromPromptInputSerializer,EndExperimentSerializer,+ ExperimentMetricsRecalculationSerializer,ExperimentSerializer,+ RecalculateMetricsRequestSerializer,ShipVariantSerializer,)+from products.experiments.backend.recalculation import (+ build_job_payload,+ get_latest_recalculation,+ get_recalculation_by_id,+ get_run_results,+ request_recalculation,+)+from products.experiments.backend.temporal.models import (+ ExperimentMetricsRecalculationWorkflowInputs as MetricsRecalcInputs,+)from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -787,7 +800,9 @@ class EnterpriseExperimentsViewSet())except Exception:- ExperimentTimeseriesRecalculation.objects.filter(id=recalculation_id).update(+ # team-scoped filter: defense in depth so the rollback can never reach across teams even if+ # recalculation_id were ever sourced from somewhere less trusted than the row we just created.+ ExperimentTimeseriesRecalculation.objects.filter(team=self.team, id=recalculation_id).update(status=ExperimentTimeseriesRecalculation.Status.FAILED)raise@@ -795,7 +810,109 @@ class EnterpriseExperimentsViewSet(status_code = 200 if is_existing else 201return Response(result, status=status_code)+ @extend_schema(+ request=RecalculateMetricsRequestSerializer,+ responses={+ 200: ExperimentMetricsRecalculationSerializer,+ 201: ExperimentMetricsRecalculationSerializer,+ },+ )+ @action(+ methods=["POST"],+ detail=True,+ url_path="metrics_recalculation",+ required_scopes=["experiment:write"],+ )+ def metrics_recalculation(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Trigger a batch recalculation of all metrics for this experiment.++ Returns 201 with the new pending recalculation, or 200 with the active one if a recalculation is+ already pending or in progress for this experiment. The response payload intentionally does not+ include the `results` array — at POST time the workflow has just been queued and no per-metric+ results exist yet. Clients should poll `GET metrics_recalculation/{id}/` for results as the workflow+ progresses.+ """+ experiment: Experiment = self.get_object()+ request_serializer = RecalculateMetricsRequestSerializer(data=request.data)+ request_serializer.is_valid(raise_exception=True)+ trigger = request_serializer.validated_data["trigger"]++ # request.user is User | AnonymousUser at the DRF level; the viewset enforces auth so it's a User here.+ result = request_recalculation(experiment, cast(User, request.user), trigger)+ # Read without mutating — the serializer surfaces is_existing on the response so clients can detect+ # the idempotent-reuse path without inspecting the HTTP status code.+ is_existing = result.get("is_existing", False)++ if not is_existing:+ recalculation_id = str(result["id"])+ try:+ temporal = sync_connect()+ asyncio.run(+ temporal.start_workflow(+ "experiment-metrics-recalculation-workflow",+ MetricsRecalcInputs(recalculation_id=recalculation_id),+ id=f"experiment-metrics-recalculation-{recalculation_id}",+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ )+ )+ except Exception:+ # team-scoped filter: defense in depth so the rollback can never reach across teams even if+ # recalculation_id were ever sourced from somewhere less trusted than the row we just created.+ ExperimentMetricsRecalculation.objects.filter(team=self.team, id=recalculation_id).update(+ status=ExperimentMetricsRecalculation.Status.FAILED+ )+ raise++ return Response(+ ExperimentMetricsRecalculationSerializer(result).data,+ status=200 if is_existing else 201,+ )++ @extend_schema(responses={200: ExperimentMetricsRecalculationSerializer, 404: None})+ @action(+ methods=["GET"],+ detail=True,+ # NOTE: this action is declared BEFORE the by-id action so its URL pattern wins on /latest/.+ url_path="metrics_recalculation/latest",+ required_scopes=["experiment:read"],+ )+ def metrics_recalculation_latest(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ experiment: Experiment = self.get_object()+ recalc = get_latest_recalculation(experiment)+ if recalc is None:+ return Response({"detail": "No completed recalculation found"}, status=404)+ return Response(_serialize_recalculation(recalc))++ @extend_schema(responses={200: ExperimentMetricsRecalculationSerializer, 404: None})+ @action(+ methods=["GET"],+ detail=True,+ # Strict UUID regex so 'latest' (the sibling action above) never matches this route.+ url_path=r"metrics_recalculation/(?P<recalculation_id>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})",+ required_scopes=["experiment:read"],+ )+ def metrics_recalculation_detail(+ self, request: Request, recalculation_id: str, *args: Any, **kwargs: Any+ ) -> Response:+ experiment: Experiment = self.get_object()+ recalc = get_recalculation_by_id(experiment, recalculation_id)+ if recalc is None:+ return Response({"detail": "Recalculation not found"}, status=404)+ return Response(_serialize_recalculation(recalc))+@action(methods=["GET"], detail=False, url_path="stats", required_scopes=["experiment:read"])def stats(self, request: Request, **kwargs: Any) -> Response:service = ExperimentService(team=self.team, user=request.user)return Response(service.get_velocity_stats())+++def _serialize_recalculation(recalc: ExperimentMetricsRecalculation) -> dict:+ """Shape an ExperimentMetricsRecalculation row + its per-run results for the GET responses.++ Computes the per-run results once and threads them into both the derived counters and the response+ `results` field — recomputing per-metric fingerprints once per request is enough.+ """+ results = get_run_results(recalc)+ payload = build_job_payload(recalc, results=results)+ payload["results"] = results+ return ExperimentMetricsRecalculationSerializer(payload).datadiff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pynew file mode 100644index 000000000000..55ce932022bd--- /dev/null+++ b/products/experiments/backend/recalculation.py@@ -0,0 +1,247 @@+"""Service layer for experiment metrics recalculation.++Module-level free functions (not methods on ExperimentService) so the API view can compose them directly:++- ``request_recalculation`` — idempotent create: returns the active run if one exists, else creates a pending job.+- ``get_latest_recalculation`` — most recent recalc row for an experiment, or ``None``.+- ``get_run_results`` — read-back of per-metric results for a specific run, scoped by recomputing each metric's+ per-run recalc fingerprint (no FK on ExperimentMetricResult; the scoping key lives entirely on the job row ++ the run id).+"""++from datetime import timedelta+from uuid import UUID++from django.db import transaction+from django.db.models import Q+from django.utils import timezone++from rest_framework.exceptions import ValidationError++from posthog.models.scoping import team_scope+from posthog.models.user import User++from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.experiments.backend.result_serialization import strip_step_sessions+from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint+from products.experiments.backend.temporal.recalculation_logic import discover_metrics_for_experiment, find_metric_dict++# How long an active (PENDING/IN_PROGRESS) row blocks new recalculations. Beyond this, the row is treated as+# stale and a fresh recalc is allowed. Sized to be safely above the workflow's worst-case end-to-end runtime+# (discovery retries + per-metric calc retries + progress activities) so a legitimately-slow run can finish+# without being clobbered, but tight enough that an operator can recover within an hour if the workflow+# never started (Temporal connect failure, transient infra issue, etc.). See the rollback in views.py for the+# happy-path failure handling; this TTL is the defense-in-depth backstop if that rollback itself fails.+_STALE_RECALC_THRESHOLD = timedelta(minutes=30)+++def _derive_counters(recalc: ExperimentMetricsRecalculation, results: list[dict] | None = None) -> tuple[int, int]:+ """Counters are not stored on the row (PR1 contract): they're derived on read from result rows + errors.++ `completed_metrics` = ExperimentMetricResult rows with status=COMPLETED for this run's fingerprints.+ `failed_metrics` = ExperimentMetricResult rows with status=FAILED + metric_errors keys that never made+ it to a result row (discovery-step failures).++ Accepts an optional pre-computed `results` list to avoid recomputing fingerprints on the GET path where+ the same list is also surfaced to the client.++ Inherits the fingerprint-divergence hazard from `get_run_results`: `completed_metrics` can silently drop+ if experiment fields that feed the fingerprint (start_date, exposure_criteria, stats method,+ only_count_matured_users) change between the workflow's writes and this read. `failed_metrics` is partly+ immune because discovery-step failures come from `metric_errors` (stored on the row), not from result rows.+ """+ rows = results if results is not None else get_run_results(recalc)+ completed = sum(1 for r in rows if r["status"] == ExperimentMetricResult.Status.COMPLETED)+ failed_in_rows = sum(1 for r in rows if r["status"] == ExperimentMetricResult.Status.FAILED)+ uuids_with_row = {r["metric_uuid"] for r in rows}+ discovery_only_failures = sum(1 for uuid in (recalc.metric_errors or {}) if uuid not in uuids_with_row)+ return completed, failed_in_rows + discovery_only_failures+++def build_job_payload(+ recalc: ExperimentMetricsRecalculation,+ *,+ is_existing: bool | None = None,+ results: list[dict] | None = None,+) -> dict:+ """Shape a recalc row + derived counters as a dict the serializer can re-serialize.++ Returns model-native values (datetimes, ints, dicts) — DRF handles the wire format. The POST path passes+ `is_existing` to signal whether the workflow needs starting; the GET paths pass `results` so the same row+ list backs both the derived counters and the response's `results` field (no duplicate fingerprint work).+ """+ completed_metrics, failed_metrics = _derive_counters(recalc, results=results)+ payload: dict = {+ "id": str(recalc.id),+ "experiment_id": recalc.experiment_id,+ "status": recalc.status,+ "total_metrics": recalc.total_metrics,+ "completed_metrics": completed_metrics,+ "failed_metrics": failed_metrics,+ "metric_errors": recalc.metric_errors,+ "trigger": recalc.trigger,+ "created_at": recalc.created_at,+ "started_at": recalc.started_at,+ "completed_at": recalc.completed_at,+ }+ if is_existing is not None:+ payload["is_existing"] = is_existing+ return payload+++def request_recalculation(experiment: Experiment, user: User, trigger: str = "manual") -> dict:+ """Create an idempotent batch recalculation request for all experiment metrics.++ If an active (pending or in_progress) run already exists for this experiment, returns the existing run's+ serialized payload with ``is_existing=True`` — the caller should NOT start a new workflow in that case.+ Otherwise creates a fresh pending row.+ """+ if not experiment.is_launched:+ raise ValidationError("Cannot recalculate metrics for experiment that hasn't started")++ with team_scope(experiment.team_id, canonical=True), transaction.atomic():+ # Serialize concurrent POSTs for this experiment by locking the Experiment row up front. Without this,+ # two simultaneous POSTs (double-click, retry storm, two tabs) both see no active recalc row and both+ # reach .create(); the second hits the unique_active_metrics_recalculation_per_experiment constraint+ # and returns HTTP 500. Locking the Experiment row queues the second POST behind the first, which+ # then sees the freshly-created row in its lookup and returns is_existing=True cleanly.+ Experiment.objects.select_for_update().filter(id=experiment.id).first()++ # Activity-aware staleness: PENDING rows anchor on created_at (workflow never reached its start+ # activity); IN_PROGRESS rows anchor on started_at (workflow began executing then stalled). A row past+ # the threshold is treated as dead and skipped, so a fresh recalc can start. Without this, a PENDING+ # row left orphaned by a Temporal-connect failure that also lost its rollback UPDATE would permanently+ # lock the experiment out of recalculations.+ threshold = timezone.now() - _STALE_RECALC_THRESHOLD+ existing = (+ ExperimentMetricsRecalculation.objects.filter(experiment=experiment)+ .filter(+ Q(status=ExperimentMetricsRecalculation.Status.PENDING, created_at__gte=threshold)+ | Q(status=ExperimentMetricsRecalculation.Status.IN_PROGRESS, started_at__gte=threshold)+ )+ .first()+ )+ if existing:+ return build_job_payload(existing, is_existing=True)++ # No fresh active row, but stale tombstones might still hold the per-experiment uniqueness constraint+ # (unique_active_metrics_recalculation_per_experiment). Mark them FAILED so the constraint releases+ # and the new row can land. Status reflects reality — these workflows are not coming back.+ ExperimentMetricsRecalculation.objects.filter(+ experiment=experiment,+ status__in=[+ ExperimentMetricsRecalculation.Status.PENDING,+ ExperimentMetricsRecalculation.Status.IN_PROGRESS,+ ],+ ).update(status=ExperimentMetricsRecalculation.Status.FAILED, completed_at=timezone.now())++ # Set total_metrics up front from the experiment definition so the client can show progress+ # ("N of M") immediately, before the workflow's discovery activity confirms the same count.+ metrics = discover_metrics_for_experiment(experiment)+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=experiment.team,+ experiment=experiment,+ trigger=trigger,+ status=ExperimentMetricsRecalculation.Status.PENDING,+ created_by=user,+ total_metrics=len(metrics),+ metric_uuids=[m.metric_uuid for m in metrics],+ )+ return build_job_payload(recalc, is_existing=False)+++def get_latest_recalculation(experiment: Experiment) -> ExperimentMetricsRecalculation | None:+ """Most recent successfully-completed recalculation for an experiment, or None.++ Powers ``GET /metrics_recalculation/latest``: the frontend renders cached results from the last good run.+ Runs that are pending/in_progress/failed are NOT returned — the client tracks those separately by id.+ """+ with team_scope(experiment.team_id, canonical=True):+ return (+ ExperimentMetricsRecalculation.objects.filter(+ team=experiment.team,+ experiment=experiment,+ status=ExperimentMetricsRecalculation.Status.COMPLETED,+ )+ .order_by("-created_at")+ .first()+ )+++def get_recalculation_by_id(experiment: Experiment, recalculation_id: str) -> ExperimentMetricsRecalculation | None:+ """Return the recalculation row for ``recalculation_id`` if it belongs to ``experiment``, else None.++ Enforces experiment scoping so the id-based GET cannot leak rows from a different experiment in the same team.+ Returns None for a malformed UUID rather than raising, so the calling view can answer with a clean 404.+ """+ try:+ uuid_value = UUID(recalculation_id)+ except (ValueError, TypeError):+ return None+ with team_scope(experiment.team_id, canonical=True):+ return ExperimentMetricsRecalculation.objects.filter(+ team=experiment.team, experiment=experiment, id=uuid_value+ ).first()+++def _recalc_fingerprints_for_run(experiment: Experiment, recalc: ExperimentMetricsRecalculation) -> dict[str, str]:+ """Recompute each metric's per-run recalc fingerprint (strategy 'a': no extra storage).++ Returns ``{metric_uuid: recalc_fp}`` for metrics still resolvable on the experiment. A uuid present on the job+ but no longer on the experiment is skipped (metric removed mid-run).++ Divergence hazard: the fingerprint is derived from mutable experiment fields (start_date, exposure_criteria,+ stats method, only_count_matured_users). If any of these change between the workflow's writes and a later+ read, the recomputed fingerprints will not match the on-disk ones and the corresponding result rows become+ unreachable (until the experiment fields revert). This is the explicit trade-off of "no FK on+ ExperimentMetricResult" — the snapshot lives in the fingerprint, not in a stored column.+ """+ stats_method = get_experiment_stats_method(experiment)+ fingerprints: dict[str, str] = {}+ for metric_uuid in recalc.metric_uuids or []:+ metric_dict = find_metric_dict(experiment, metric_uuid)+ if metric_dict is None:+ continue+ config_fp = compute_metric_fingerprint(+ metric_dict,+ experiment.start_date,+ stats_method,+ experiment.exposure_criteria,+ only_count_matured_users=experiment.only_count_matured_users,+ )+ fingerprints[metric_uuid] = compute_recalc_fingerprint(config_fp, str(recalc.id))+ return fingerprints+++def get_run_results(recalc: ExperimentMetricsRecalculation) -> list[dict]:+ """Return the ExperimentMetricResult rows that belong to THIS run.++ Scopes by recomputing each metric's recalc fingerprint and filtering ``fingerprint__in`` — never returns+ rows from a previous run or from the timeseries workflow (which uses config fingerprints).++ See `_recalc_fingerprints_for_run` for the fingerprint-divergence hazard: if experiment fields that feed+ the fingerprint change after the run wrote its rows, this can return [] for what is on-disk a successful+ run. Symptom: "results disappeared after editing exposure_criteria / start_date / stats config."+ """+ fingerprints = _recalc_fingerprints_for_run(recalc.experiment, recalc)+ if not fingerprints:+ return []++ rows = ExperimentMetricResult.objects.filter(+ experiment=recalc.experiment, fingerprint__in=list(fingerprints.values())+ )+ return [+ {+ "metric_uuid": row.metric_uuid,+ "status": row.status,+ "result": strip_step_sessions(row.result),+ "error_message": row.error_message,+ }+ for row in rows+ ]diff --git a/products/experiments/backend/result_serialization.py b/products/experiments/backend/result_serialization.pynew file mode 100644index 000000000000..a191a381f19f--- /dev/null+++ b/products/experiments/backend/result_serialization.py@@ -0,0 +1,27 @@+"""Shared helpers for shaping ExperimentMetricResult payloads before they leave the backend."""++from collections.abc import Mapping+from typing import Any+++def strip_step_sessions(result: Any) -> Any:+ """Remove the per-session funnel actors payload from a stored experiment metric result.++ `step_sessions` powers the frontend's "view sessions per step" affordance off+ a separate per-metric query, not this timeseries endpoint. Carrying it through+ here multiplies the response by sessions × steps × variants and pushes MCP+ consumers past their context window with no benefit.+ """+ if not isinstance(result, Mapping):+ return result+ cleaned = {k: v for k, v in result.items() if k != "step_sessions"}+ baseline = cleaned.get("baseline")+ if isinstance(baseline, dict):+ cleaned["baseline"] = {k: v for k, v in baseline.items() if k != "step_sessions"}+ variants = cleaned.get("variant_results")+ if isinstance(variants, list):+ cleaned["variant_results"] = [+ {k: v for k, v in variant.items() if k != "step_sessions"} if isinstance(variant, dict) else variant+ for variant in variants+ ]+ return cleaneddiff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 8fabd2cb8e46..eb7ae52e79e5 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -88,6 +88,44 @@ def _get_recalc_state(recalculation_id: str) -> _RecalcState:)+def discover_metrics_for_experiment(experiment: Experiment) -> list[ExperimentMetricToRecalculate]:+ """Traverse the experiment definition and return the list of metrics a recalc should process.++ Pure read of the experiment object — no database writes, no scoping concerns. The activity wrapper+ (`_discover_experiment_metrics_sync`) loads + scopes + persists `metric_uuids`; the service layer can+ call this directly when it already has the experiment in scope (e.g., to seed `total_metrics` at create+ time so the client can show progress without waiting for the workflow's discovery activity to run).++ Named `discover_metrics_for_experiment` (not `discover_experiment_metrics`) to avoid colliding with the+ Temporal activity of the same shape in `recalculation_activities.py`, which takes a `recalculation_id`+ instead of an Experiment.+ """+ metrics_to_recalculate: list[ExperimentMetricToRecalculate] = []++ def _add(metric_uuid: str | None, metric_type: str) -> None:+ if metric_uuid:+ metrics_to_recalculate.append(+ ExperimentMetricToRecalculate(+ experiment_id=experiment.id, metric_uuid=metric_uuid, metric_type=metric_type+ )+ )++ # Inline metrics carry their uuid directly on the dict; the metric_type is the source list.+ for source, metric_type in [(experiment.metrics, "primary"), (experiment.metrics_secondary, "secondary")]:+ for metric in source or []:+ _add(metric.get("uuid"), metric_type)++ # Saved (shared) metrics live in the M2M through-model: uuid is on saved_metric.query["uuid"], and+ # primary/secondary is recorded on the link's metadata["type"] (default "primary").+ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():+ saved_query = link.saved_metric.query+ metric_uuid = saved_query.get("uuid") if saved_query else None+ metric_type = link.metadata.get("type", "primary") if link.metadata else "primary"+ _add(metric_uuid, metric_type)++ return metrics_to_recalculate++@database_sync_to_asyncdef _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:close_old_connections()@@ -97,28 +135,7 @@ def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentMrecalculation = ExperimentMetricsRecalculation.objects.select_related("experiment").get(id=recalculation_id)experiment = recalculation.experiment- metrics_to_recalculate: list[ExperimentMetricToRecalculate] = []-- def _add(metric_uuid: str | None, metric_type: str) -> None:- if metric_uuid:- metrics_to_recalculate.append(- ExperimentMetricToRecalculate(- experiment_id=experiment.id, metric_uuid=metric_uuid, metric_type=metric_type- )- )-- # Inline metrics carry their uuid directly on the dict; the metric_type is the source list.- for source, metric_type in [(experiment.metrics, "primary"), (experiment.metrics_secondary, "secondary")]:- for metric in source or []:- _add(metric.get("uuid"), metric_type)-- # Saved (shared) metrics live in the M2M through-model: uuid is on saved_metric.query["uuid"], and- # primary/secondary is recorded on the link's metadata["type"] (default "primary").- for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():- saved_query = link.saved_metric.query- metric_uuid = saved_query.get("uuid") if saved_query else None- metric_type = link.metadata.get("type", "primary") if link.metadata else "primary"- _add(metric_uuid, metric_type)+ metrics_to_recalculate = discover_metrics_for_experiment(experiment)recalculation.metric_uuids = [m.metric_uuid for m in metrics_to_recalculate]recalculation.save(update_fields=["metric_uuids"])diff --git a/products/experiments/backend/test/conftest.py b/products/experiments/backend/test/conftest.pynew file mode 100644index 000000000000..906e978e3ac3--- /dev/null+++ b/products/experiments/backend/test/conftest.py@@ -0,0 +1,20 @@+import pytest++from posthog.models.scoping import team_scope++[email protected](autouse=True)+def _enter_team_scope(request):+ """Open team_scope around every test that exposes self.team (BaseTest / APIBaseTest subclasses).++ Tests without self.team get a no-op fixture; they don't hit the fail-closed ORM manager on+ ExperimentMetricsRecalculation. (The django_db marker check that the temporal-package conftest uses+ doesn't apply here — APIBaseTest is unittest-style via DRFTestCase, not a pytest-marked function.)+ """+ instance = getattr(request.node, "instance", None)+ team = getattr(instance, "team", None) if instance is not None else None+ if team is None:+ yield+ return+ with team_scope(team.id, canonical=True):+ yielddiff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.pynew file mode 100644index 000000000000..2a48e62e6728--- /dev/null+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py@@ -0,0 +1,197 @@+from datetime import UTC, datetime++from posthog.test.base import APIBaseTest+from unittest import mock++from parameterized import parameterized+from rest_framework import status++from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _mean_metric(uuid: str) -> dict:+ return {+ "uuid": uuid,+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+++class TestMetricsRecalculationAPI(APIBaseTest):+ def _flag(self, key: str) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=key,+ name=f"Flag for {key}",+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ },+ )++ def _launched_experiment(self, flag_key: str = "api-flag") -> Experiment:+ exp = Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ feature_flag=self._flag(flag_key),+ name="exp",+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ )+ exp.metrics = [_mean_metric("m1")]+ exp.save()+ return exp++ def _post_url(self, exp_id: int) -> str:+ return f"/api/projects/{self.team.id}/experiments/{exp_id}/metrics_recalculation/"++ def _latest_url(self, exp_id: int) -> str:+ return f"/api/projects/{self.team.id}/experiments/{exp_id}/metrics_recalculation/latest/"++ def _by_id_url(self, exp_id: int, recalc_id: str) -> str:+ return f"/api/projects/{self.team.id}/experiments/{exp_id}/metrics_recalculation/{recalc_id}/"++ # ------------------------------------------------------------------+ # POST /metrics_recalculation/+ # ------------------------------------------------------------------++ @mock.patch("products.experiments.backend.presentation.views.sync_connect")+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")+ def test_post_creates_and_starts_workflow(self, mock_run, mock_connect):+ exp = self._launched_experiment()+ resp = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")+ assert resp.status_code == status.HTTP_201_CREATED, resp.content+ body = resp.json()+ assert body["status"] == "pending"+ assert body["trigger"] == "manual"+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1+ assert mock_run.called++ @mock.patch("products.experiments.backend.presentation.views.sync_connect")+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")+ def test_post_is_idempotent_returns_200(self, mock_run, mock_connect):+ exp = self._launched_experiment()+ first = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")+ assert first.status_code == status.HTTP_201_CREATED+ second = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")+ assert second.status_code == status.HTTP_200_OK+ assert second.json()["id"] == first.json()["id"]+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1++ @mock.patch("products.experiments.backend.presentation.views.sync_connect")+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")+ def test_post_rejects_unlaunched_experiment(self, mock_run, mock_connect):+ exp = Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=self._flag("unlaunched"), name="draft"+ )+ resp = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ @mock.patch(+ "products.experiments.backend.presentation.views.sync_connect", side_effect=RuntimeError("temporal down")+ )+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")+ def test_post_marks_failed_when_workflow_start_errors(self, mock_run, mock_connect):+ # When the workflow start fails, the view marks the freshly-created row FAILED then re-raises.+ # The DRF test client converts the exception into a 500 response rather than propagating it.+ exp = self._launched_experiment()+ resp = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")+ assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ row = ExperimentMetricsRecalculation.objects.get(experiment=exp)+ assert row.status == ExperimentMetricsRecalculation.Status.FAILED++ # ------------------------------------------------------------------+ # GET /metrics_recalculation/latest/+ # ------------------------------------------------------------------++ def test_get_latest_404_when_no_completed_run(self):+ exp = self._launched_experiment()+ ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="pending")+ resp = self.client.get(self._latest_url(exp.id))+ assert resp.status_code == status.HTTP_404_NOT_FOUND++ def test_get_latest_returns_most_recent_completed_with_results(self):+ exp = self._launched_experiment()+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ metric_uuids=["m1"],+ status="completed",+ query_to=datetime(2026, 6, 1, tzinfo=UTC),+ )+ # Narrow nullable fields populated above. _launched_experiment always sets metrics + start_date,+ # and we just set query_to on the recalc above.+ assert exp.metrics and exp.start_date is not None+ assert recalc.query_to is not None+ config_fp = compute_metric_fingerprint(+ exp.metrics[0],+ exp.start_date,+ get_experiment_stats_method(exp),+ exp.exposure_criteria,+ only_count_matured_users=exp.only_count_matured_users,+ )+ recalc_fp = compute_recalc_fingerprint(config_fp, str(recalc.id))+ ExperimentMetricResult.objects.create(+ experiment=exp,+ metric_uuid="m1",+ fingerprint=recalc_fp,+ query_from=exp.start_date,+ query_to=recalc.query_to,+ status="completed",+ result={"ok": True},+ )++ resp = self.client.get(self._latest_url(exp.id))+ assert resp.status_code == status.HTTP_200_OK, resp.content+ body = resp.json()+ assert body["id"] == str(recalc.id)+ assert body["status"] == "completed"+ assert len(body["results"]) == 1+ assert body["results"][0]["metric_uuid"] == "m1"+ assert body["results"][0]["result"] == {"ok": True}++ # ------------------------------------------------------------------+ # GET /metrics_recalculation/{id}/+ # ------------------------------------------------------------------++ @parameterized.expand(+ [+ ("pending", "pending"),+ ("in_progress", "in_progress"),+ ("completed", "completed"),+ ("failed", "failed"),+ ]+ )+ def test_get_by_id_returns_run_of_any_status(self, name: str, run_status: str):+ exp = self._launched_experiment(flag_key=f"by-id-{name}")+ row = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status=run_status)+ resp = self.client.get(self._by_id_url(exp.id, str(row.id)))+ assert resp.status_code == status.HTTP_200_OK, resp.content+ assert resp.json()["status"] == run_status+ assert resp.json()["id"] == str(row.id)++ def test_get_by_id_404_for_unknown_id(self):+ exp = self._launched_experiment()+ resp = self.client.get(self._by_id_url(exp.id, "00000000-0000-0000-0000-000000000001"))+ assert resp.status_code == status.HTTP_404_NOT_FOUND++ def test_get_by_id_404_for_other_experiment_id(self):+ exp = self._launched_experiment(flag_key="by-id-mine")+ other = self._launched_experiment(flag_key="by-id-other")+ row = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=other, status="completed")+ resp = self.client.get(self._by_id_url(exp.id, str(row.id)))+ assert resp.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/experiments/backend/test/test_metrics_recalculation_serializer.py b/products/experiments/backend/test/test_metrics_recalculation_serializer.pyindex b53c22b12174..aa7da7c83865 100644--- a/products/experiments/backend/test/test_metrics_recalculation_serializer.py+++ b/products/experiments/backend/test/test_metrics_recalculation_serializer.py@@ -5,7 +5,11 @@ from parameterized import parameterizedfrom posthog.models.scoping import team_scopefrom products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation-from products.experiments.backend.presentation.serializers import ExperimentMetricsRecalculationSerializer+from products.experiments.backend.presentation.serializers import (+ ExperimentMetricsRecalculationSerializer,+ MetricRecalculationResultSerializer,+ RecalculateMetricsRequestSerializer,+)from products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -74,3 +78,53 @@ class TestExperimentMetricsRecalculationSerializer(BaseTest):# can't silently start emitting is_existing on payloads that never asked for it.data = ExperimentMetricsRecalculationSerializer({}).dataassert "is_existing" not in data+++class TestRecalculateMetricsRequestSerializer(BaseTest):+ def test_defaults_trigger_to_manual_when_omitted(self):+ s = RecalculateMetricsRequestSerializer(data={})+ assert s.is_valid(), s.errors+ assert s.validated_data["trigger"] == "manual"++ @parameterized.expand(+ [+ ("manual",),+ ("experiment_launch",),+ ("experiment_stop",),+ ("experiment_update",),+ ]+ )+ def test_accepts_valid_trigger(self, trigger: str):+ s = RecalculateMetricsRequestSerializer(data={"trigger": trigger})+ assert s.is_valid(), s.errors+ assert s.validated_data["trigger"] == trigger++ def test_rejects_unknown_trigger(self):+ s = RecalculateMetricsRequestSerializer(data={"trigger": "nonsense"})+ assert not s.is_valid()+ assert "trigger" in s.errors+++class TestMetricRecalculationResultSerializer(BaseTest):+ @parameterized.expand(+ [+ (+ "completed",+ {"metric_uuid": "m1", "status": "completed", "result": {"variants": []}, "error_message": None},+ ),+ (+ "failed",+ {"metric_uuid": "m2", "status": "failed", "result": None, "error_message": "boom"},+ ),+ (+ "pending",+ {"metric_uuid": "m3", "status": "pending", "result": None, "error_message": None},+ ),+ ]+ )+ def test_serializes_result_row(self, name: str, payload: dict):+ data = MetricRecalculationResultSerializer(payload).data+ assert data["metric_uuid"] == payload["metric_uuid"]+ assert data["status"] == payload["status"]+ assert data["result"] == payload["result"]+ assert data["error_message"] == payload["error_message"]diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.pynew file mode 100644index 000000000000..c29fd9aba967--- /dev/null+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -0,0 +1,306 @@+from datetime import UTC, datetime, timedelta++import pytest+from posthog.test.base import BaseTest++from django.utils import timezone++from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.experiments.backend.recalculation import (+ get_latest_recalculation,+ get_recalculation_by_id,+ get_run_results,+ request_recalculation,+)+from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _mean_metric(uuid: str) -> dict:+ return {+ "uuid": uuid,+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }++[email protected]_db(transaction=True)+class TestRecalculationService(BaseTest):+ def _flag(self, key: str) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=key,+ name=f"Flag for {key}",+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ },+ )++ def _launched_experiment(self, flag_key: str = "svc-flag") -> Experiment:+ exp = Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ feature_flag=self._flag(flag_key),+ name="exp",+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ )+ exp.metrics = [_mean_metric("m1")]+ exp.save()+ return exp++ def test_request_recalculation_creates_pending(self):+ exp = self._launched_experiment()+ result = request_recalculation(exp, self.user, "manual")+ assert result["status"] == "pending"+ assert result["is_existing"] is False+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1++ def test_request_recalculation_is_idempotent(self):+ exp = self._launched_experiment()+ first = request_recalculation(exp, self.user, "manual")+ second = request_recalculation(exp, self.user, "manual")+ assert second["is_existing"] is True+ assert second["id"] == first["id"]+ # Only one job row was created across both calls.+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1++ @parameterized.expand(+ [+ # (name, status, stale_field) — both lifecycle anchors must release the experiment when their+ # respective timestamp is past the staleness threshold. Without this, a Temporal-connect failure+ # that also lost its rollback UPDATE permanently locks the experiment out of recalculations.+ ("pending_stale_by_created_at", "pending", "created_at"),+ ("in_progress_stale_by_started_at", "in_progress", "started_at"),+ ]+ )+ def test_request_recalculation_recovers_from_stale_active_row(self, name: str, status: str, stale_field: str):+ exp = self._launched_experiment(flag_key=f"stale-{name}")+ long_ago = timezone.now() - timedelta(hours=2)+ stale_kwargs: dict = {"team": self.team, "experiment": exp, "status": status}+ if stale_field == "created_at":+ # created_at uses auto_now_add so we have to update after create.+ stale_row = ExperimentMetricsRecalculation.objects.create(**stale_kwargs)+ ExperimentMetricsRecalculation.objects.filter(id=stale_row.id).update(created_at=long_ago)+ else:+ stale_row = ExperimentMetricsRecalculation.objects.create(**stale_kwargs, started_at=long_ago)++ result = request_recalculation(exp, self.user, "manual")++ # A fresh row was created (NOT the stale one) and the stale row was marked FAILED.+ assert result["is_existing"] is False+ assert result["id"] != str(stale_row.id)+ stale_row.refresh_from_db()+ assert stale_row.status == "failed"++ def test_request_recalculation_does_not_recover_recent_active_row(self):+ # Defensive: a row created N minutes ago (well under the threshold) must still block, no matter the+ # status. This pins the threshold is doing real work and we aren't accidentally short-circuiting it.+ exp = self._launched_experiment(flag_key="recent-pending")+ recent_row = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="pending")+ result = request_recalculation(exp, self.user, "manual")+ assert result["is_existing"] is True+ assert result["id"] == str(recent_row.id)++ def test_request_recalculation_rejects_unlaunched(self):+ exp = Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=self._flag("unlaunched"), name="draft"+ )+ with pytest.raises(ValidationError):+ request_recalculation(exp, self.user, "manual")++ @parameterized.expand(+ [+ ("manual",),+ ("experiment_launch",),+ ("experiment_stop",),+ ("experiment_update",),+ ]+ )+ def test_request_recalculation_persists_trigger(self, trigger: str):+ exp = self._launched_experiment(flag_key=f"trigger-{trigger}")+ result = request_recalculation(exp, self.user, trigger)+ assert result["trigger"] == trigger+ row = ExperimentMetricsRecalculation.objects.get(id=result["id"])+ assert row.trigger == trigger++ def test_get_latest_recalculation_returns_most_recent_completed(self):+ # get_latest_recalculation filters to status='completed' (powers GET /metrics_recalculation/latest).+ exp = self._launched_experiment()+ first_done = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="completed")+ ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="failed")+ second_done = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="completed")+ # A pending run created AFTER the latest completed one must NOT be returned.+ ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="pending")+ latest = get_latest_recalculation(exp)+ assert latest is not None+ assert latest.id == second_done.id+ assert latest.id != first_done.id++ @parameterized.expand(+ [+ ("never_ran", []),+ ("only_pending", ["pending"]),+ ("only_failed", ["failed"]),+ ("only_in_progress", ["in_progress"]),+ ]+ )+ def test_get_latest_recalculation_none_when_no_completed(self, name: str, statuses: list[str]):+ exp = self._launched_experiment(flag_key=f"latest-{name}")+ for status in statuses:+ ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status=status)+ assert get_latest_recalculation(exp) is None++ def test_get_recalculation_by_id_returns_row(self):+ exp = self._launched_experiment()+ row = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="in_progress")+ result = get_recalculation_by_id(exp, str(row.id))+ assert result is not None+ assert result.id == row.id++ def test_get_recalculation_by_id_none_for_unknown_id(self):+ exp = self._launched_experiment()+ # Valid UUID format but no such row exists.+ assert get_recalculation_by_id(exp, "00000000-0000-0000-0000-000000000001") is None++ def test_get_recalculation_by_id_none_for_other_experiment(self):+ # ID belongs to a different experiment in the same team — must NOT cross experiments.+ exp = self._launched_experiment(flag_key="by-id-mine")+ other = self._launched_experiment(flag_key="by-id-other")+ row = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=other, status="completed")+ assert get_recalculation_by_id(exp, str(row.id)) is None++ def test_get_run_results_scopes_by_recalc_fingerprint(self):+ exp = self._launched_experiment()+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ metric_uuids=["m1"],+ status="completed",+ query_to=timezone.now(),+ )+ # Narrow nullable fields populated above. _launched_experiment always sets metrics + start_date,+ # and we just set query_to on the recalc above.+ assert exp.metrics and exp.start_date is not None+ assert recalc.query_to is not None+ config_fp = compute_metric_fingerprint(+ exp.metrics[0],+ exp.start_date,+ get_experiment_stats_method(exp),+ exp.exposure_criteria,+ only_count_matured_users=exp.only_count_matured_users,+ )+ recalc_fp = compute_recalc_fingerprint(config_fp, str(recalc.id))++ # The row from THIS run (recalc-fingerprinted) — must be returned.+ ExperimentMetricResult.objects.create(+ experiment=exp,+ metric_uuid="m1",+ fingerprint=recalc_fp,+ query_from=exp.start_date,+ query_to=recalc.query_to,+ status="completed",+ result={"ok": True},+ )+ # A stale row from another run / different fingerprint — must NOT be returned.+ ExperimentMetricResult.objects.create(+ experiment=exp,+ metric_uuid="m1",+ fingerprint="some-other-fingerprint",+ query_from=exp.start_date,+ query_to=datetime(2026, 4, 1, tzinfo=UTC),+ status="completed",+ result={"stale": True},+ )++ results = get_run_results(recalc)+ assert len(results) == 1+ assert results[0]["metric_uuid"] == "m1"+ assert results[0]["status"] == "completed"+ assert results[0]["result"] == {"ok": True}+ assert results[0]["error_message"] is None++ def test_get_run_results_strips_step_sessions(self):+ # step_sessions carries per-step person IDs, session IDs, and event UUIDs. It powers the frontend's+ # "view sessions per step" affordance off a separate per-metric query, so it does not belong in the+ # recalc results payload. Mirrors the same stripping the timeseries-results path applies.+ exp = self._launched_experiment()+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ metric_uuids=["m1"],+ status="completed",+ query_to=timezone.now(),+ )+ assert exp.metrics and exp.start_date is not None+ assert recalc.query_to is not None+ config_fp = compute_metric_fingerprint(+ exp.metrics[0],+ exp.start_date,+ get_experiment_stats_method(exp),+ exp.exposure_criteria,+ only_count_matured_users=exp.only_count_matured_users,+ )+ recalc_fp = compute_recalc_fingerprint(config_fp, str(recalc.id))+ ExperimentMetricResult.objects.create(+ experiment=exp,+ metric_uuid="m1",+ fingerprint=recalc_fp,+ query_from=exp.start_date,+ query_to=recalc.query_to,+ status="completed",+ result={+ "step_sessions": [["top-level-leak"]],+ "baseline": {+ "step_sessions": [["baseline-leak"]],+ "count": 42,+ },+ "variant_results": [+ {+ "key": "test",+ "step_sessions": [["variant-leak"]],+ "count": 7,+ },+ ],+ },+ )++ results = get_run_results(recalc)++ assert len(results) == 1+ result = results[0]["result"]+ assert "step_sessions" not in result+ assert "step_sessions" not in result["baseline"]+ assert result["baseline"]["count"] == 42+ assert "step_sessions" not in result["variant_results"][0]+ assert result["variant_results"][0]["count"] == 7+ assert result["variant_results"][0]["key"] == "test"++ def test_get_run_results_returns_empty_when_no_rows_yet(self):+ exp = self._launched_experiment()+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=exp, metric_uuids=["m1"], status="in_progress"+ )+ assert get_run_results(recalc) == []++ def test_get_run_results_returns_empty_when_no_metrics_persisted(self):+ # Discovery hasn't yet persisted metric_uuids onto the job.+ exp = self._launched_experiment()+ recalc = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="pending")+ assert get_run_results(recalc) == []diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 0f5b9e71d6c9..c3b0c1c1e352 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -757,6 +757,150 @@ export interface EndExperimentApi {conclusion_comment?: string | null}+/**+ * * `manual` - manual+ * * `experiment_launch` - experiment_launch+ * * `experiment_stop` - experiment_stop+ * * `experiment_update` - experiment_update+ */+export type RecalculateMetricsRequestTriggerEnumApi =+ (typeof RecalculateMetricsRequestTriggerEnumApi)[keyof typeof RecalculateMetricsRequestTriggerEnumApi]++export const RecalculateMetricsRequestTriggerEnumApi = {+ Manual: 'manual',+ ExperimentLaunch: 'experiment_launch',+ ExperimentStop: 'experiment_stop',+ ExperimentUpdate: 'experiment_update',+} as const++/**+ * Request body for triggering a metrics recalculation.+ */+export interface RecalculateMetricsRequestApi {+ /** What triggered this recalculation (manual is the default for user-initiated runs)+ *+ * * `manual` - manual+ * * `experiment_launch` - experiment_launch+ * * `experiment_stop` - experiment_stop+ * * `experiment_update` - experiment_update */+ trigger?: RecalculateMetricsRequestTriggerEnumApi+}++/**+ * * `pending` - Pending+ * * `in_progress` - In Progress+ * * `completed` - Completed+ * * `failed` - Failed+ */+export type ExperimentMetricsRecalculationStatusEnumApi =+ (typeof ExperimentMetricsRecalculationStatusEnumApi)[keyof typeof ExperimentMetricsRecalculationStatusEnumApi]++export const ExperimentMetricsRecalculationStatusEnumApi = {+ Pending: 'pending',+ InProgress: 'in_progress',+ Completed: 'completed',+ Failed: 'failed',+} as const++/**+ * * `manual` - Manual+ * * `experiment_launch` - Experiment Launch+ * * `experiment_stop` - Experiment Stop+ * * `experiment_update` - Experiment Update+ */+export type ExperimentMetricsRecalculationTriggerEnumApi =+ (typeof ExperimentMetricsRecalculationTriggerEnumApi)[keyof typeof ExperimentMetricsRecalculationTriggerEnumApi]++export const ExperimentMetricsRecalculationTriggerEnumApi = {+ Manual: 'manual',+ ExperimentLaunch: 'experiment_launch',+ ExperimentStop: 'experiment_stop',+ ExperimentUpdate: 'experiment_update',+} as const++/**+ * * `pending` - pending+ * * `completed` - completed+ * * `failed` - failed+ */+export type MetricRecalculationResultStatusEnumApi =+ (typeof MetricRecalculationResultStatusEnumApi)[keyof typeof MetricRecalculationResultStatusEnumApi]++export const MetricRecalculationResultStatusEnumApi = {+ Pending: 'pending',+ Completed: 'completed',+ Failed: 'failed',+} as const++/**+ * One metric's recalculated result row, read back from ExperimentMetricResult.+ */+export interface MetricRecalculationResultApi {+ /** UUID of the metric this result belongs to */+ readonly metric_uuid: string+ /** Status of this metric's calculation in the run+ *+ * * `pending` - pending+ * * `completed` - completed+ * * `failed` - failed */+ readonly status: MetricRecalculationResultStatusEnumApi+ /** The computed metric result (ExperimentQueryResponse shape); null when status is pending or failed */+ readonly result: unknown+ /**+ * Error message when status is failed; otherwise null+ * @nullable+ */+ readonly error_message: string | null+}++/**+ * Serializer for metrics recalculation status responses.+ */+export interface ExperimentMetricsRecalculationApi {+ /** Unique identifier for this recalculation job */+ readonly id: string+ /** ID of the experiment being recalculated */+ readonly experiment_id: number+ /** Current status of the recalculation job+ *+ * * `pending` - Pending+ * * `in_progress` - In Progress+ * * `completed` - Completed+ * * `failed` - Failed */+ readonly status: ExperimentMetricsRecalculationStatusEnumApi+ /** Total number of metrics to recalculate */+ readonly total_metrics: number+ /** Number of metrics with a COMPLETED result row in this run (derived, not stored) */+ readonly completed_metrics: number+ /** Number of failed metrics in this run (derived): FAILED result rows plus discovery-step failures that never made it to a result row */+ readonly failed_metrics: number+ /** Map of metric_uuid to error details */+ readonly metric_errors: unknown+ /** What triggered this recalculation+ *+ * * `manual` - Manual+ * * `experiment_launch` - Experiment Launch+ * * `experiment_stop` - Experiment Stop+ * * `experiment_update` - Experiment Update */+ readonly trigger: ExperimentMetricsRecalculationTriggerEnumApi+ /** When the job was created */+ readonly created_at: string+ /**+ * When processing started+ * @nullable+ */+ readonly started_at: string | null+ /**+ * When processing completed+ * @nullable+ */+ readonly completed_at: string | null+ /** True if returning an existing job rather than a newly created one */+ readonly is_existing: boolean+ /** Per-metric results computed by this run, scoped by the run's recalc fingerprint */+ readonly results: readonly MetricRecalculationResultApi[]+}+export interface ShipVariantApi {/** The conclusion of the experiment.*diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex bb5e68fbfbcb..b2988cf7a6ff 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -15,6 +15,7 @@ import type {ExperimentApi,ExperimentHoldoutApi,ExperimentHoldoutsListParams,+ ExperimentMetricsRecalculationApi,ExperimentSavedMetricApi,ExperimentSavedMetricsListParams,ExperimentsListParams,@@ -26,6 +27,7 @@ import type {PatchedExperimentApi,PatchedExperimentHoldoutApi,PatchedExperimentSavedMetricApi,+ RecalculateMetricsRequestApi,ShipVariantApi,} from './api.schemas'@@ -552,6 +554,88 @@ export const experimentsLaunchCreate = async (})}+export const getExperimentsMetricsRecalculationCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/metrics_recalculation/`+}++/**+ * Trigger a batch recalculation of all metrics for this experiment.+ *+ * Returns 201 with the new pending recalculation, or 200 with the active one if a recalculation is+ * already pending or in progress for this experiment. The response payload intentionally does not+ * include the `results` array — at POST time the workflow has just been queued and no per-metric+ * results exist yet. Clients should poll `GET metrics_recalculation/{id}/` for results as the workflow+ * progresses.+ */+export const experimentsMetricsRecalculationCreate = async (+ projectId: string,+ id: number,+ recalculateMetricsRequestApi?: RecalculateMetricsRequestApi,+ options?: RequestInit+): Promise<ExperimentMetricsRecalculationApi> => {+ return apiMutator<ExperimentMetricsRecalculationApi>(getExperimentsMetricsRecalculationCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(recalculateMetricsRequestApi),+ })+}++export const getExperimentsMetricsRecalculationRetrieveUrl = (+ projectId: string,+ id: number,+ recalculationId: string+) => {+ return `/api/projects/${projectId}/experiments/${id}/metrics_recalculation/${recalculationId}/`+}++/**+ * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.+ *+ * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator+ * on serializer methods and converts them into proper HTTP 409 Conflict responses with+ * change request details.+ */+export const experimentsMetricsRecalculationRetrieve = async (+ projectId: string,+ id: number,+ recalculationId: string,+ options?: RequestInit+): Promise<ExperimentMetricsRecalculationApi> => {+ return apiMutator<ExperimentMetricsRecalculationApi>(+ getExperimentsMetricsRecalculationRetrieveUrl(projectId, id, recalculationId),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getExperimentsMetricsRecalculationLatestRetrieveUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/metrics_recalculation/latest/`+}++/**+ * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.+ *+ * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator+ * on serializer methods and converts them into proper HTTP 409 Conflict responses with+ * change request details.+ */+export const experimentsMetricsRecalculationLatestRetrieve = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<ExperimentMetricsRecalculationApi> => {+ return apiMutator<ExperimentMetricsRecalculationApi>(+ getExperimentsMetricsRecalculationLatestRetrieveUrl(projectId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getExperimentsPauseCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/experiments/${id}/pause/`}diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.tsindex 62d1ec612c7c..299389dbd57d 100644--- a/products/experiments/frontend/generated/api.zod.ts+++ b/products/experiments/frontend/generated/api.zod.ts@@ -210,6 +210,31 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({conclusion_comment: zod.string().nullish().describe('Optional comment about the experiment conclusion.'),})+/**+ * Trigger a batch recalculation of all metrics for this experiment.+ *+ * Returns 201 with the new pending recalculation, or 200 with the active one if a recalculation is+ * already pending or in progress for this experiment. The response payload intentionally does not+ * include the `results` array — at POST time the workflow has just been queued and no per-metric+ * results exist yet. Clients should poll `GET metrics_recalculation/{id}/` for results as the workflow+ * progresses.+ */+export const experimentsMetricsRecalculationCreateBodyTriggerDefault = `manual`++export const ExperimentsMetricsRecalculationCreateBody = /* @__PURE__ */ zod+ .object({+ trigger: zod+ .enum(['manual', 'experiment_launch', 'experiment_stop', 'experiment_update'])+ .describe(+ '\* `manual` - manual\n\* `experiment_launch` - experiment_launch\n\* `experiment_stop` - experiment_stop\n\* `experiment_update` - experiment_update'+ )+ .default(experimentsMetricsRecalculationCreateBodyTriggerDefault)+ .describe(+ 'What triggered this recalculation (manual is the default for user-initiated runs)\n\n\* `manual` - manual\n\* `experiment_launch` - experiment_launch\n\* `experiment_stop` - experiment_stop\n\* `experiment_update` - experiment_update'+ ),+ })+ .describe('Request body for triggering a metrics recalculation.')+/*** Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.*diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 4e712086358c..3703c0fcd0a5 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -848,6 +848,15 @@ tools:experiments-eligible-feature-flags:operation: experiments_eligible_feature_flags_retrieveenabled: false+ experiments-metrics-recalculation-create:+ operation: experiments_metrics_recalculation_create+ enabled: false+ experiments-metrics-recalculation-latest-retrieve:+ operation: experiments_metrics_recalculation_latest_retrieve+ enabled: false+ experiments-metrics-recalculation-retrieve:+ operation: experiments_metrics_recalculation_retrieve+ enabled: falseexperiments-prompt-templates-retrieve:operation: experiments_prompt_templates_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c776b076b922..665d1a9c779e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18807,6 +18807,121 @@ export namespace Schemas {Boolean: 'boolean',} as const;+ /**+ * * `pending` - Pending+ * * `in_progress` - In Progress+ * * `completed` - Completed+ * * `failed` - Failed+ */+ export type ExperimentMetricsRecalculationStatusEnum = typeof ExperimentMetricsRecalculationStatusEnum[keyof typeof ExperimentMetricsRecalculationStatusEnum];+++ export const ExperimentMetricsRecalculationStatusEnum = {+ Pending: 'pending',+ InProgress: 'in_progress',+ Completed: 'completed',+ Failed: 'failed',+ } as const;++ /**+ * * `manual` - Manual+ * * `experiment_launch` - Experiment Launch+ * * `experiment_stop` - Experiment Stop+ * * `experiment_update` - Experiment Update+ */+ export type ExperimentMetricsRecalculationTriggerEnum = typeof ExperimentMetricsRecalculationTriggerEnum[keyof typeof ExperimentMetricsRecalculationTriggerEnum];+++ export const ExperimentMetricsRecalculationTriggerEnum = {+ Manual: 'manual',+ ExperimentLaunch: 'experiment_launch',+ ExperimentStop: 'experiment_stop',+ ExperimentUpdate: 'experiment_update',+ } as const;++ /**+ * * `pending` - pending+ * * `completed` - completed+ * * `failed` - failed+ */+ export type MetricRecalculationResultStatusEnum = typeof MetricRecalculationResultStatusEnum[keyof typeof MetricRecalculationResultStatusEnum];+++ export const MetricRecalculationResultStatusEnum = {+ Pending: 'pending',+ Completed: 'completed',+ Failed: 'failed',+ } as const;++ /**+ * One metric's recalculated result row, read back from ExperimentMetricResult.+ */+ export interface MetricRecalculationResult {+ /** UUID of the metric this result belongs to */+ readonly metric_uuid: string;+ /** Status of this metric's calculation in the run+ *+ * * `pending` - pending+ * * `completed` - completed+ * * `failed` - failed */+ readonly status: MetricRecalculationResultStatusEnum;+ /** The computed metric result (ExperimentQueryResponse shape); null when status is pending or failed */+ readonly result: unknown;+ /**+ * Error message when status is failed; otherwise null+ * @nullable+ */+ readonly error_message: string | null;+ }++ /**+ * Serializer for metrics recalculation status responses.+ */+ export interface ExperimentMetricsRecalculation {+ /** Unique identifier for this recalculation job */+ readonly id: string;+ /** ID of the experiment being recalculated */+ readonly experiment_id: number;+ /** Current status of the recalculation job+ *+ * * `pending` - Pending+ * * `in_progress` - In Progress+ * * `completed` - Completed+ * * `failed` - Failed */+ readonly status: ExperimentMetricsRecalculationStatusEnum;+ /** Total number of metrics to recalculate */+ readonly total_metrics: number;+ /** Number of metrics with a COMPLETED result row in this run (derived, not stored) */+ readonly completed_metrics: number;+ /** Number of failed metrics in this run (derived): FAILED result rows plus discovery-step failures that never made it to a result row */+ readonly failed_metrics: number;+ /** Map of metric_uuid to error details */+ readonly metric_errors: unknown;+ /** What triggered this recalculation+ *+ * * `manual` - Manual+ * * `experiment_launch` - Experiment Launch+ * * `experiment_stop` - Experiment Stop+ * * `experiment_update` - Experiment Update */+ readonly trigger: ExperimentMetricsRecalculationTriggerEnum;+ /** When the job was created */+ readonly created_at: string;+ /**+ * When processing started+ * @nullable+ */+ readonly started_at: string | null;+ /**+ * When processing completed+ * @nullable+ */+ readonly completed_at: string | null;+ /** True if returning an existing job rather than a newly created one */+ readonly is_existing: boolean;+ /** Per-metric results computed by this run, scoped by the run's recalc fingerprint */+ readonly results: readonly MetricRecalculationResult[];+ }+/*** Mixin for serializers to add user access control fields*/@@ -41135,6 +41250,35 @@ export namespace Schemas {suggested_integration: string | null;}+ /**+ * * `manual` - manual+ * * `experiment_launch` - experiment_launch+ * * `experiment_stop` - experiment_stop+ * * `experiment_update` - experiment_update+ */+ export type RecalculateMetricsRequestTriggerEnum = typeof RecalculateMetricsRequestTriggerEnum[keyof typeof RecalculateMetricsRequestTriggerEnum];+++ export const RecalculateMetricsRequestTriggerEnum = {+ Manual: 'manual',+ ExperimentLaunch: 'experiment_launch',+ ExperimentStop: 'experiment_stop',+ ExperimentUpdate: 'experiment_update',+ } as const;++ /**+ * Request body for triggering a metrics recalculation.+ */+ export interface RecalculateMetricsRequest {+ /** What triggered this recalculation (manual is the default for user-initiated runs)+ *+ * * `manual` - manual+ * * `experiment_launch` - experiment_launch+ * * `experiment_stop` - experiment_stop+ * * `experiment_update` - experiment_update */+ trigger?: RecalculateMetricsRequestTriggerEnum;+ }+export interface RecomputeResult {run: Run;counts_changed: boolean;