: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): add retry actions on failing recalculations (#97129)
Rodrigo Iloroafb279e8393d
diff --git a/posthog/templates/admin/posthog/experiment/change_form.html b/posthog/templates/admin/posthog/experiment/change_form.htmlindex 9d5e68a0e2bc..ac61a5d037d6 100644--- a/posthog/templates/admin/posthog/experiment/change_form.html+++ b/posthog/templates/admin/posthog/experiment/change_form.html@@ -88,4 +88,7 @@{% endif %}</div>{% endif %}+ {% if original %}+ {% include "admin/experiments/_recalculation_panel.html" with panel=recalculation_panel %}+ {% endif %}{% endblock %}diff --git a/products/experiments/backend/admin/experiment_admin.py b/products/experiments/backend/admin/experiment_admin.pyindex 03d852f2896f..fad32f1d3435 100644--- a/products/experiments/backend/admin/experiment_admin.py+++ b/products/experiments/backend/admin/experiment_admin.py@@ -10,12 +10,14 @@ from django.utils.html import format_htmlfrom posthog.models.utils import convert_legacy_metricsfrom products.cohorts.backend.models.cohort import Cohort+from products.experiments.backend.admin.recalculation_panel import build_recalculation_panelfrom products.experiments.backend.models.experiment import (Experiment,ExperimentHoldout,ExperimentSavedMetric,ExperimentToSavedMetric,)+from products.experiments.backend.recalculation import get_latest_recalculationfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -229,6 +231,11 @@ class ExperimentAdmin(admin.ModelAdmin):extra_context["show_migration"] = has_legacy_metric(all_metrics) or has_legacy_shared_metricextra_context["can_migrate"] = not has_unmigrated_legacy_shared_metric+ latest_recalculation = get_latest_recalculation(obj)+ extra_context["recalculation_panel"] = (+ build_recalculation_panel(latest_recalculation) if latest_recalculation is not None else None+ )+return super().change_view(request, object_id, form_url, extra_context=extra_context)def get_urls(self):diff --git a/products/experiments/backend/admin/recalculation_admin.py b/products/experiments/backend/admin/recalculation_admin.pyindex e26abaa4e432..698bca47e7a3 100644--- a/products/experiments/backend/admin/recalculation_admin.py+++ b/products/experiments/backend/admin/recalculation_admin.py@@ -1,4 +1,3 @@-from django.conf import settingsfrom django.contrib import admin, messagesfrom django.core.exceptions import PermissionDeniedfrom django.db.models import QuerySet@@ -7,12 +6,12 @@ from django.urls import path, reversefrom django.utils import timezonefrom django.utils.html import format_html-from products.experiments.backend.models.experiment import ExperimentMetricsRecalculation-from products.experiments.backend.recalculation import (- cancel_recalculation_workflow,- request_recalculation,- start_metrics_recalculation_workflow,+from products.experiments.backend.admin.recalculation_panel import (+ start_recalculation_for_experiment,+ temporal_workflow_url,)+from products.experiments.backend.models.experiment import ExperimentMetricsRecalculation+from products.experiments.backend.recalculation import cancel_recalculation_workflow_TERMINAL_STATUSES = {ExperimentMetricsRecalculation.Status.COMPLETED,@@ -20,15 +19,6 @@ _TERMINAL_STATUSES = {}-def temporal_workflow_url(recalculation_id: str) -> str:- """Link to the recalc's Temporal Cloud workflow. Uses the runtime namespace (e.g. posthog-prod-us.usz2o),- so it resolves per region without hardcoding a slug."""- return (- f"https://cloud.temporal.io/namespaces/{settings.TEMPORAL_NAMESPACE}"- f"/workflows/experiment-metrics-recalculation-{recalculation_id}"- )--@admin.register(ExperimentMetricsRecalculation)class ExperimentMetricsRecalculationAdmin(admin.ModelAdmin):list_display = (@@ -126,6 +116,11 @@ class ExperimentMetricsRecalculationAdmin(admin.ModelAdmin):self.admin_site.admin_view(self.start_recalculation_view),name="experiments_recalculation_start",),+ path(+ "<path:object_id>/retry-failures/",+ self.admin_site.admin_view(self.retry_failures_view),+ name="experiments_recalculation_retry_failures",+ ),]return custom + urls@@ -171,38 +166,30 @@ class ExperimentMetricsRecalculationAdmin(admin.ModelAdmin):obj = self.get_object(request, object_id)if obj is None:return HttpResponseRedirect(reverse("admin:experiments_experimentmetricsrecalculation_changelist"))+ change_url = reverse("admin:experiments_experimentmetricsrecalculation_change", args=[obj.pk])+ # A full recalculation of every metric: advances the window to now.+ return self._dispatch_recalculation(+ request, obj, change_url, trigger=ExperimentMetricsRecalculation.Trigger.MANUAL+ )++ def retry_failures_view(self, request: HttpRequest, object_id: str) -> HttpResponseRedirect:+ obj = self.get_object(request, object_id)+ if obj is None:+ return HttpResponseRedirect(reverse("admin:experiments_experimentmetricsrecalculation_changelist"))+ change_url = reverse("admin:experiments_experimentmetricsrecalculation_change", args=[obj.pk])+ # A metric-scoped change reuses the latest terminal run's window, so metrics that already succeeded+ # hit the (experiment, metric, query_to, fingerprint) cache and only the failed ones recompute.+ return self._dispatch_recalculation(+ request, obj, change_url, trigger=ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE+ )+ def _dispatch_recalculation(+ self, request: HttpRequest, obj: ExperimentMetricsRecalculation, change_url: str, *, trigger: str+ ) -> HttpResponseRedirect:if not self.has_change_permission(request, obj):raise PermissionDenied- change_url = reverse("admin:experiments_experimentmetricsrecalculation_change", args=[obj.pk])if request.method != "POST":return HttpResponseRedirect(change_url)- experiment = obj.experiment- try:- result = request_recalculation(experiment, request.user, trigger="manual")- except Exception as e:- messages.error(request, f"Could not create recalculation: {e}")- return HttpResponseRedirect(change_url)-- if result.get("is_existing"):- messages.info(request, "An active recalculation already exists for this experiment; reused it.")- return HttpResponseRedirect(change_url)-- recalculation_id = str(result["id"])- try:- start_metrics_recalculation_workflow(recalculation_id, str(experiment.team.organization_id))- except Exception as e:- # Roll the fresh row back to FAILED so a workflow that never started isn't left pending forever.- ExperimentMetricsRecalculation.objects.for_team(experiment.team_id).filter(id=recalculation_id).update(- status=ExperimentMetricsRecalculation.Status.FAILED- )- messages.error(request, f"Created the row but failed to start the workflow (marked failed): {e}")- return HttpResponseRedirect(change_url)-- new_change_url = reverse("admin:experiments_experimentmetricsrecalculation_change", args=[recalculation_id])- messages.success(- request, format_html('Started new recalculation <a href="{}">{}</a>.', new_change_url, recalculation_id)- )- return HttpResponseRedirect(new_change_url)+ return start_recalculation_for_experiment(request, obj.experiment, trigger=trigger, fallback_url=change_url)diff --git a/products/experiments/backend/admin/recalculation_panel.py b/products/experiments/backend/admin/recalculation_panel.pynew file mode 100644index 000000000000..4d902bc2f687--- /dev/null+++ b/products/experiments/backend/admin/recalculation_panel.py@@ -0,0 +1,176 @@+"""Shared read helpers for the admin "latest recalculation" panel.++Both the Experiment change page and the ExperimentMetricsRecalculation change page render the same+summary: run status, timing, and a table of per-metric failures with the message a user sees on the+experiment page. Keeping the shaping here means both admin classes stay thin and the failure-resolution+order stays in one place, matching the frontend resolver in experimentMetricsLogic.ts.+"""++from datetime import datetime+from typing import cast++from django.conf import settings+from django.contrib import messages+from django.http import HttpRequest, HttpResponseRedirect+from django.urls import reverse+from django.utils.html import format_html++from posthog.models.user import User++from products.experiments.backend.metric_events import _default_metric_title+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.experiments.backend.recalculation import (+ _derive_counters,+ get_run_results,+ request_recalculation,+ start_metrics_recalculation_workflow,+)+from products.experiments.backend.temporal.metric_resolution import build_metric, find_metric_dict+++def format_duration(started_at: datetime | None, completed_at: datetime | None) -> str | None:+ """Human-friendly run duration, e.g. "4m 10s" or "45s". None when either bound is missing."""+ if started_at is None or completed_at is None:+ return None+ total_seconds = int((completed_at - started_at).total_seconds())+ if total_seconds < 0:+ return None+ hours, remainder = divmod(total_seconds, 3600)+ minutes, seconds = divmod(remainder, 60)+ parts = []+ if hours:+ parts.append(f"{hours}h")+ if minutes:+ parts.append(f"{minutes}m")+ # Always show seconds so a sub-minute run reads as "45s" rather than an empty string.+ if seconds or not parts:+ parts.append(f"{seconds}s")+ return " ".join(parts)+++def _metric_name(experiment: Experiment, metric_uuid: str) -> str:+ """Resolve a metric_uuid to the title a user sees, falling back to the uuid for a metric that no+ longer resolves on the experiment (removed after the run)."""+ metric_dict = find_metric_dict(experiment, metric_uuid)+ if metric_dict is None:+ return metric_uuid+ if metric_dict.get("name"):+ return metric_dict["name"]+ try:+ return _default_metric_title(build_metric(metric_dict)) or metric_uuid+ except Exception:+ return metric_uuid+++def _resolve_failures(recalc: ExperimentMetricsRecalculation, results: list[dict]) -> list[dict]:+ """Per-metric failures as {metric_uuid, metric_name, error}, matching the frontend resolver:+ metric_errors wins (it covers discovery-step failures absent from results), then a FAILED result+ row's error_message.+ """+ metric_errors = recalc.metric_errors or {}+ failed_row_message = {+ row["metric_uuid"]: row["error_message"]+ for row in results+ if row["status"] == ExperimentMetricResult.Status.FAILED and row["error_message"]+ }++ # Union of every uuid that failed either way, so a discovery-step failure with no result row still shows.+ failed_uuids = set(metric_errors.keys()) | set(failed_row_message.keys())+ failures = []+ for metric_uuid in failed_uuids:+ error = None+ entry = metric_errors.get(metric_uuid)+ if isinstance(entry, dict):+ error = entry.get("message")+ error = error or failed_row_message.get(metric_uuid)+ if not error:+ continue+ failures.append(+ {+ "metric_uuid": metric_uuid,+ "metric_name": _metric_name(recalc.experiment, metric_uuid),+ "error": error,+ }+ )+ failures.sort(key=lambda f: f["metric_name"].lower())+ return failures+++def temporal_workflow_url(recalculation_id: str) -> str:+ """Link to the recalc's Temporal Cloud workflow. Uses the runtime namespace (e.g. posthog-prod-us.usz2o),+ so it resolves per region without hardcoding a slug."""+ return (+ f"https://cloud.temporal.io/namespaces/{settings.TEMPORAL_NAMESPACE}"+ f"/workflows/experiment-metrics-recalculation-{recalculation_id}"+ )+++def build_recalculation_panel(recalc: ExperimentMetricsRecalculation) -> dict:+ """Shape one recalculation row for the admin panel: status, timing, human duration, failures table,+ and the links the template renders (all recalculations, Temporal workflow, retry)."""+ results = get_run_results(recalc)+ completed_metrics, failed_metrics = _derive_counters(recalc, results=results)+ failures = _resolve_failures(recalc, results)++ all_recalculations_url = (+ reverse("admin:experiments_experimentmetricsrecalculation_changelist")+ + f"?experiment__id__exact={recalc.experiment_id}"+ )++ return {+ "id": str(recalc.id),+ "status": recalc.get_status_display(),+ "trigger": recalc.get_trigger_display(),+ "total_metrics": recalc.total_metrics,+ "completed_metrics": completed_metrics,+ "failed_metrics": failed_metrics,+ "started_at": recalc.started_at,+ "completed_at": recalc.completed_at,+ "duration_human": format_duration(recalc.started_at, recalc.completed_at),+ "failures": failures,+ "has_failures": bool(failures),+ "all_recalculations_url": all_recalculations_url,+ "temporal_url": temporal_workflow_url(str(recalc.id)),+ "retry_url": reverse("admin:experiments_recalculation_retry_failures", args=[recalc.pk]),+ }+++def start_recalculation_for_experiment(+ request: HttpRequest, experiment: Experiment, *, trigger: str, fallback_url: str+) -> HttpResponseRedirect:+ """Create a recalculation and dispatch its workflow, then redirect to the new run's change page.++ Shared by every admin action that starts a run (start new, retry failures). Mirrors the API's create ++ start path: an active run already existing returns is_existing and reuses it; a workflow that fails to+ start rolls the fresh row back to FAILED so it is never left pending forever.+ """+ try:+ # admin_view gates these callers to staff, so request.user is always a real User, not AnonymousUser.+ result = request_recalculation(experiment, cast(User, request.user), trigger=trigger)+ except Exception as e:+ messages.error(request, f"Could not create recalculation: {e}")+ return HttpResponseRedirect(fallback_url)++ if result.get("is_existing"):+ messages.info(request, "An active recalculation already exists for this experiment; reused it.")+ return HttpResponseRedirect(fallback_url)++ recalculation_id = str(result["id"])+ try:+ start_metrics_recalculation_workflow(recalculation_id, str(experiment.team.organization_id))+ except Exception as e:+ ExperimentMetricsRecalculation.objects.for_team(experiment.team_id).filter(id=recalculation_id).update(+ status=ExperimentMetricsRecalculation.Status.FAILED+ )+ messages.error(request, f"Created the row but failed to start the workflow (marked failed): {e}")+ return HttpResponseRedirect(fallback_url)++ new_change_url = reverse("admin:experiments_experimentmetricsrecalculation_change", args=[recalculation_id])+ messages.success(+ request, format_html('Started new recalculation <a href="{}">{}</a>.', new_change_url, recalculation_id)+ )+ return HttpResponseRedirect(new_change_url)diff --git a/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html b/products/experiments/backend/templates/admin/experiments/_recalculation_panel.htmlnew file mode 100644index 000000000000..7f357db98d21--- /dev/null+++ b/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html@@ -0,0 +1,85 @@+{% load i18n %}+<fieldset style="margin: 20px 0;+ padding: 16px;+ border: 1px solid #ccc;+ border-radius: 4px">+ <h2>Latest recalculation</h2>+ {% if panel %}+ <table style="margin: 8px 0 16px; border-collapse: collapse;">+ <tbody>+ <tr>+ <th style="text-align: left; padding: 2px 16px 2px 0;">Status</th>+ <td>{{ panel.status }} <span style="color: #666;">({{ panel.trigger }})</span></td>+ </tr>+ <tr>+ <th style="text-align: left; padding: 2px 16px 2px 0;">Metrics</th>+ <td>{{ panel.completed_metrics }} completed, {{ panel.failed_metrics }} failed of {{ panel.total_metrics }}</td>+ </tr>+ <tr>+ <th style="text-align: left; padding: 2px 16px 2px 0;">Started</th>+ <td>{{ panel.started_at|default:"—" }}</td>+ </tr>+ <tr>+ <th style="text-align: left; padding: 2px 16px 2px 0;">Ended</th>+ <td>{{ panel.completed_at|default:"—" }}</td>+ </tr>+ <tr>+ <th style="text-align: left; padding: 2px 16px 2px 0;">Execution time</th>+ <td>{{ panel.duration_human|default:"—" }}</td>+ </tr>+ </tbody>+ </table>+ {% if panel.has_failures %}+ <h3 style="margin: 8px 0;">Failures</h3>+ <table style="border-collapse: collapse; width: 100%; max-width: 900px;">+ <thead>+ <tr>+ <th style="text-align: left;+ padding: 6px 12px;+ border-bottom: 1px solid #ccc">Metric</th>+ <th style="text-align: left;+ padding: 6px 12px;+ border-bottom: 1px solid #ccc">Error</th>+ </tr>+ </thead>+ <tbody>+ {% for failure in panel.failures %}+ <tr>+ <td style="padding: 6px 12px;+ border-bottom: 1px solid #eee;+ vertical-align: top">{{ failure.metric_name }}</td>+ <td style="padding: 6px 12px;+ border-bottom: 1px solid #eee;+ white-space: pre-wrap">{{ failure.error }}</td>+ </tr>+ {% endfor %}+ </tbody>+ </table>+ {% endif %}+ <div style="margin-top: 12px;+ display: flex;+ gap: 8px;+ align-items: center;+ flex-wrap: wrap">+ {% if panel.has_failures %}+ <button type="submit"+ formaction="{{ panel.retry_url }}"+ formmethod="post"+ formnovalidate+ class="button"+ style="padding: 8px 14px;+ background: #417690">Retry latest failures</button>+ {% endif %}+ <a href="{{ panel.all_recalculations_url }}"+ class="button"+ style="padding: 8px 14px">All recalculations</a>+ <a href="{{ panel.temporal_url }}"+ target="_blank"+ rel="noopener"+ class="button"+ style="padding: 8px 14px">Temporal workflow</a>+ </div>+ {% else %}+ <p style="color: #666; margin: 4px 0;">No recalculation has run for this experiment yet.</p>+ {% endif %}+</fieldset>diff --git a/products/experiments/backend/test/test_recalculation_admin.py b/products/experiments/backend/test/test_recalculation_admin.pynew file mode 100644index 000000000000..8f5ae2dca967--- /dev/null+++ b/products/experiments/backend/test/test_recalculation_admin.py@@ -0,0 +1,199 @@+from datetime import UTC, datetime, timedelta++import pytest+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.contrib.admin.sites import AdminSite+from django.contrib.messages.storage.fallback import FallbackStorage+from django.contrib.sessions.backends.cache import SessionStore+from django.core.exceptions import PermissionDenied+from django.test import RequestFactory++from parameterized import parameterized++from products.experiments.backend.admin.recalculation_admin import ExperimentMetricsRecalculationAdmin+from products.experiments.backend.admin.recalculation_panel import build_recalculation_panel, format_duration+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.experiments.backend.recalculation import _recalc_fingerprints_for_run+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _mean_metric(uuid: str, name: str | None = None) -> dict:+ metric: dict = {+ "uuid": uuid,+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ if name is not None:+ metric["name"] = name+ return metric+++_BASE = datetime(2026, 1, 1, tzinfo=UTC)+++class TestFormatDuration:+ @parameterized.expand(+ [+ ("sub_minute", 45, "45s"),+ ("minutes_and_seconds", 250, "4m 10s"),+ ("exact_minute_drops_seconds", 120, "2m"),+ ("zero_reads_as_seconds", 0, "0s"),+ ("hours", 3661, "1h 1m 1s"),+ ]+ )+ def test_formats_elapsed(self, _name: str, elapsed_seconds: int, expected: str) -> None:+ assert format_duration(_BASE, _BASE + timedelta(seconds=elapsed_seconds)) == expected++ @parameterized.expand([("missing_start", None, _BASE), ("missing_end", _BASE, None)])+ def test_missing_bound_is_none(self, _name: str, started: datetime | None, completed: datetime | None) -> None:+ assert format_duration(started, completed) is None++ def test_negative_duration_is_none(self) -> None:+ assert format_duration(_BASE + timedelta(seconds=10), _BASE) is None++[email protected]_db(transaction=True)+class TestRecalculationAdminPanel(BaseTest):+ def _launched_experiment(self) -> Experiment:+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="admin-panel-flag",+ name="Flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ exp = Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ feature_flag=flag,+ name="exp",+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ )+ exp.metrics = [_mean_metric("m-named", name="Signups"), _mean_metric("m-discovery")]+ exp.save()+ return exp++ def test_failures_prefer_metric_errors_and_include_discovery_only(self) -> None:+ exp = self._launched_experiment()+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ status=ExperimentMetricsRecalculation.Status.FAILED,+ total_metrics=2,+ metric_uuids=["m-named", "m-discovery"],+ # m-discovery failed in discovery (no result row); m-named has a metric_errors entry that must+ # win over any result-row message.+ metric_errors={+ "m-named": {"message": "row-level query failed"},+ "m-discovery": {"message": "metric could not be resolved"},+ },+ started_at=datetime(2026, 1, 2, 10, 0, 0, tzinfo=UTC),+ completed_at=datetime(2026, 1, 2, 10, 4, 10, tzinfo=UTC),+ )++ panel = build_recalculation_panel(recalc)++ assert panel["has_failures"] is True+ assert panel["duration_human"] == "4m 10s"+ by_uuid = {f["metric_uuid"]: f for f in panel["failures"]}+ # metric_errors message wins, and a named metric shows its name not its uuid.+ assert by_uuid["m-named"]["error"] == "row-level query failed"+ assert by_uuid["m-named"]["metric_name"] == "Signups"+ # a discovery-only failure with no result row is still surfaced.+ assert by_uuid["m-discovery"]["error"] == "metric could not be resolved"++ def test_failure_falls_back_to_result_row_message(self) -> None:+ exp = self._launched_experiment()+ query_to = datetime(2026, 1, 2, 10, 0, 0, tzinfo=UTC)+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ status=ExperimentMetricsRecalculation.Status.FAILED,+ total_metrics=2,+ metric_uuids=["m-named"],+ metric_errors={},+ query_to=query_to,+ started_at=datetime(2026, 1, 2, 10, 0, 0, tzinfo=UTC),+ completed_at=datetime(2026, 1, 2, 10, 0, 30, tzinfo=UTC),+ )+ # No metric_errors entry, so the failure text comes from the FAILED result row's error_message.+ fingerprints = _recalc_fingerprints_for_run(exp, recalc)+ ExperimentMetricResult.objects.create(+ experiment=exp,+ metric_uuid="m-named",+ fingerprint=fingerprints["m-named"],+ query_from=datetime(2026, 1, 1, tzinfo=UTC),+ query_to=query_to,+ status=ExperimentMetricResult.Status.FAILED,+ error_message="timeout in ClickHouse",+ )++ panel = build_recalculation_panel(recalc)++ by_uuid = {f["metric_uuid"]: f for f in panel["failures"]}+ assert by_uuid["m-named"]["error"] == "timeout in ClickHouse"++ @patch("products.experiments.backend.admin.recalculation_panel.start_metrics_recalculation_workflow")+ def test_retry_failures_reuses_window_and_redirects_to_new_run(self, mock_start: MagicMock) -> None:+ exp = self._launched_experiment()+ prior = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ status=ExperimentMetricsRecalculation.Status.FAILED,+ total_metrics=2,+ metric_uuids=["m-named", "m-discovery"],+ metric_errors={"m-discovery": {"message": "boom"}},+ started_at=datetime(2026, 1, 2, 10, 0, 0, tzinfo=UTC),+ completed_at=datetime(2026, 1, 2, 10, 4, 10, tzinfo=UTC),+ )++ admin = ExperimentMetricsRecalculationAdmin(ExperimentMetricsRecalculation, AdminSite())+ request = RequestFactory().post("/")+ request.user = self.user+ # A bare RequestFactory request has no message store; the success path calls messages.success.+ request.session = SessionStore()+ request._messages = FallbackStorage(request) # type: ignore[attr-defined]+ with patch.object(admin, "has_change_permission", return_value=True):+ response = admin.retry_failures_view(request, str(prior.pk))++ # A metric-scoped trigger reuses the prior window, so only failed metrics recompute.+ new_run = (+ ExperimentMetricsRecalculation.objects.filter(experiment=exp)+ .exclude(pk=prior.pk)+ .order_by("-created_at")+ .first()+ )+ assert new_run is not None+ assert new_run.trigger == ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE+ assert str(new_run.pk) in response.url+ mock_start.assert_called_once()++ @patch("products.experiments.backend.admin.recalculation_panel.start_metrics_recalculation_workflow")+ def test_retry_failures_denied_without_change_permission(self, mock_start: MagicMock) -> None:+ exp = self._launched_experiment()+ prior = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ status=ExperimentMetricsRecalculation.Status.FAILED,+ total_metrics=1,+ metric_uuids=["m-named"],+ metric_errors={"m-named": {"message": "boom"}},+ started_at=datetime(2026, 1, 2, 10, 0, 0, tzinfo=UTC),+ completed_at=datetime(2026, 1, 2, 10, 4, 10, tzinfo=UTC),+ )++ admin = ExperimentMetricsRecalculationAdmin(ExperimentMetricsRecalculation, AdminSite())+ request = RequestFactory().post("/")+ request.user = self.user+ with patch.object(admin, "has_change_permission", return_value=False), pytest.raises(PermissionDenied):+ admin.retry_failures_view(request, str(prior.pk))++ assert not ExperimentMetricsRecalculation.objects.filter(experiment=exp).exclude(pk=prior.pk).exists()+ mock_start.assert_not_called()