Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): admin filters and a start recalculation button (#102469)

Rodrigo Iloro83ead142c38c
diff --git a/products/experiments/backend/admin/experiment_admin.py b/products/experiments/backend/admin/experiment_admin.py
index fad32f1d3435..368831e29623 100644
--- a/products/experiments/backend/admin/experiment_admin.py
+++ b/products/experiments/backend/admin/experiment_admin.py
@@ -1,19 +1,27 @@
import copy
+from uuid import UUID
from django.contrib import admin, messages
+from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.forms import ModelForm
+from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import path, reverse
from django.utils.html import format_html
+from posthog.models.organization import Organization
from posthog.models.utils import convert_legacy_metrics
from products.cohorts.backend.models.cohort import Cohort
-from products.experiments.backend.admin.recalculation_panel import build_recalculation_panel
+from products.experiments.backend.admin.recalculation_panel import (
+ build_recalculation_panel,
+ start_recalculation_for_experiment,
+)
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentHoldout,
+ ExperimentMetricsRecalculation,
ExperimentSavedMetric,
ExperimentToSavedMetric,
)
@@ -122,6 +130,51 @@ def fix_metric_properties(metric):
return metric
+class ExperimentStatusFilter(admin.SimpleListFilter):
+ title = "status"
+ parameter_name = "status"
+
+ def lookups(self, request, model_admin):
+ return [(status.value, status.label) for status in Experiment.Status]
+
+ def queryset(self, request, queryset):
+ # Mirrors Experiment.computed_status, so rows whose stored status is still null match too.
+ match self.value():
+ case Experiment.Status.DRAFT:
+ return queryset.filter(start_date__isnull=True)
+ case Experiment.Status.RUNNING:
+ return queryset.filter(start_date__isnull=False, end_date__isnull=True)
+ case Experiment.Status.STOPPED:
+ return queryset.filter(start_date__isnull=False, end_date__isnull=False)
+ return queryset
+
+
+class OrganizationFilter(admin.SimpleListFilter):
+ # Only the organization named in the URL is offered, because a sidebar that lists every
+ # organization loads them all on each changelist render. The organization column sets the URL.
+ title = "organization"
+ parameter_name = "organization"
+
+ def _organization_id(self) -> UUID | None:
+ try:
+ return UUID(self.value() or "")
+ except ValueError:
+ return None
+
+ def lookups(self, request, model_admin):
+ organization_id = self._organization_id()
+ if organization_id is None:
+ return []
+ organization = Organization.objects.filter(pk=organization_id).only("name").first()
+ return [(str(organization_id), organization.name if organization else str(organization_id))]
+
+ def queryset(self, request, queryset):
+ organization_id = self._organization_id()
+ if organization_id is None:
+ return queryset
+ return queryset.filter(team__organization_id=organization_id)
+
+
@admin.register(Experiment)
class ExperimentAdmin(admin.ModelAdmin):
form = ExperimentAdminForm
@@ -132,11 +185,13 @@ class ExperimentAdmin(admin.ModelAdmin):
"engine",
"migrated_links",
"team_link",
+ "organization_link",
"created_at",
"created_by",
)
list_display_links = ("id", "name")
list_select_related = ("team", "team__organization")
+ list_filter = (ExperimentStatusFilter, "archived", OrganizationFilter)
search_fields = ("id", "name", "team__name", "team__organization__name")
autocomplete_fields = ("team", "created_by")
ordering = ("-created_at",)
@@ -150,6 +205,16 @@ class ExperimentAdmin(admin.ModelAdmin):
experiment.team.name,
)
+ @admin.display(description="Organization")
+ def organization_link(self, experiment: Experiment):
+ organization = experiment.team.organization
+ return format_html(
+ '<a href="{}?organization={}" title="Show only this organization\'s experiments">{}</a>',
+ reverse("admin:experiments_experiment_changelist"),
+ organization.pk,
+ organization.name,
+ )
+
@admin.display(description="Status")
def status_indicator(self, experiment: Experiment):
issues = []
@@ -235,6 +300,9 @@ class ExperimentAdmin(admin.ModelAdmin):
extra_context["recalculation_panel"] = (
build_recalculation_panel(latest_recalculation) if latest_recalculation is not None else None
)
+ # request_recalculation rejects an experiment with no start_date, so a draft gets no button.
+ extra_context["can_start_recalculation"] = obj.is_launched and self.has_change_permission(request, obj)
+ extra_context["start_recalculation_url"] = reverse("admin:experiment_start_recalculation", args=[obj.pk])
return super().change_view(request, object_id, form_url, extra_context=extra_context)
@@ -251,9 +319,32 @@ class ExperimentAdmin(admin.ModelAdmin):
self.admin_site.admin_view(self.fix_malformed_properties),
name="experiment_fix_properties",
),
+ path(
+ "<path:object_id>/start-recalculation/",
+ self.admin_site.admin_view(self.start_recalculation_view),
+ name="experiment_start_recalculation",
+ ),
]
return custom_urls + urls
+ def start_recalculation_view(self, request: HttpRequest, object_id: str) -> HttpResponseRedirect:
+ experiment = self.get_object(request, object_id)
+ if experiment is None:
+ messages.error(request, "Experiment not found")
+ return HttpResponseRedirect(reverse("admin:experiments_experiment_changelist"))
+
+ # admin_view only enforces is_staff; a view-only staff user must not be able to start a run.
+ if not self.has_change_permission(request, experiment):
+ raise PermissionDenied
+
+ change_url = reverse("admin:experiments_experiment_change", args=[experiment.pk])
+ if request.method != "POST":
+ return HttpResponseRedirect(change_url)
+
+ return start_recalculation_for_experiment(
+ request, experiment, trigger=ExperimentMetricsRecalculation.Trigger.MANUAL, fallback_url=change_url
+ )
+
def migrate_experiment(self, request, object_id):
try:
with transaction.atomic():
diff --git a/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html b/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html
index 7f357db98d21..fd83b71bd630 100644
--- a/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html
+++ b/products/experiments/backend/templates/admin/experiments/_recalculation_panel.html
@@ -61,11 +61,24 @@
gap: 8px;
align-items: center;
flex-wrap: wrap">
+ {% if can_start_recalculation %}
+ <button type="submit"
+ formaction="{{ start_recalculation_url }}"
+ formmethod="post"
+ formnovalidate
+ data-disable-on-submit
+ data-submitting-text="Starting..."
+ class="button"
+ style="padding: 8px 14px;
+ background: #417690">Start new recalculation</button>
+ {% endif %}
{% if panel.has_failures %}
<button type="submit"
formaction="{{ panel.retry_url }}"
formmethod="post"
formnovalidate
+ data-disable-on-submit
+ data-submitting-text="Retrying..."
class="button"
style="padding: 8px 14px;
background: #417690">Retry latest failures</button>
@@ -81,5 +94,29 @@
</div>
{% else %}
<p style="color: #666; margin: 4px 0;">No recalculation has run for this experiment yet.</p>
+ {% if can_start_recalculation %}
+ <button type="submit"
+ formaction="{{ start_recalculation_url }}"
+ formmethod="post"
+ formnovalidate
+ data-disable-on-submit
+ data-submitting-text="Starting..."
+ class="button"
+ style="margin-top: 8px;
+ padding: 8px 14px;
+ background: #417690">Start new recalculation</button>
+ {% endif %}
{% endif %}
</fieldset>
+<script>
+ // These buttons live inside the admin change form, so the submit event bubbles up from it.
+ // Disabling the submitter after submit starts keeps the request but blocks a second click.
+ document.addEventListener("submit", function (event) {
+ var button = event.submitter;
+ if (!button || !button.hasAttribute("data-disable-on-submit")) {
+ return;
+ }
+ button.disabled = true;
+ button.textContent = button.getAttribute("data-submitting-text") || button.textContent;
+ });
+</script>
diff --git a/products/experiments/backend/test/test_experiment_admin.py b/products/experiments/backend/test/test_experiment_admin.py
new file mode 100644
index 000000000000..e0b8b4f59756
--- /dev/null
+++ b/products/experiments/backend/test/test_experiment_admin.py
@@ -0,0 +1,81 @@
+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.test import RequestFactory
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+
+from products.experiments.backend.admin.experiment_admin import ExperimentAdmin
+from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestExperimentAdmin(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.model_admin = ExperimentAdmin(Experiment, AdminSite())
+ now = timezone.now()
+ self.draft = self._create_experiment(self.team, "draft")
+ self.running = self._create_experiment(self.team, "running", start_date=now)
+ self.stopped = self._create_experiment(self.team, "stopped", start_date=now, end_date=now)
+ other_organization = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_organization, name="other")
+ self.other_org_experiment = self._create_experiment(other_team, "elsewhere")
+
+ def _create_experiment(self, team: Team, name: str, **fields: object) -> Experiment:
+ flag = FeatureFlag.objects.create(team=team, created_by=self.user, key=f"{name}-flag", name=name)
+ return Experiment.objects.create(team=team, name=name, created_by=self.user, feature_flag=flag, **fields)
+
+ def _changelist_ids(self, params: dict[str, str]) -> set[int]:
+ request = RequestFactory().get("/admin/experiments/experiment/", params)
+ request.user = self.user
+ changelist = self.model_admin.get_changelist_instance(request)
+ return set(changelist.get_queryset(request).values_list("id", flat=True))
+
+ @parameterized.expand(
+ [
+ ("draft", "draft", {"draft", "other_org_experiment"}),
+ ("running", "running", {"running"}),
+ ("stopped", "stopped", {"stopped"}),
+ ]
+ )
+ def test_status_filter_uses_dates_not_stored_status(self, _name: str, status: str, expected: set[str]) -> None:
+ Experiment.objects.update(status=None)
+ expected_ids = {getattr(self, attr).id for attr in expected}
+ assert self._changelist_ids({"status": status}) == expected_ids
+
+ def test_organization_filter_scopes_to_one_organization(self) -> None:
+ assert self._changelist_ids({"organization": str(self.organization.id)}) == {
+ self.draft.id,
+ self.running.id,
+ self.stopped.id,
+ }
+
+ def test_organization_filter_ignores_a_value_that_is_not_a_uuid(self) -> None:
+ all_ids = {self.draft.id, self.running.id, self.stopped.id, self.other_org_experiment.id}
+ assert self._changelist_ids({"organization": "invalid"}) == all_ids
+
+ @parameterized.expand([("post_starts_manual_run", "post", True), ("get_is_a_noop", "get", False)])
+ @patch("products.experiments.backend.admin.recalculation_panel.start_metrics_recalculation_workflow")
+ def test_start_recalculation_view(self, _name: str, method: str, expects_run: bool, mock_start: MagicMock) -> None:
+ request = getattr(RequestFactory(), method)("/")
+ request.user = self.user
+ request.session = SessionStore()
+ request._messages = FallbackStorage(request)
+ with patch.object(self.model_admin, "has_change_permission", return_value=True):
+ response = self.model_admin.start_recalculation_view(request, str(self.running.pk))
+
+ run = ExperimentMetricsRecalculation.objects.unscoped().filter(experiment=self.running).first()
+ assert (run is not None) is expects_run
+ assert mock_start.called is expects_run
+ if run is not None:
+ assert run.trigger == ExperimentMetricsRecalculation.Trigger.MANUAL
+ assert str(run.pk) in response.url