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): latest endpoint returns active recalculation if present (#72120)

Rodrigo Ilorod070e12cd462
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
index 76af5c6c5824..9ed4e00b54ef 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
@@ -39,7 +39,9 @@ const baseRecalculation = {
failed_metrics: 0,
metric_errors: {},
trigger: 'manual',
- created_at: '2026-06-10T00:00:00Z',
+ // Recent, not a fixed date: polling anchors its staleness cap to created_at/started_at, and a
+ // months-old fixture would make every multi-tick poll test trip the zombie-run cutoff.
+ created_at: new Date().toISOString(),
started_at: null,
completed_at: null,
query_to: null,
@@ -379,6 +381,72 @@ describe('experimentMetricsLogic', () => {
expect(capturedBody).toEqual({ trigger: 'cold_run' })
})
+ it('applies terminal results and resumes polling the active run (reload while recalculating)', async () => {
+ const createMock = jest.fn(() => [201, pendingRecalculation])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ { ...completedRecalculation, active_run: { id: 'recalc-2', status: 'in_progress' } },
+ ],
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/:recalc_id/': () => [
+ 200,
+ completedRecalculation2,
+ ],
+ },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ jest.useFakeTimers()
+ mountLogic()
+
+ await expectLogic(logic)
+ .toDispatchActions(['loadLatestRecalculation', 'setCurrentRecalculation', 'pollRecalculation'])
+ .toNotHaveDispatchedActions(['triggerRecalculation'])
+
+ // The terminal run's results are on screen immediately, dimmed while the active run refreshes them.
+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)
+ expect(logic.values.recalculatingMetricUuids).toContain(PRIMARY_METRIC_UUID)
+
+ // The next poll tick finds the active run completed and applies its fresh results.
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)
+ expect(logic.values.currentRecalculation?.id).toBe('recalc-2')
+ expect(logic.values.currentRecalculation?.status).toBe('completed')
+ expect(logic.values.recalculatingMetricUuids).toEqual([])
+ // Resuming must not create a new run — that was the bug (progress frozen until manual refresh).
+ expect(createMock).not.toHaveBeenCalled()
+ jest.useRealTimers()
+ })
+
+ it('stops polling a run older than the staleness window instead of polling it forever', async () => {
+ // A worker that dies mid-run leaves the row in_progress permanently; the poll loop must give up
+ // once the run passes the backend's staleness threshold rather than hitting the by-id endpoint
+ // (and its live-progress query) every tick until the tab closes.
+ const retrieveMock = jest.fn(() => [200, { ...pendingRecalculation, status: 'in_progress' }])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ { ...completedRecalculation, active_run: { id: 'recalc-2', status: 'in_progress' } },
+ ],
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/:recalc_id/': retrieveMock,
+ },
+ })
+ jest.useFakeTimers()
+ mountLogic()
+ await expectLogic(logic).toDispatchActions(['loadLatestRecalculation', 'pollRecalculation'])
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)
+ expect(retrieveMock).toHaveBeenCalled()
+
+ // Age the run past the cap: polling must stop and the in-flight tags must clear.
+ logic.cache.recalcStartMs = Date.now() - 31 * 60 * 1000
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)
+ retrieveMock.mockClear()
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 5)
+ expect(retrieveMock).not.toHaveBeenCalled()
+ expect(logic.values.recalculatingMetricUuids).toEqual([])
+ jest.useRealTimers()
+ })
+
it('does not auto-trigger when the latest completed run is healthy', async () => {
// freshCompletedRecalculation has result_source 'recalculation' (a real run) with all metrics
// resolved, so neither the config-change heal path nor the timeseries-fallback path fires.
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index 3e81896ae367..66704038bc0c 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -41,6 +41,12 @@ export interface ExperimentMetricsLogicProps {
const RECALCULATION_POLL_INTERVAL_MS = 2000
const MAX_POLL_RETRIES = 5
+/**
+ * Mirrors the backend's 30-minute staleness threshold (_STALE_RECALC_THRESHOLD): a run still non-terminal
+ * past it is a zombie whose worker died, and the backend will force-fail it on the next trigger. Without
+ * this cap every tab that resumed the run would poll its id (and the per-tick live-progress query) forever.
+ */
+const MAX_POLL_DURATION_MS = 30 * 60 * 1000
export const RECALCULATION_STATUSES = {
pending: 'pending',
@@ -576,6 +582,28 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
actions.setCurrentRecalculation(recalculation)
applyResults(recalculation)
+ /**
+ * if there's an active recalculation running, schedule polling of
+ * the active recalculation status
+ */
+ if (recalculation.active_run) {
+ actions.setRecalculatingMetricUuids(
+ metricUuidsToDim(
+ props.experiment,
+ values.primaryMetricsResults,
+ values.secondaryMetricsResults,
+ values.primaryMetricsResultsErrors,
+ values.secondaryMetricsResultsErrors
+ )
+ )
+ cache.activeRecalculationId = recalculation.active_run.id
+ cache.recalcStartMs = Date.now()
+ cache.pollCount = 0
+ cache.pollRetryCount = 0
+ actions.pollRecalculation(recalculation.active_run.id)
+ return
+ }
+
/**
* Timeseries fallback is a placeholder: it may cover only some metrics and is cumulative
* daily data, not a fresh point-in-time result. Always trigger a real cold_run to fill the
@@ -733,6 +761,12 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
}
cache.activeRecalculationId = recalculationId
+ if (Date.now() - (cache.recalcStartMs ?? Date.now()) > MAX_POLL_DURATION_MS) {
+ actions.setRecalculatingMetricUuids([])
+ lemonToast.error('Recalculation appears stuck. Please reload to try again.')
+ return
+ }
+
// Pace this tick; aborts here if a newer poll superseded us or the logic unmounted.
await breakpoint(RECALCULATION_POLL_INTERVAL_MS)
@@ -768,6 +802,18 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
return
}
+ /**
+ * Anchor duration telemetry (and the zombie cap) to the run's actual start, not the moment
+ * this tab triggered or resumed it. Once per run: the first successful poll wins.
+ */
+ if (cache.recalcAnchoredId !== recalculationId) {
+ const runStartMs = Date.parse(recalculation.started_at ?? recalculation.created_at)
+ if (!Number.isNaN(runStartMs)) {
+ cache.recalcStartMs = runStartMs
+ }
+ cache.recalcAnchoredId = recalculationId
+ }
+
/**
* Count only polls that pass the supersession check so the analytics event reflects the work
* THIS run actually paid for; superseded ticks would otherwise inflate the number.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 849826067600..4bb26d1fc5f1 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -563,6 +563,10 @@ SPECTACULAR_SETTINGS = {
"IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind",
"TicketStatusEnum": "products.conversations.backend.models.constants.Status",
"BatchImportStatusEnum": "products.managed_migrations.backend.models.batch_imports.BatchImport.Status",
+ # Shared by ExperimentMetricsRecalculation.status and ActiveRecalculationRun.status (same choice set).
+ "MetricsRecalculationStatusEnum": (
+ "products.experiments.backend.models.experiment.ExperimentMetricsRecalculation.Status"
+ ),
"HealthIssueStatusEnum": "posthog.models.health_issue.HealthIssue.Status",
"HealthIssueSeverityEnum": "posthog.models.health_issue.HealthIssue.Severity",
"IngestionWarningSeverityEnum": "posthog.api.ingestion_warnings_v2.INGESTION_WARNING_SEVERITIES",
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index d752464b9e0f..d87d05e162e1 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1198,6 +1198,17 @@ class RecalculateMetricsRequestSerializer(serializers.Serializer):
)
+class ActiveRecalculationRunSerializer(serializers.Serializer):
+ """Pointer to a recalculation run that is still executing, surfaced alongside the latest terminal results."""
+
+ id = serializers.UUIDField(read_only=True, help_text="Identifier of the run that is still executing")
+ status = serializers.ChoiceField(
+ choices=ExperimentMetricsRecalculation.Status.choices,
+ read_only=True,
+ help_text="Status of the executing run (pending or in_progress)",
+ )
+
+
class ExperimentMetricsRecalculationSerializer(serializers.Serializer):
"""Serializer for metrics recalculation status responses."""
@@ -1241,8 +1252,14 @@ 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"
)
- # Named result_source (not source) to avoid shadowing DRF's reserved Field.source attribute, mirroring
- # the metric_errors-vs-errors rename above.
+
+ active_run = ActiveRecalculationRunSerializer(
+ read_only=True,
+ required=False,
+ allow_null=True,
+ help_text="Run currently executing for this experiment, if any; poll it by id for live progress",
+ )
+
result_source = serializers.ChoiceField(
choices=["recalculation", "timeseries_fallback"],
required=False,
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 663b3b5a257c..53d59d37ac61 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -70,6 +70,7 @@ from products.experiments.backend.presentation.serializers import (
from products.experiments.backend.recalculation import (
build_job_payload,
build_timeseries_cold_start_payload,
+ get_active_recalculation,
get_latest_recalculation,
get_recalculation_by_id,
get_run_results,
@@ -1117,14 +1118,26 @@ class EnterpriseExperimentsViewSet(
)
def metrics_recalculation_latest(self, request: Request, *args: Any, **kwargs: Any) -> Response:
experiment: Experiment = self.get_object()
+ active = get_active_recalculation(experiment)
+ active_run = {"id": str(active.id), "status": active.status} if active is not None else None
recalc = get_latest_recalculation(experiment)
+
if recalc is not None:
- return Response(_serialize_recalculation(recalc))
- # Cold start: no completed run yet. Fall back to the latest timeseries data as a read-only
- # placeholder so the user sees results immediately. Pure read, no workflow start.
+ return Response(_serialize_recalculation(recalc, active_run=active_run))
+
+ # Cold start: no terminal run worth showing. Fall back to the latest timeseries data as a read-only
+ # placeholder so the user sees results immediately, even while a first run is active (its pending
+ # payload would blank them out); an active run still rides along for polling. Pure read, no
+ # workflow start.
fallback = build_timeseries_cold_start_payload(experiment)
if fallback is not None:
+ if active_run is not None:
+ fallback["active_run"] = active_run
return Response(ExperimentMetricsRecalculationSerializer(fallback).data)
+
+ if active is not None:
+ return Response(_serialize_recalculation(active, active_run=active_run))
+
return Response({"detail": "No completed recalculation found"}, status=404)
@extend_schema(responses={200: ExperimentMetricsRecalculationSerializer, 404: None})
@@ -1260,13 +1273,10 @@ class EnterpriseExperimentsViewSet(
return Response(serializer.data)
-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.
- """
+def _serialize_recalculation(recalc: ExperimentMetricsRecalculation, active_run: dict | None = None) -> dict:
results = get_run_results(recalc)
payload = build_job_payload(recalc, results=results, include_live_progress=True)
payload["results"] = results
+ if active_run is not None:
+ payload["active_run"] = active_run
return ExperimentMetricsRecalculationSerializer(payload).data
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index 14d9894c22e8..7fc2176667cd 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -270,9 +270,11 @@ def request_recalculation(experiment: Experiment, user: User, trigger: str = "ma
).values_list("id", flat=True)
)
if stale_ids:
+ # No completed_at: that stamp is reserved for the workflow finalize step, and its absence is
+ # what keeps superseded/tombstone rows out of get_latest_recalculation.
ExperimentMetricsRecalculation.objects.filter(
team=experiment.team, experiment=experiment, id__in=stale_ids
- ).update(status=ExperimentMetricsRecalculation.Status.FAILED, completed_at=timezone.now())
+ ).update(status=ExperimentMetricsRecalculation.Status.FAILED)
_recalculation_stale_cleanup_counter.inc(len(stale_ids))
transaction.on_commit(lambda: _cancel_superseded_workflows([str(stale_id) for stale_id in stale_ids]))
@@ -291,18 +293,31 @@ def request_recalculation(experiment: Experiment, user: User, trigger: str = "ma
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.
+def get_active_recalculation(experiment: Experiment) -> ExperimentMetricsRecalculation | None:
+ with team_scope(experiment.team_id, canonical=True):
+ threshold = timezone.now() - _STALE_RECALC_THRESHOLD
+ return (
+ ExperimentMetricsRecalculation.objects.filter(team=experiment.team, experiment=experiment)
+ .filter(
+ Q(status=ExperimentMetricsRecalculation.Status.PENDING, created_at__gte=threshold)
+ | Q(status=ExperimentMetricsRecalculation.Status.IN_PROGRESS, started_at__gte=threshold)
+ )
+ .order_by("-created_at")
+ .first()
+ )
- 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.
- """
+
+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,
- status=ExperimentMetricsRecalculation.Status.COMPLETED,
+ 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()
diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.py
index cf271aec3f04..7461610970fc 100644
--- a/products/experiments/backend/test/test_metrics_recalculation_api.py
+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py
@@ -118,11 +118,29 @@ class TestMetricsRecalculationAPI(APIBaseTest):
# GET /metrics_recalculation/latest/
# ------------------------------------------------------------------
- def test_get_latest_404_when_no_completed_run(self):
+ def test_get_latest_combines_terminal_results_with_active_run(self):
+ # Reload while recalculating: the payload is the latest terminal run's results, with the executing
+ # run's id + status alongside so the client resumes polling without losing what's on screen.
exp = self._launched_experiment()
- ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="pending")
+ done = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="completed")
+ active = 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
+ assert resp.status_code == status.HTTP_200_OK, resp.content
+ body = resp.json()
+ assert body["id"] == str(done.id)
+ assert body["status"] == "completed"
+ assert body["active_run"] == {"id": str(active.id), "status": "pending"}
+
+ def test_get_latest_returns_active_run_when_no_terminal_exists(self):
+ # First-ever run still executing: no terminal results, but the client still needs an id to poll.
+ exp = self._launched_experiment()
+ active = 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_200_OK, resp.content
+ body = resp.json()
+ assert body["id"] == str(active.id)
+ assert body["status"] == "pending"
+ assert body["active_run"] == {"id": str(active.id), "status": "pending"}
def test_get_latest_returns_most_recent_completed_with_results(self):
exp = self._launched_experiment()
@@ -163,6 +181,7 @@ class TestMetricsRecalculationAPI(APIBaseTest):
assert len(body["results"]) == 1
assert body["results"][0]["metric_uuid"] == "m1"
assert body["results"][0]["result"] == {"ok": True}
+ assert body.get("active_run") is None
# ------------------------------------------------------------------
# GET /metrics_recalculation/{id}/
@@ -233,6 +252,21 @@ class TestMetricsRecalculationAPI(APIBaseTest):
assert len(body["results"]) == 1
assert body["results"][0]["result"] == {"ok": True}
+ def test_get_latest_prefers_timeseries_fallback_over_first_active_run(self):
+ # Reload during the first-ever run: the pending run has no results yet, so returning it would blank
+ # out the timeseries data on screen. The fallback keeps the results visible while active_run rides
+ # along so the client still polls the executing run.
+ exp = self._launched_experiment(flag_key="ts-fallback-active")
+ self._store_timeseries_point(exp, "m1", datetime(2026, 2, 2, tzinfo=UTC))
+ active = 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_200_OK, resp.content
+ body = resp.json()
+ assert body["result_source"] == "timeseries_fallback"
+ assert body["results"][0]["result"] == {"ok": True}
+ assert body["active_run"] == {"id": str(active.id), "status": "pending"}
+
def test_get_latest_still_404_when_no_recalc_and_no_timeseries(self):
exp = self._launched_experiment(flag_key="ts-empty")
resp = self.client.get(self._latest_url(exp.id))
diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.py
index 0949b3de2587..1a6bb31467e0 100644
--- a/products/experiments/backend/test/test_recalculation_service.py
+++ b/products/experiments/backend/test/test_recalculation_service.py
@@ -24,6 +24,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.recalculation import (
build_timeseries_cold_start_payload,
+ get_active_recalculation,
get_latest_recalculation,
get_live_query_progress,
get_recalculation_by_id,
@@ -174,14 +175,23 @@ class TestRecalculationService(BaseTest):
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).
+ def test_latest_stays_terminal_while_a_run_is_active(self):
+ # Reload while recalculating: the terminal results must keep coming back from get_latest_recalculation
+ # while get_active_recalculation separately surfaces the executing run for the client to poll.
exp = self._launched_experiment()
+ done = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="completed")
+ pending = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="pending")
+ latest = get_latest_recalculation(exp)
+ active = get_active_recalculation(exp)
+ assert latest is not None and latest.id == done.id
+ assert active is not None and active.id == pending.id
+
+ def test_get_latest_recalculation_returns_most_recent_completed(self):
+ exp = self._launched_experiment(flag_key="latest-terminal")
first_done = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="completed")
+ # A force-failed tombstone (no metric_errors) has nothing to display and must not shadow older results.
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
@@ -189,17 +199,52 @@ class TestRecalculationService(BaseTest):
@parameterized.expand(
[
- ("never_ran", []),
- ("only_pending", ["pending"]),
- ("only_failed", ["failed"]),
- ("only_in_progress", ["in_progress"]),
+ # (name, row_kwargs, stale_created_at, expect_active, expect_latest)
+ ("never_ran", None, False, False, False),
+ ("fresh_pending", {"status": "pending"}, False, True, False),
+ ("fresh_in_progress", {"status": "in_progress", "started_at": "now"}, False, True, False),
+ ("stale_pending", {"status": "pending"}, True, False, False),
+ ("stale_in_progress", {"status": "in_progress", "started_at": "old"}, False, False, False),
+ ("completed", {"status": "completed"}, False, False, True),
+ (
+ "failed_finalized_with_errors",
+ {"status": "failed", "completed_at": "now", "metric_errors": {"m1": {"message": "boom"}}},
+ False,
+ False,
+ True,
+ ),
+ # Finalized run whose failures live only in FAILED result rows (crash between the result write
+ # and the metric_errors write): still the latest terminal run, must not be hidden.
+ ("failed_finalized_without_errors", {"status": "failed", "completed_at": "now"}, False, False, True),
+ # No completed_at means the finalize step never ran: a trigger-failure tombstone or a
+ # superseded row. Nothing to display, must not shadow older results.
+ ("failed_tombstone", {"status": "failed"}, False, False, False),
]
)
- def test_get_latest_recalculation_none_when_no_completed(self, name: str, statuses: list[str]):
+ def test_latest_and_active_row_eligibility(
+ self, name: str, row_kwargs: dict | None, stale_created_at: bool, expect_active: bool, expect_latest: bool
+ ):
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
+ row = None
+ if row_kwargs is not None:
+ kwargs = dict(row_kwargs)
+ if kwargs.get("started_at") == "now":
+ kwargs["started_at"] = timezone.now()
+ elif kwargs.get("started_at") == "old":
+ kwargs["started_at"] = timezone.now() - timedelta(hours=2)
+ if kwargs.get("completed_at") == "now":
+ kwargs["completed_at"] = timezone.now()
+ row = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, **kwargs)
+ if stale_created_at:
+ # created_at uses auto_now_add so it has to be moved after create.
+ ExperimentMetricsRecalculation.objects.filter(id=row.id).update(
+ created_at=timezone.now() - timedelta(hours=2)
+ )
+
+ active = get_active_recalculation(exp)
+ latest = get_latest_recalculation(exp)
+ assert (active.id if active else None) == (row.id if row and expect_active else None)
+ assert (latest.id if latest else None) == (row.id if row and expect_latest else None)
def test_get_recalculation_by_id_returns_row(self):
exp = self._launched_experiment()
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 66a0eb2a904f..bf5104eb1620 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1814,16 +1814,31 @@ export interface RecalculateMetricsRequestApi {
* * `completed` - Completed
* * `failed` - Failed
*/
-export type ExperimentMetricsRecalculationStatusEnumApi =
- (typeof ExperimentMetricsRecalculationStatusEnumApi)[keyof typeof ExperimentMetricsRecalculationStatusEnumApi]
+export type MetricsRecalculationStatusEnumApi =
+ (typeof MetricsRecalculationStatusEnumApi)[keyof typeof MetricsRecalculationStatusEnumApi]
-export const ExperimentMetricsRecalculationStatusEnumApi = {
+export const MetricsRecalculationStatusEnumApi = {
Pending: 'pending',
InProgress: 'in_progress',
Completed: 'completed',
Failed: 'failed',
} as const
+/**
+ * Pointer to a recalculation run that is still executing, surfaced alongside the latest terminal results.
+ */
+export interface ActiveRecalculationRunApi {
+ /** Identifier of the run that is still executing */
+ readonly id: string
+ /** Status of the executing run (pending or in_progress)
+ *
+ * * `pending` - Pending
+ * * `in_progress` - In Progress
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: MetricsRecalculationStatusEnumApi
+}
+
/**
* * `recalculation` - recalculation
* * `timeseries_fallback` - timeseries_fallback
@@ -1884,7 +1899,7 @@ export interface ExperimentMetricsRecalculationApi {
* * `in_progress` - In Progress
* * `completed` - Completed
* * `failed` - Failed */
- readonly status: ExperimentMetricsRecalculationStatusEnumApi
+ readonly status: MetricsRecalculationStatusEnumApi
/** Total number of metrics to recalculate */
readonly total_metrics: number
/** Number of metrics with a COMPLETED result row in this run (derived, not stored) */
@@ -1923,6 +1938,8 @@ export interface ExperimentMetricsRecalculationApi {
readonly query_to: string | null
/** True if returning an existing job rather than a newly created one */
readonly is_existing: boolean
+ /** Run currently executing for this experiment, if any; poll it by id for live progress */
+ readonly active_run: ActiveRecalculationRunApi | null
/** Where these results came from: 'recalculation' for a real metrics-recalculation run, 'timeseries_fallback' for a cold-start placeholder built from the latest daily timeseries data.
*
* * `recalculation` - recalculation
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7f726b19d205..0a4eb5877001 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1991,6 +1991,37 @@ export namespace Schemas {
Stale: 'STALE',
} as const;
+ /**
+ * * `pending` - Pending
+ * * `in_progress` - In Progress
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+ export type MetricsRecalculationStatusEnum = typeof MetricsRecalculationStatusEnum[keyof typeof MetricsRecalculationStatusEnum];
+
+
+ export const MetricsRecalculationStatusEnum = {
+ Pending: 'pending',
+ InProgress: 'in_progress',
+ Completed: 'completed',
+ Failed: 'failed',
+ } as const;
+
+ /**
+ * Pointer to a recalculation run that is still executing, surfaced alongside the latest terminal results.
+ */
+ export interface ActiveRecalculationRun {
+ /** Identifier of the run that is still executing */
+ readonly id: string;
+ /** Status of the executing run (pending or in_progress)
+ *
+ * * `pending` - Pending
+ * * `in_progress` - In Progress
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: MetricsRecalculationStatusEnum;
+ }
+
export type ActivityEventsListWidgetAddRequestOpenApiWidgetType = typeof ActivityEventsListWidgetAddRequestOpenApiWidgetType[keyof typeof ActivityEventsListWidgetAddRequestOpenApiWidgetType];
@@ -25409,22 +25440,6 @@ 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
* * `cold_run` - Cold Run
@@ -25510,7 +25525,7 @@ export namespace Schemas {
* * `in_progress` - In Progress
* * `completed` - Completed
* * `failed` - Failed */
- readonly status: ExperimentMetricsRecalculationStatusEnum;
+ readonly status: MetricsRecalculationStatusEnum;
/** Total number of metrics to recalculate */
readonly total_metrics: number;
/** Number of metrics with a COMPLETED result row in this run (derived, not stored) */
@@ -25549,6 +25564,8 @@ export namespace Schemas {
readonly query_to: string | null;
/** True if returning an existing job rather than a newly created one */
readonly is_existing: boolean;
+ /** Run currently executing for this experiment, if any; poll it by id for live progress */
+ readonly active_run: ActiveRecalculationRun | null;
/** Where these results came from: 'recalculation' for a real metrics-recalculation run, 'timeseries_fallback' for a cold-start placeholder built from the latest daily timeseries data.
*
* * `recalculation` - recalculation