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): return the latest run for manual recalculations inside five minutes (#112205)

Rodrigo Iloro33247d435034
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 8591096f2386..1670e72a4e68 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -1363,6 +1363,12 @@ class EnterpriseExperimentsViewSet(
responses={
200: ExperimentMetricsRecalculationJobSerializer,
201: ExperimentMetricsRecalculationJobSerializer,
+ 429: OpenApiResponse(
+ description=(
+ "A manual trigger arrived less than five minutes after the latest completed run finished. "
+ "Retry-After carries the seconds until the next run is allowed."
+ )
+ ),
},
)
@action(
@@ -1375,7 +1381,8 @@ class EnterpriseExperimentsViewSet(
"""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
+ already pending or in progress for this experiment. A manual trigger within five minutes after the latest
+ completed run finished returns 429 with a Retry-After header. 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.
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index 2428ac49f74e..8da3874144cc 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -15,11 +15,11 @@ from uuid import UUID
from django.conf import settings
from django.db import transaction
-from django.db.models import Q
+from django.db.models import Q, QuerySet
from django.utils import timezone
from prometheus_client import Counter
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import Throttled, ValidationError
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
@@ -55,6 +55,28 @@ from products.experiments.backend.temporal.recalculation_logic import discover_e
# backstop if that rollback itself fails.
_STALE_RECALC_THRESHOLD = timedelta(minutes=30)
+# rate limiting manual reloads (including agents).
+MIN_USER_RECALCULATION_INTERVAL = timedelta(minutes=5)
+_RATE_LIMITED_TRIGGERS = frozenset(
+ {
+ ExperimentMetricsRecalculation.Trigger.MANUAL,
+ ExperimentMetricsRecalculation.Trigger.AGENT_MCP,
+ }
+)
+
+
+class RecalculationRateLimited(Throttled):
+ """A user-driven trigger landed inside MIN_USER_RECALCULATION_INTERVAL. The API layer renders it as a 429
+ with a Retry-After header, so a client or an agent knows when the next run is allowed."""
+
+ # DRF sets this in Throttled.__init__ and its handler turns it into Retry-After; the stubs omit it.
+ wait: float | None
+
+ default_code = "recalculation_rate_limited"
+ # DRF appends "Expected available in N seconds." to this, so the wait is not repeated here.
+ default_detail = "Metrics were recalculated less than 5 minutes ago."
+
+
# A daily timeseries point older than this no longer stands in for a recalculation on the cold-start read. The
# daily run happens once per day, so a fresh experiment always has a point inside the bound.
TIMESERIES_FALLBACK_MAX_AGE = timedelta(hours=24)
@@ -65,6 +87,11 @@ _recalculation_reuse_counter = Counter(
"experiment_metrics_recalculation_existing_run_reused",
"POST requests that returned an existing active run instead of creating a new one (idempotent reuse).",
)
+# Counts user-driven POSTs that landed inside MIN_USER_RECALCULATION_INTERVAL and got the latest run back.
+_recalculation_rate_limited_counter = Counter(
+ "experiment_metrics_recalculation_rate_limited",
+ "POST requests answered with 429 because a user-driven run was requested inside the refresh window.",
+)
# Fires whenever the 30-min staleness threshold marks a PENDING/IN_PROGRESS row FAILED so the experiment
# can recalculate again. A sustained climb is a leading indicator of Temporal connect failures or the
# rollback in start_metrics_recalculation_workflow itself failing.
@@ -282,12 +309,18 @@ def _cancel_superseded_workflows(recalculation_ids: list[str]) -> None:
pass
+def _refresh_window_enforced() -> bool:
+ # Local development skips the window so a developer can reload at will. Tests keep it, because they assert it.
+ return not settings.DEBUG or settings.TEST
+
+
def request_recalculation(experiment: Experiment, user: User | None, 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.
+ A user-driven trigger inside ``MIN_USER_RECALCULATION_INTERVAL`` after the latest completed run finished
+ raises ``RecalculationRateLimited``. Otherwise creates a fresh pending row.
"""
if not experiment.is_launched:
raise ValidationError("Cannot recalculate metrics for experiment that hasn't started")
@@ -318,6 +351,21 @@ def request_recalculation(experiment: Experiment, user: User | None, trigger: st
_recalculation_reuse_counter.inc()
return build_job_payload(existing, is_existing=True)
+ if trigger in _RATE_LIMITED_TRIGGERS and _refresh_window_enforced():
+ # get the latest terminal run and check against the rate limiting rules
+ # if matched, increment counter and raise so the API answers 429 with Retry-After
+ latest = _terminal_recalculations(experiment).order_by("-created_at").first()
+ if (
+ latest is not None
+ and latest.status == ExperimentMetricsRecalculation.Status.COMPLETED
+ and latest.trigger != ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC
+ and latest.completed_at is not None
+ and latest.completed_at >= timezone.now() - MIN_USER_RECALCULATION_INTERVAL
+ ):
+ _recalculation_rate_limited_counter.inc()
+ next_allowed_at = latest.completed_at + MIN_USER_RECALCULATION_INTERVAL
+ raise RecalculationRateLimited(wait=(next_allowed_at - timezone.now()).total_seconds())
+
# 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, and cancel their workflows after commit — a superseded run that is still
@@ -369,21 +417,22 @@ def get_active_recalculation(experiment: Experiment) -> ExperimentMetricsRecalcu
)
+def _terminal_recalculations(experiment: Experiment) -> QuerySet[ExperimentMetricsRecalculation]:
+ """Runs that really finished. Callers hold the team scope.
+
+ completed_at is only ever stamped by the workflow's finalize step, so it separates runs that really
+ finished from trigger-failure tombstones (status flipped to FAILED at create time, never started). Keying
+ on metric_errors instead would hide a failed run whose failures live only in result rows.
+ """
+ return ExperimentMetricsRecalculation.objects.filter(team=experiment.team, experiment=experiment).filter(
+ Q(status=ExperimentMetricsRecalculation.Status.COMPLETED)
+ | (Q(status=ExperimentMetricsRecalculation.Status.FAILED) & Q(completed_at__isnull=False))
+ )
+
+
def get_latest_recalculation(experiment: Experiment) -> ExperimentMetricsRecalculation | None:
with team_scope(experiment.team_id, canonical=True):
- return (
- ExperimentMetricsRecalculation.objects.filter(team=experiment.team, experiment=experiment)
- .filter(
- # completed_at is only ever stamped by the workflow's finalize step, so it separates runs
- # that really finished from trigger-failure tombstones (status flipped to FAILED at create
- # time, never started). Keying on metric_errors instead would hide a failed run whose
- # failures live only in result rows.
- Q(status=ExperimentMetricsRecalculation.Status.COMPLETED)
- | (Q(status=ExperimentMetricsRecalculation.Status.FAILED) & Q(completed_at__isnull=False))
- )
- .order_by("-created_at")
- .first()
- )
+ return _terminal_recalculations(experiment).order_by("-created_at").first()
def get_recalculation_by_id(experiment: Experiment, recalculation_id: str) -> ExperimentMetricsRecalculation | None:
diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.md
index a8de3d3fa01b..84fd3624ff36 100644
--- a/products/experiments/backend/temporal/ARCHITECTURE.md
+++ b/products/experiments/backend/temporal/ARCHITECTURE.md
@@ -110,6 +110,7 @@ Two safeguards on the POST endpoint:
- **Idempotent reuse.** If an active recalc (pending or in-progress) exists for this experiment and is younger than 30 minutes, the POST returns it instead of creating a new one. Frontend can click Reload twice and get the same `recalculation_id`.
- **Per-experiment lock.** The service runs inside `transaction.atomic()` with `Experiment.objects.select_for_update()` to serialize concurrent POSTs. Without this, two simultaneous clicks would both see no active row, both reach `.create()`, and the second would hit the per-experiment unique constraint and return HTTP 500.
+- **User refresh window.** A `manual` or `agent_mcp` POST within `MIN_USER_RECALCULATION_INTERVAL` (five minutes) after the latest completed run's `completed_at` gets a 429 with a `Retry-After` header (`RecalculationRateLimited`), so a client or an agent knows when the next run is allowed. The window measures from completion, not `query_to`, because a stopped experiment pins `query_to` to `end_date`. A failed latest run never anchors the window, and neither does a `timeseries_sync` run, which may lack metrics the daily workflow does not compute. System triggers (`cold_run`, `heal_latest_run`, `manual_retry`, config changes) are exempt. Local development (`DEBUG` on, outside tests) skips the window, and the frontend mirrors that through the `is_debug` preflight field.
### Activity-aware staleness
diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.py
index bf67e0ac269c..07c74a7490e4 100644
--- a/products/experiments/backend/test/test_metrics_recalculation_api.py
+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py
@@ -149,6 +149,27 @@ class TestMetricsRecalculationAPI(APIBaseTest):
assert second.json()["id"] == first.json()["id"]
assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1
+ @mock.patch("products.experiments.backend.recalculation.sync_connect")
+ @mock.patch("products.experiments.backend.recalculation.asyncio.run")
+ def test_post_manual_inside_refresh_window_returns_429_without_a_workflow(self, mock_run, mock_connect):
+ exp = self._launched_experiment()
+ now = timezone.now()
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status="completed",
+ query_to=now - timedelta(minutes=3),
+ completed_at=now - timedelta(minutes=2),
+ )
+
+ resp = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")
+
+ assert resp.status_code == status.HTTP_429_TOO_MANY_REQUESTS, resp.content
+ assert resp.json()["code"] == "recalculation_rate_limited"
+ assert 170 <= int(resp["Retry-After"]) <= 180
+ assert not mock_connect.called
+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1
+
@mock.patch("products.experiments.backend.recalculation.sync_connect")
@mock.patch("products.experiments.backend.recalculation.asyncio.run")
def test_post_rejects_unlaunched_experiment(self, mock_run, mock_connect):
diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.py
index a0f58252be3b..4c5e516381a5 100644
--- a/products/experiments/backend/test/test_recalculation_service.py
+++ b/products/experiments/backend/test/test_recalculation_service.py
@@ -5,6 +5,7 @@ import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import patch
+from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -24,6 +25,7 @@ from products.experiments.backend.models.experiment import (
ExperimentToSavedMetric,
)
from products.experiments.backend.recalculation import (
+ RecalculationRateLimited,
build_timeseries_cold_start_payload,
get_active_recalculation,
get_latest_recalculation,
@@ -102,6 +104,70 @@ class TestRecalculationService(BaseTest):
assert row.total_metrics == 3
assert set(row.metric_uuids) == {"p1", "s1", "shared1"}
+ @parameterized.expand(
+ [
+ # (name, trigger, latest_status, latest_trigger, minutes_since_completed, expects_new_run)
+ ("manual_inside_window_is_rate_limited", "manual", "completed", "manual", 2, False),
+ ("agent_mcp_inside_window_is_rate_limited", "agent_mcp", "completed", "manual", 2, False),
+ ("manual_outside_window_starts_new", "manual", "completed", "manual", 6, True),
+ ("manual_after_failed_run_starts_new", "manual", "failed", "manual", 2, True),
+ ("manual_after_timeseries_sync_starts_new", "manual", "completed", "timeseries_sync", 2, True),
+ ("heal_inside_window_starts_new", "heal_latest_run", "completed", "manual", 2, True),
+ ("manual_retry_inside_window_starts_new", "manual_retry", "completed", "manual", 2, True),
+ ]
+ )
+ def test_request_recalculation_user_refresh_window(
+ self,
+ name: str,
+ trigger: str,
+ latest_status: str,
+ latest_trigger: str,
+ minutes_since_completed: int,
+ expects_new_run: bool,
+ ):
+ exp = self._launched_experiment(flag_key=f"window-{name}")
+ now = timezone.now()
+ # query_to sits a day back, as on a stopped experiment, so the window can only come from completed_at.
+ latest = ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status=latest_status,
+ trigger=latest_trigger,
+ query_to=now - timedelta(days=1),
+ completed_at=now - timedelta(minutes=minutes_since_completed),
+ )
+
+ if expects_new_run:
+ result = request_recalculation(exp, self.user, trigger)
+ assert result["is_existing"] is False
+ assert result["id"] != str(latest.id)
+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 2
+ return
+
+ with pytest.raises(RecalculationRateLimited) as exc_info:
+ request_recalculation(exp, self.user, trigger)
+ # Three minutes of the window remain; the wait tells the caller when to try again.
+ assert exc_info.value.wait is not None
+ assert 170 <= exc_info.value.wait <= 180
+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1
+
+ @override_settings(DEBUG=True, TEST=False)
+ def test_request_recalculation_skips_the_refresh_window_in_local_development(self):
+ exp = self._launched_experiment(flag_key="window-debug")
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status="completed",
+ trigger="manual",
+ query_to=timezone.now() - timedelta(days=1),
+ completed_at=timezone.now() - timedelta(minutes=2),
+ )
+
+ result = request_recalculation(exp, self.user, "manual")
+
+ assert result["is_existing"] is False
+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 2
+
def test_request_recalculation_is_idempotent(self):
exp = self._launched_experiment()
first = request_recalculation(exp, self.user, "manual")
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 8e2eb2682a32..13eeeeb9130f 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -745,7 +745,8 @@ export const getExperimentsMetricsRecalculationCreateUrl = (projectId: string, i
* 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
+ * already pending or in progress for this experiment. A manual trigger within five minutes after the latest
+ * completed run finished returns 429 with a Retry-After header. 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.
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index f414b60122c7..fc54f4ad19fd 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -1072,7 +1072,8 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
* 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
+ * already pending or in progress for this experiment. A manual trigger within five minutes after the latest
+ * completed run finished returns 429 with a Retry-After header. 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.
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 07c7dc061865..1c5c50cbcb60 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -18820,7 +18820,8 @@ export const ExperimentsLaunchCreateParams = () => zod.object({
* 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
+ * already pending or in progress for this experiment. A manual trigger within five minutes after the latest
+ * completed run finished returns 429 with a Retry-After header. 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.