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.

fix(experiments): refactoring recalculation serializer types (#108704)

Rodrigo Ilorob5d73dfe2d63
diff --git a/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx
index 7952e46f14e4..836e2b77ed2a 100644
--- a/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx
@@ -7,13 +7,11 @@ import { useAnimatedNumber } from '@posthog/quill-charts'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'
+import { type RecalculationPayload, experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'
import { experimentResultsNotificationLogic } from '~/scenes/experiments/experimentResultsNotificationLogic'
import { useRetryCountdownLabel } from '~/scenes/experiments/MetricsView/shared/MetricRetryState'
import { Experiment } from '~/types'
-import type { ExperimentMetricsRecalculationApi } from 'products/experiments/frontend/generated/api.schemas'
-
/**
* Status line for an in-flight recalculation. Renders only while a run is actually executing
* (`cold` / `refreshing`); loading-from-latest and terminal states show nothing — the metric rows
@@ -55,7 +53,7 @@ function InFlightStatus({
notifyWhenResultsReady,
onSubscribe,
}: {
- recalculation: ExperimentMetricsRecalculationApi | null
+ recalculation: RecalculationPayload | null
liveRowsProgress: { recalculationId: string; rowsRead: number; estimatedRows: number } | null
retryingCount: number
nextRetryAt: string | null
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
index c168e90d1bb8..ba45fa890f6c 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
@@ -11,7 +11,7 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { Experiment } from '~/types'
-import type { ExperimentMetricsRecalculationApi } from 'products/experiments/frontend/generated/api.schemas'
+import type { ExperimentMetricsRecalculationRunApi } from 'products/experiments/frontend/generated/api.schemas'
import { experimentMetricsLogic } from './experimentMetricsLogic'
@@ -1120,8 +1120,8 @@ describe('experimentMetricsLogic', () => {
})
describe('liveRowsProgress', () => {
- const asRecalc = (obj: Record<string, unknown>): ExperimentMetricsRecalculationApi =>
- obj as unknown as ExperimentMetricsRecalculationApi
+ const asRecalc = (obj: Record<string, unknown>): ExperimentMetricsRecalculationRunApi =>
+ obj as unknown as ExperimentMetricsRecalculationRunApi
it('retains the last nonzero sample within a run and clears on a new run', () => {
// Draft experiment: afterMount no-ops, so the reducer can be driven directly.
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index 7f8f2bbbe15b..95e16fcc569e 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -19,7 +19,8 @@ import {
experimentsMetricsRecalculationRetrieve,
} from 'products/experiments/frontend/generated/api'
import type {
- ExperimentMetricsRecalculationApi,
+ ExperimentMetricsRecalculationJobApi,
+ ExperimentMetricsRecalculationRunApi,
ExperimentMetricsRecalculationTriggerEnumApi,
} from 'products/experiments/frontend/generated/api.schemas'
@@ -40,6 +41,15 @@ function reportExperimentMetricRecalculation(
posthog.capture('experiment metric recalculation', { status, ...properties })
}
+/**
+ * The shape every recalculation endpoint returns. POST answers with the queued job plus is_existing; the by-id
+ * poll and latest add results, retry state and live progress, so those fields are optional here.
+ */
+export type RecalculationPayload = Omit<ExperimentMetricsRecalculationJobApi, 'is_existing'> &
+ Partial<
+ Pick<ExperimentMetricsRecalculationRunApi, 'metric_retries' | 'results' | 'rows_read' | 'estimated_rows_total'>
+ >
+
type ExperimentSavedMetric = {
metadata: {
type: 'primary' | 'secondary'
@@ -118,7 +128,7 @@ const currentMetricUuids = (experiment: Experiment): string[] =>
].filter((uuid): uuid is string => !!uuid)
/** Metric uuids a run resolved: a computed result or a recorded failure. */
-const coveredMetricUuids = (recalculation: ExperimentMetricsRecalculationApi): string[] => [
+const coveredMetricUuids = (recalculation: RecalculationPayload): string[] => [
...(recalculation.results ?? []).map(({ metric_uuid }) => metric_uuid),
...Object.keys((recalculation.metric_errors as Record<string, unknown> | null) ?? {}),
]
@@ -170,7 +180,7 @@ const resolveResultByUuid = (
* wins (it covers FAILED rows AND discovery-step failures absent from `results`), falling back to a
* failed row's error_message.
*/
-const resolveErrorByUuid = (recalculation: ExperimentMetricsRecalculationApi): ResolveByUuid<MetricErrorState> => {
+const resolveErrorByUuid = (recalculation: RecalculationPayload): ResolveByUuid<MetricErrorState> => {
const metricErrors = (recalculation.metric_errors as Record<string, { message?: string }> | null) ?? {}
const failedResultMessageByUuid = new Map(
(recalculation.results ?? [])
@@ -188,7 +198,7 @@ export interface experimentMetricsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
receivedFeatureFlags: boolean // featureFlagLogic
currentProjectId: number | null // projectLogic
- currentRecalculation: ExperimentMetricsRecalculationApi | null
+ currentRecalculation: RecalculationPayload | null
isMetricRecalculating: (metricUuid: string | undefined) => boolean
isRecalculating: boolean
lastRefresh: string | null
@@ -229,8 +239,8 @@ export interface experimentMetricsLogicActions {
pollRecalculation: (recalculationId: string) => {
recalculationId: string
}
- setCurrentRecalculation: (recalculation: ExperimentMetricsRecalculationApi | null) => {
- recalculation: ExperimentMetricsRecalculationApi | null
+ setCurrentRecalculation: (recalculation: RecalculationPayload | null) => {
+ recalculation: RecalculationPayload | null
}
setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => {
results: CachedNewExperimentQueryResponse[]
@@ -262,23 +272,18 @@ export interface experimentMetricsLogicActions {
export interface experimentMetricsLogicMeta {
key: ExperimentIdType
__keaTypeGenInternalSelectorTypes: {
- isRecalculating: (
- recalculationLoading: boolean,
- currentRecalculation: ExperimentMetricsRecalculationApi | null
- ) => boolean
- recalculationProgress: (currentRecalculation: ExperimentMetricsRecalculationApi | null) => {
+ isRecalculating: (recalculationLoading: boolean, currentRecalculation: RecalculationPayload | null) => boolean
+ recalculationProgress: (currentRecalculation: RecalculationPayload | null) => {
completed: number
total: number
}
totalMetricsCount: (arg: any) => number
- lastRefresh: (currentRecalculation: ExperimentMetricsRecalculationApi | null) => string | null
- metricRetries: (
- currentRecalculation: ExperimentMetricsRecalculationApi | null
- ) => Record<string, MetricRetryInfo>
+ lastRefresh: (currentRecalculation: RecalculationPayload | null) => string | null
+ metricRetries: (currentRecalculation: RecalculationPayload | null) => Record<string, MetricRetryInfo>
nextRetryAt: (metricRetries: Record<string, MetricRetryInfo>) => string | null
recalculationDisplayState: (
recalculationLoading: boolean,
- currentRecalculation: ExperimentMetricsRecalculationApi | null
+ currentRecalculation: RecalculationPayload | null
) => 'cold' | 'initial' | 'partial' | 'refreshing' | 'resting'
isMetricRecalculating: (recalculatingMetricUuids: string[]) => (metricUuid: string | undefined) => boolean
}
@@ -300,7 +305,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
actions: [featureFlagLogic, ['setFeatureFlags']],
})),
actions({
- setCurrentRecalculation: (recalculation: ExperimentMetricsRecalculationApi | null) => ({ recalculation }),
+ setCurrentRecalculation: (recalculation: RecalculationPayload | null) => ({ recalculation }),
loadLatestRecalculation: true,
triggerRecalculation: (trigger: ExperimentMetricsRecalculationTriggerEnumApi = 'manual') => ({ trigger }),
pollRecalculation: (recalculationId: string) => ({ recalculationId }),
@@ -315,7 +320,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
}),
reducers({
currentRecalculation: [
- null as ExperimentMetricsRecalculationApi | null,
+ null as RecalculationPayload | null,
{
setCurrentRecalculation: (_, { recalculation }) => recalculation,
},
@@ -392,7 +397,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
// True while a recalculation is being fetched or is still running.
isRecalculating: [
(s) => [s.recalculationLoading, s.currentRecalculation],
- (recalculationLoading: boolean, recalculation: ExperimentMetricsRecalculationApi | null): boolean =>
+ (recalculationLoading: boolean, recalculation: RecalculationPayload | null): boolean =>
recalculationLoading ||
recalculation?.status === RECALCULATION_STATUSES.pending ||
recalculation?.status === RECALCULATION_STATUSES.in_progress,
@@ -401,7 +406,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
(s) => [s.currentRecalculation],
// "completed" here means resolved: a failed metric is done too, so it counts toward progress.
// Without this, a run where every metric fails sits at 0/N forever and looks stuck.
- (recalc: ExperimentMetricsRecalculationApi | null): { completed: number; total: number } => ({
+ (recalc: RecalculationPayload | null): { completed: number; total: number } => ({
completed: (recalc?.completed_metrics ?? 0) + (recalc?.failed_metrics ?? 0),
total: recalc?.total_metrics ?? 0,
}),
@@ -415,11 +420,11 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
],
lastRefresh: [
(s) => [s.currentRecalculation],
- (recalc: ExperimentMetricsRecalculationApi | null): string | null => recalc?.query_to ?? null,
+ (recalc: RecalculationPayload | null): string | null => recalc?.query_to ?? null,
],
metricRetries: [
(s) => [s.currentRecalculation],
- (recalc: ExperimentMetricsRecalculationApi | null): Record<string, MetricRetryInfo> => {
+ (recalc: RecalculationPayload | null): Record<string, MetricRetryInfo> => {
const raw = (recalc?.metric_retries ?? {}) as Record<string, MetricRetryInfo>
const landed = new Set([
...(recalc?.results ?? []).map(({ metric_uuid }) => metric_uuid),
@@ -442,7 +447,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
(s) => [s.recalculationLoading, s.currentRecalculation],
(
recalculationLoading: boolean,
- recalculation: ExperimentMetricsRecalculationApi | null
+ recalculation: RecalculationPayload | null
): 'initial' | 'cold' | 'refreshing' | 'partial' | 'resting' => {
if (!recalculation) {
return recalculationLoading ? 'initial' : 'resting'
@@ -497,7 +502,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
* Emit the terminal analytics event for a recalc run. Reads duration_ms / poll_count off the cache
* fields set on trigger; both are 0 on a terminal-on-create run because no poll ever happened.
*/
- const emitTerminalEvent = (recalculation: ExperimentMetricsRecalculationApi): void => {
+ const emitTerminalEvent = (recalculation: RecalculationPayload): void => {
const startMs = cache.recalcStartMs ?? Date.now()
reportExperimentMetricRecalculation(
recalculation.status === RECALCULATION_STATUSES.completed ? 'completed' : 'failed',
@@ -517,7 +522,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
* apply per-metric results and errors by setting primary and secondary metric results and errors.
* Partial failures will load the metrics that succeeded, and failed metrics get a nice error view.
*/
- const applyResults = (recalculation: ExperimentMetricsRecalculationApi): void => {
+ const applyResults = (recalculation: RecalculationPayload): void => {
const resultFor = resolveResultByUuid(recalculation.results)
const errorFor = resolveErrorByUuid(recalculation)
@@ -913,7 +918,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
// Pace this tick; aborts here if a newer poll superseded us or the logic unmounted.
await breakpoint(RECALCULATION_POLL_INTERVAL_MS)
- let recalculation: ExperimentMetricsRecalculationApi
+ let recalculation: ExperimentMetricsRecalculationRunApi
try {
recalculation = await experimentsMetricsRecalculationRetrieve(
String(projectId),
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 5709c8904c01..bd420f1abbd0 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1452,8 +1452,12 @@ class ActiveRecalculationRunSerializer(serializers.Serializer):
)
-class ExperimentMetricsRecalculationSerializer(serializers.Serializer):
- """Serializer for metrics recalculation status responses."""
+class _ExperimentMetricsRecalculationBaseSerializer(serializers.Serializer):
+ """Identity, counters and timestamps of one recalculation job row.
+
+ Never a response on its own. Each endpoint serializes with the subclass that matches what it fills, so the
+ generated client types carry only the fields that endpoint returns.
+ """
id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this recalculation job")
experiment_id = serializers.IntegerField(read_only=True, help_text="ID of the experiment being recalculated")
@@ -1476,21 +1480,6 @@ class ExperimentMetricsRecalculationSerializer(serializers.Serializer):
)
# 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")
- metric_retries = serializers.JSONField(
- read_only=True,
- required=False,
- help_text=(
- "Transient retry state per metric_uuid: {attempt, max_attempts, error_type, message, "
- "next_retry_at}. message is a user-safe description of the error that triggered the retry. "
- "Present only while a metric is between failed attempts; cleared when it succeeds or "
- "fails terminally, so treat entries for metrics that already have a result as stale."
- ),
- )
- trigger = serializers.ChoiceField(
- choices=ExperimentMetricsRecalculation.Trigger.choices,
- read_only=True,
- help_text="What triggered this recalculation",
- )
created_at = serializers.DateTimeField(read_only=True, help_text="When the job was created")
started_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When processing started")
completed_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When processing completed")
@@ -1502,29 +1491,29 @@ class ExperimentMetricsRecalculationSerializer(serializers.Serializer):
"Shared by every metric in the run; null until processing starts"
),
)
+
+
+class ExperimentMetricsRecalculationJobSerializer(_ExperimentMetricsRecalculationBaseSerializer):
+ """POST response: the job just queued, or the one already active. It carries no results or live progress yet."""
+
is_existing = serializers.BooleanField(
read_only=True, required=False, help_text="True if returning an existing job rather than a newly created one"
)
- 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,
- default="recalculation",
+class ExperimentMetricsRecalculationRunSerializer(_ExperimentMetricsRecalculationBaseSerializer):
+ """GET by id: one run with its per-metric results, retry state and live query progress."""
+
+ metric_retries = serializers.JSONField(
read_only=True,
+ required=False,
help_text=(
- "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."
+ "Transient retry state per metric_uuid: {attempt, max_attempts, error_type, message, "
+ "next_retry_at}. message is a user-safe description of the error that triggered the retry. "
+ "Present only while a metric is between failed attempts; cleared when it succeeds or "
+ "fails terminally, so treat entries for metrics that already have a result as stale."
),
)
- # 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,
@@ -1550,6 +1539,27 @@ class ExperimentMetricsRecalculationSerializer(serializers.Serializer):
)
+class ExperimentMetricsRecalculationLatestSerializer(ExperimentMetricsRecalculationRunSerializer):
+ """GET latest: the newest terminal run, or the timeseries fallback, plus a pointer to any active run."""
+
+ 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,
+ default="recalculation",
+ read_only=True,
+ help_text=(
+ "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."
+ ),
+ )
+
+
class RunningTimeBaselineStatsSerializer(serializers.Serializer):
"""Raw control-group statistics the calculator uses to derive a baseline value and variance.
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 4bed84e67a5a..444449726c93 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -96,7 +96,9 @@ from products.experiments.backend.presentation.serializers import (
ExperimentFlagCleanupTaskSerializer,
ExperimentInSessionExposureSerializer,
ExperimentMatchingIdsResponseSerializer,
- ExperimentMetricsRecalculationSerializer,
+ ExperimentMetricsRecalculationJobSerializer,
+ ExperimentMetricsRecalculationLatestSerializer,
+ ExperimentMetricsRecalculationRunSerializer,
ExperimentSerializer,
ExperimentSessionBucketRequestSerializer,
ExperimentSessionBucketResponseSerializer,
@@ -1361,8 +1363,8 @@ class EnterpriseExperimentsViewSet(
@extend_schema(
request=RecalculateMetricsRequestSerializer,
responses={
- 200: ExperimentMetricsRecalculationSerializer,
- 201: ExperimentMetricsRecalculationSerializer,
+ 200: ExperimentMetricsRecalculationJobSerializer,
+ 201: ExperimentMetricsRecalculationJobSerializer,
},
)
@action(
@@ -1430,11 +1432,11 @@ class EnterpriseExperimentsViewSet(
raise
return Response(
- ExperimentMetricsRecalculationSerializer(result).data,
+ ExperimentMetricsRecalculationJobSerializer(result).data,
status=200 if is_existing else 201,
)
- @extend_schema(responses={200: ExperimentMetricsRecalculationSerializer, 404: None})
+ @extend_schema(responses={200: ExperimentMetricsRecalculationLatestSerializer, 404: None})
@action(
methods=["GET"],
detail=True,
@@ -1449,7 +1451,7 @@ class EnterpriseExperimentsViewSet(
recalc = get_latest_recalculation(experiment)
if recalc is not None:
- return Response(_serialize_recalculation(recalc, active_run=active_run))
+ return Response(_serialize_latest(_build_run_payload(recalc), 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
@@ -1457,12 +1459,10 @@ class EnterpriseExperimentsViewSet(
# 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)
+ return Response(_serialize_latest(fallback, active_run))
if active is not None:
- return Response(_serialize_recalculation(active, active_run=active_run))
+ return Response(_serialize_latest(_build_run_payload(active), active_run))
return Response({"detail": "No completed recalculation found"}, status=404)
@@ -1481,7 +1481,7 @@ class EnterpriseExperimentsViewSet(
),
)
],
- responses={200: ExperimentMetricsRecalculationSerializer, 404: None},
+ responses={200: ExperimentMetricsRecalculationRunSerializer, 404: None},
)
@action(
methods=["GET"],
@@ -1497,7 +1497,7 @@ class EnterpriseExperimentsViewSet(
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))
+ return Response(ExperimentMetricsRecalculationRunSerializer(_build_run_payload(recalc)).data)
@action(methods=["GET"], detail=False, url_path="stats", required_scopes=["experiment:read"])
def stats(self, request: Request, **kwargs: Any) -> Response:
@@ -1886,10 +1886,14 @@ class EnterpriseExperimentsViewSet(
return False
-def _serialize_recalculation(recalc: ExperimentMetricsRecalculation, active_run: dict | None = None) -> dict:
+def _build_run_payload(recalc: ExperimentMetricsRecalculation) -> dict:
results = get_run_results(recalc)
payload = build_job_payload(recalc, results=results, include_live_progress=True)
payload["results"] = results
+ return payload
+
+
+def _serialize_latest(payload: dict, active_run: dict | None) -> dict:
if active_run is not None:
payload["active_run"] = active_run
- return ExperimentMetricsRecalculationSerializer(payload).data
+ return ExperimentMetricsRecalculationLatestSerializer(payload).data
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index aa37bfddf14b..de29b32e9d7a 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -501,7 +501,7 @@ def build_timeseries_cold_start_payload(experiment: Experiment) -> dict | None:
"completed_metrics": len(results),
"failed_metrics": 0,
"metric_errors": {},
- "trigger": ExperimentMetricsRecalculation.Trigger.COLD_RUN,
+ "metric_retries": {},
"created_at": latest_query_to,
"started_at": latest_query_to,
"completed_at": latest_query_to,
diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.py
index f36a142fc29f..de6e22d0233a 100644
--- a/products/experiments/backend/test/test_metrics_recalculation_api.py
+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py
@@ -80,7 +80,6 @@ class TestMetricsRecalculationAPI(APIBaseTest):
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
@@ -90,7 +89,6 @@ class TestMetricsRecalculationAPI(APIBaseTest):
exp = self._launched_experiment()
resp = self.client.post(self._post_url(exp.id), format="json", headers={"X-PostHog-Client": "mcp"})
assert resp.status_code == status.HTTP_201_CREATED, resp.content
- assert resp.json()["trigger"] == ExperimentMetricsRecalculation.Trigger.AGENT_MCP
assert (
ExperimentMetricsRecalculation.objects.get(experiment=exp).trigger
== ExperimentMetricsRecalculation.Trigger.AGENT_MCP
@@ -102,7 +100,27 @@ class TestMetricsRecalculationAPI(APIBaseTest):
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
- assert resp.json()["trigger"] == ExperimentMetricsRecalculation.Trigger.MANUAL
+ assert (
+ ExperimentMetricsRecalculation.objects.get(experiment=exp).trigger
+ == ExperimentMetricsRecalculation.Trigger.MANUAL
+ )
+
+ @mock.patch("products.experiments.backend.presentation.views.sync_connect")
+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")
+ def test_each_endpoint_returns_only_its_own_fields(self, mock_run, mock_connect):
+ exp = self._launched_experiment()
+ created = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json").json()
+ assert "is_existing" in created
+ assert {"results", "rows_read", "active_run", "result_source", "trigger"}.isdisjoint(created)
+
+ by_id = self.client.get(self._by_id_url(exp.id, created["id"])).json()
+ assert "results" in by_id
+ assert {"is_existing", "active_run", "result_source", "trigger"}.isdisjoint(by_id)
+
+ latest = self.client.get(self._latest_url(exp.id)).json()
+ assert "results" in latest
+ assert latest["active_run"] == {"id": created["id"], "status": "pending"}
+ assert {"is_existing", "trigger"}.isdisjoint(latest)
@mock.patch("products.experiments.backend.presentation.views.sync_connect")
@mock.patch("products.experiments.backend.presentation.views.asyncio.run")
@@ -294,6 +312,8 @@ class TestMetricsRecalculationAPI(APIBaseTest):
assert resp.status_code == status.HTTP_200_OK, resp.content
body = resp.json()
assert body["result_source"] == "timeseries_fallback"
+ # The latest response type declares metric_retries; the fallback has no run, so it reports none.
+ assert body["metric_retries"] == {}
assert body["status"] == "completed"
assert len(body["results"]) == 1
assert body["results"][0]["result"] == {"ok": True}
diff --git a/products/experiments/backend/test/test_metrics_recalculation_serializer.py b/products/experiments/backend/test/test_metrics_recalculation_serializer.py
index f6f6ea8bdd14..2a1f80365772 100644
--- a/products/experiments/backend/test/test_metrics_recalculation_serializer.py
+++ b/products/experiments/backend/test/test_metrics_recalculation_serializer.py
@@ -8,14 +8,16 @@ from posthog.models.scoping import team_scope
from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation
from products.experiments.backend.presentation.serializers import (
- ExperimentMetricsRecalculationSerializer,
+ ExperimentMetricsRecalculationJobSerializer,
+ ExperimentMetricsRecalculationLatestSerializer,
+ ExperimentMetricsRecalculationRunSerializer,
MetricRecalculationResultSerializer,
RecalculateMetricsRequestSerializer,
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
-class TestExperimentMetricsRecalculationSerializer(BaseTest):
+class TestExperimentMetricsRecalculationSerializers(BaseTest):
def test_serializes_status_payload(self):
payload = {
"id": "00000000-0000-0000-0000-000000000001",
@@ -29,11 +31,12 @@ class TestExperimentMetricsRecalculationSerializer(BaseTest):
"completed_at": None,
"query_to": "2026-05-28T10:00:01Z",
}
- data = ExperimentMetricsRecalculationSerializer(payload).data
+ data = ExperimentMetricsRecalculationRunSerializer(payload).data
assert data["status"] == "in_progress"
assert data["total_metrics"] == 3
assert data["experiment_id"] == 7
- assert data["trigger"] == "manual"
+ # trigger is model state for the window decision and analytics; no client reads it.
+ assert "trigger" not in data
assert data["completed_at"] is None
assert data["query_to"] == "2026-05-28T10:00:01Z"
# Field is metric_errors (not errors) to avoid shadowing DRF's Serializer.errors property.
@@ -60,7 +63,7 @@ class TestExperimentMetricsRecalculationSerializer(BaseTest):
experiment=experiment,
metric_errors={"m1": {"step": "calculation", "message": "boom"}},
)
- data = ExperimentMetricsRecalculationSerializer(recalc).data
+ data = ExperimentMetricsRecalculationRunSerializer(recalc).data
assert data["metric_errors"] == {"m1": {"step": "calculation", "message": "boom"}}
assert "errors" not in data
@@ -72,7 +75,7 @@ class TestExperimentMetricsRecalculationSerializer(BaseTest):
)
def test_is_existing_round_trips_when_set(self, name: str, value: bool):
# is_existing is required=False; when the caller populates it, it must round-trip with that value.
- data = ExperimentMetricsRecalculationSerializer({"is_existing": value}).data
+ data = ExperimentMetricsRecalculationJobSerializer({"is_existing": value}).data
assert data["is_existing"] is value
def test_is_existing_omitted_when_absent_from_instance(self):
@@ -80,17 +83,17 @@ class TestExperimentMetricsRecalculationSerializer(BaseTest):
# and the field disappears from the output entirely (rather than serializing as None). Pins the
# contract so a future refactor — adding default=, switching to ModelSerializer, flipping required —
# can't silently start emitting is_existing on payloads that never asked for it.
- data = ExperimentMetricsRecalculationSerializer({}).data
+ data = ExperimentMetricsRecalculationJobSerializer({}).data
assert "is_existing" not in data
def test_result_source_defaults_to_recalculation_when_absent(self):
# required=False + default means a real payload that never sets result_source still serializes it as
# "recalculation", so clients can always read a concrete source.
- data = ExperimentMetricsRecalculationSerializer({"status": "completed"}).data
+ data = ExperimentMetricsRecalculationLatestSerializer({"status": "completed"}).data
assert data["result_source"] == "recalculation"
def test_result_source_round_trips_timeseries_fallback(self):
- data = ExperimentMetricsRecalculationSerializer(
+ data = ExperimentMetricsRecalculationLatestSerializer(
{"status": "completed", "result_source": "timeseries_fallback"}
).data
assert data["result_source"] == "timeseries_fallback"
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index f30663a4d789..921ad80d01b9 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2214,31 +2214,49 @@ export const MetricsRecalculationStatusEnumApi = {
} as const
/**
- * Pointer to a recalculation run that is still executing, surfaced alongside the latest terminal results.
+ * POST response: the job just queued, or the one already active. It carries no results or live progress yet.
*/
-export interface ActiveRecalculationRunApi {
- /** Identifier of the run that is still executing */
+export interface ExperimentMetricsRecalculationJobApi {
+ /** Unique identifier for this recalculation job */
readonly id: string
- /** Status of the executing run (pending or in_progress)
+ /** 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: 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) */
+ 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
+ /** 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
+ /**
+ * Upper time bound the metrics in this run were calculated against (the data freshness cutoff). Shared by every metric in the run; null until processing starts
+ * @nullable
+ */
+ readonly query_to: string | null
+ /** True if returning an existing job rather than a newly created one */
+ readonly is_existing: boolean
}
-/**
- * * `recalculation` - recalculation
- * * `timeseries_fallback` - timeseries_fallback
- */
-export type ResultSourceEnumApi = (typeof ResultSourceEnumApi)[keyof typeof ResultSourceEnumApi]
-
-export const ResultSourceEnumApi = {
- Recalculation: 'recalculation',
- TimeseriesFallback: 'timeseries_fallback',
-} as const
-
/**
* * `pending` - pending
* * `completed` - completed
@@ -2275,9 +2293,9 @@ export interface MetricRecalculationResultApi {
}
/**
- * Serializer for metrics recalculation status responses.
+ * GET by id: one run with its per-metric results, retry state and live query progress.
*/
-export interface ExperimentMetricsRecalculationApi {
+export interface ExperimentMetricsRecalculationRunApi {
/** Unique identifier for this recalculation job */
readonly id: string
/** ID of the experiment being recalculated */
@@ -2297,23 +2315,88 @@ export interface ExperimentMetricsRecalculationApi {
readonly failed_metrics: number
/** Map of metric_uuid to error details */
readonly metric_errors: unknown
+ /** 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
+ /**
+ * Upper time bound the metrics in this run were calculated against (the data freshness cutoff). Shared by every metric in the run; null until processing starts
+ * @nullable
+ */
+ readonly query_to: string | null
/** Transient retry state per metric_uuid: {attempt, max_attempts, error_type, message, next_retry_at}. message is a user-safe description of the error that triggered the retry. Present only while a metric is between failed attempts; cleared when it succeeds or fails terminally, so treat entries for metrics that already have a result as stale. */
readonly metric_retries: unknown
- /** What triggered this recalculation
+ /** Per-metric results computed by this run, scoped by the run's recalc fingerprint */
+ readonly results: readonly MetricRecalculationResultApi[]
+ /**
+ * Rows read by the run's metric queries so far, both finished and currently running. Cumulative and roughly monotonic across the run; the primary live progress signal
+ * @nullable
+ */
+ rows_read?: number | null
+ /**
+ * ClickHouse's total_rows_approx across running queries plus the final read_rows of finished ones. A soft ceiling revised mid-scan, so it can exceed or trail rows_read; treat rows_read as the reliable signal
+ * @nullable
+ */
+ estimated_rows_total?: number | null
+}
+
+/**
+ * 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)
*
- * * `manual` - Manual
- * * `agent_mcp` - Agent (MCP)
- * * `cold_run` - Cold Run
- * * `stale_refresh` - Stale Refresh
- * * `auto_refresh` - Auto Refresh
- * * `experiment_config_change` - Experiment Config Change
- * * `metric_config_change` - Metric Config Change
- * * `config_change` - Config Change
- * * `experiment_launch` - Experiment Launch
- * * `experiment_stop` - Experiment Stop
- * * `experiment_update` - Experiment Update
- * * `timeseries_sync` - Timeseries Sync */
- readonly trigger: ExperimentMetricsRecalculationTriggerEnumApi
+ * * `pending` - Pending
+ * * `in_progress` - In Progress
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: MetricsRecalculationStatusEnumApi
+}
+
+/**
+ * * `recalculation` - recalculation
+ * * `timeseries_fallback` - timeseries_fallback
+ */
+export type ResultSourceEnumApi = (typeof ResultSourceEnumApi)[keyof typeof ResultSourceEnumApi]
+
+export const ResultSourceEnumApi = {
+ Recalculation: 'recalculation',
+ TimeseriesFallback: 'timeseries_fallback',
+} as const
+
+/**
+ * GET latest: the newest terminal run, or the timeseries fallback, plus a pointer to any active run.
+ */
+export interface ExperimentMetricsRecalculationLatestApi {
+ /** 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: 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) */
+ 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
/** When the job was created */
readonly created_at: string
/**
@@ -2331,15 +2414,8 @@ export interface ExperimentMetricsRecalculationApi {
* @nullable
*/
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
- * * `timeseries_fallback` - timeseries_fallback */
- readonly result_source: ResultSourceEnumApi
+ /** Transient retry state per metric_uuid: {attempt, max_attempts, error_type, message, next_retry_at}. message is a user-safe description of the error that triggered the retry. Present only while a metric is between failed attempts; cleared when it succeeds or fails terminally, so treat entries for metrics that already have a result as stale. */
+ readonly metric_retries: unknown
/** Per-metric results computed by this run, scoped by the run's recalc fingerprint */
readonly results: readonly MetricRecalculationResultApi[]
/**
@@ -2352,6 +2428,13 @@ export interface ExperimentMetricsRecalculationApi {
* @nullable
*/
estimated_rows_total?: number | null
+ /** 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
+ * * `timeseries_fallback` - timeseries_fallback */
+ readonly result_source: ResultSourceEnumApi
}
/**
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 8858c0c0511b..8e2eb2682a32 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -23,7 +23,9 @@ import type {
ExperimentHoldoutsListParams,
ExperimentInSessionExposureApi,
ExperimentMatchingIdsResponseApi,
- ExperimentMetricsRecalculationApi,
+ ExperimentMetricsRecalculationJobApi,
+ ExperimentMetricsRecalculationLatestApi,
+ ExperimentMetricsRecalculationRunApi,
ExperimentSavedMetricApi,
ExperimentSavedMetricsListParams,
ExperimentSessionBucketRequestApi,
@@ -753,13 +755,16 @@ export const experimentsMetricsRecalculationCreate = async (
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),
- })
+): Promise<ExperimentMetricsRecalculationJobApi> => {
+ return apiMutator<ExperimentMetricsRecalculationJobApi>(
+ getExperimentsMetricsRecalculationCreateUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(recalculateMetricsRequestApi),
+ }
+ )
}
export const getExperimentsMetricsRecalculationRetrieveUrl = (
@@ -782,8 +787,8 @@ export const experimentsMetricsRecalculationRetrieve = async (
id: number,
recalculationId: string,
options?: RequestInit
-): Promise<ExperimentMetricsRecalculationApi> => {
- return apiMutator<ExperimentMetricsRecalculationApi>(
+): Promise<ExperimentMetricsRecalculationRunApi> => {
+ return apiMutator<ExperimentMetricsRecalculationRunApi>(
getExperimentsMetricsRecalculationRetrieveUrl(projectId, id, recalculationId),
{
...options,
@@ -807,8 +812,8 @@ export const experimentsMetricsRecalculationLatestRetrieve = async (
projectId: string,
id: number,
options?: RequestInit
-): Promise<ExperimentMetricsRecalculationApi> => {
- return apiMutator<ExperimentMetricsRecalculationApi>(
+): Promise<ExperimentMetricsRecalculationLatestApi> => {
+ return apiMutator<ExperimentMetricsRecalculationLatestApi>(
getExperimentsMetricsRecalculationLatestRetrieveUrl(projectId, id),
{
...options,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 01a32579ecd9..4061e45b3d0c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -41233,48 +41233,48 @@ export namespace Schemas {
}
/**
- * * `manual` - Manual
- * * `agent_mcp` - Agent (MCP)
- * * `cold_run` - Cold Run
- * * `stale_refresh` - Stale Refresh
- * * `auto_refresh` - Auto Refresh
- * * `experiment_config_change` - Experiment Config Change
- * * `metric_config_change` - Metric Config Change
- * * `config_change` - Config Change
- * * `experiment_launch` - Experiment Launch
- * * `experiment_stop` - Experiment Stop
- * * `experiment_update` - Experiment Update
- * * `timeseries_sync` - Timeseries Sync
- */
- export type ExperimentMetricsRecalculationTriggerEnum = typeof ExperimentMetricsRecalculationTriggerEnum[keyof typeof ExperimentMetricsRecalculationTriggerEnum];
-
-
- export const ExperimentMetricsRecalculationTriggerEnum = {
- Manual: 'manual',
- AgentMcp: 'agent_mcp',
- ColdRun: 'cold_run',
- StaleRefresh: 'stale_refresh',
- AutoRefresh: 'auto_refresh',
- ExperimentConfigChange: 'experiment_config_change',
- MetricConfigChange: 'metric_config_change',
- ConfigChange: 'config_change',
- ExperimentLaunch: 'experiment_launch',
- ExperimentStop: 'experiment_stop',
- ExperimentUpdate: 'experiment_update',
- TimeseriesSync: 'timeseries_sync',
- } as const;
-
- /**
- * * `recalculation` - recalculation
- * * `timeseries_fallback` - timeseries_fallback
+ * POST response: the job just queued, or the one already active. It carries no results or live progress yet.
*/
- export type ResultSourceEnum = typeof ResultSourceEnum[keyof typeof ResultSourceEnum];
-
-
- export const ResultSourceEnum = {
- Recalculation: 'recalculation',
- TimeseriesFallback: 'timeseries_fallback',
- } as const;
+ export interface ExperimentMetricsRecalculationJob {
+ /** 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: 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) */
+ 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;
+ /** 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;
+ /**
+ * Upper time bound the metrics in this run were calculated against (the data freshness cutoff). Shared by every metric in the run; null until processing starts
+ * @nullable
+ */
+ readonly query_to: string | null;
+ /** True if returning an existing job rather than a newly created one */
+ readonly is_existing: boolean;
+ }
/**
* * `pending` - pending
@@ -41312,9 +41312,21 @@ export namespace Schemas {
}
/**
- * Serializer for metrics recalculation status responses.
+ * * `recalculation` - recalculation
+ * * `timeseries_fallback` - timeseries_fallback
+ */
+ export type ResultSourceEnum = typeof ResultSourceEnum[keyof typeof ResultSourceEnum];
+
+
+ export const ResultSourceEnum = {
+ Recalculation: 'recalculation',
+ TimeseriesFallback: 'timeseries_fallback',
+ } as const;
+
+ /**
+ * GET latest: the newest terminal run, or the timeseries fallback, plus a pointer to any active run.
*/
- export interface ExperimentMetricsRecalculation {
+ export interface ExperimentMetricsRecalculationLatest {
/** Unique identifier for this recalculation job */
readonly id: string;
/** ID of the experiment being recalculated */
@@ -41334,23 +41346,6 @@ export namespace Schemas {
readonly failed_metrics: number;
/** Map of metric_uuid to error details */
readonly metric_errors: unknown;
- /** Transient retry state per metric_uuid: {attempt, max_attempts, error_type, message, next_retry_at}. message is a user-safe description of the error that triggered the retry. Present only while a metric is between failed attempts; cleared when it succeeds or fails terminally, so treat entries for metrics that already have a result as stale. */
- readonly metric_retries: unknown;
- /** What triggered this recalculation
- *
- * * `manual` - Manual
- * * `agent_mcp` - Agent (MCP)
- * * `cold_run` - Cold Run
- * * `stale_refresh` - Stale Refresh
- * * `auto_refresh` - Auto Refresh
- * * `experiment_config_change` - Experiment Config Change
- * * `metric_config_change` - Metric Config Change
- * * `config_change` - Config Change
- * * `experiment_launch` - Experiment Launch
- * * `experiment_stop` - Experiment Stop
- * * `experiment_update` - Experiment Update
- * * `timeseries_sync` - Timeseries Sync */
- readonly trigger: ExperimentMetricsRecalculationTriggerEnum;
/** When the job was created */
readonly created_at: string;
/**
@@ -41368,8 +41363,20 @@ export namespace Schemas {
* @nullable
*/
readonly query_to: string | null;
- /** True if returning an existing job rather than a newly created one */
- readonly is_existing: boolean;
+ /** Transient retry state per metric_uuid: {attempt, max_attempts, error_type, message, next_retry_at}. message is a user-safe description of the error that triggered the retry. Present only while a metric is between failed attempts; cleared when it succeeds or fails terminally, so treat entries for metrics that already have a result as stale. */
+ readonly metric_retries: unknown;
+ /** Per-metric results computed by this run, scoped by the run's recalc fingerprint */
+ readonly results: readonly MetricRecalculationResult[];
+ /**
+ * Rows read by the run's metric queries so far, both finished and currently running. Cumulative and roughly monotonic across the run; the primary live progress signal
+ * @nullable
+ */
+ rows_read?: number | null;
+ /**
+ * ClickHouse's total_rows_approx across running queries plus the final read_rows of finished ones. A soft ceiling revised mid-scan, so it can exceed or trail rows_read; treat rows_read as the reliable signal
+ * @nullable
+ */
+ estimated_rows_total?: number | null;
/** 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.
@@ -41377,6 +41384,50 @@ export namespace Schemas {
* * `recalculation` - recalculation
* * `timeseries_fallback` - timeseries_fallback */
readonly result_source: ResultSourceEnum;
+ }
+
+ /**
+ * GET by id: one run with its per-metric results, retry state and live query progress.
+ */
+ export interface ExperimentMetricsRecalculationRun {
+ /** 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: 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) */
+ 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;
+ /** 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;
+ /**
+ * Upper time bound the metrics in this run were calculated against (the data freshness cutoff). Shared by every metric in the run; null until processing starts
+ * @nullable
+ */
+ readonly query_to: string | null;
+ /** Transient retry state per metric_uuid: {attempt, max_attempts, error_type, message, next_retry_at}. message is a user-safe description of the error that triggered the retry. Present only while a metric is between failed attempts; cleared when it succeeds or fails terminally, so treat entries for metrics that already have a result as stale. */
+ readonly metric_retries: unknown;
/** Per-metric results computed by this run, scoped by the run's recalc fingerprint */
readonly results: readonly MetricRecalculationResult[];
/**
@@ -41391,6 +41442,38 @@ export namespace Schemas {
estimated_rows_total?: number | null;
}
+ /**
+ * * `manual` - Manual
+ * * `agent_mcp` - Agent (MCP)
+ * * `cold_run` - Cold Run
+ * * `stale_refresh` - Stale Refresh
+ * * `auto_refresh` - Auto Refresh
+ * * `experiment_config_change` - Experiment Config Change
+ * * `metric_config_change` - Metric Config Change
+ * * `config_change` - Config Change
+ * * `experiment_launch` - Experiment Launch
+ * * `experiment_stop` - Experiment Stop
+ * * `experiment_update` - Experiment Update
+ * * `timeseries_sync` - Timeseries Sync
+ */
+ export type ExperimentMetricsRecalculationTriggerEnum = typeof ExperimentMetricsRecalculationTriggerEnum[keyof typeof ExperimentMetricsRecalculationTriggerEnum];
+
+
+ export const ExperimentMetricsRecalculationTriggerEnum = {
+ Manual: 'manual',
+ AgentMcp: 'agent_mcp',
+ ColdRun: 'cold_run',
+ StaleRefresh: 'stale_refresh',
+ AutoRefresh: 'auto_refresh',
+ ExperimentConfigChange: 'experiment_config_change',
+ MetricConfigChange: 'metric_config_change',
+ ConfigChange: 'config_change',
+ ExperimentLaunch: 'experiment_launch',
+ ExperimentStop: 'experiment_stop',
+ ExperimentUpdate: 'experiment_update',
+ TimeseriesSync: 'timeseries_sync',
+ } as const;
+
/**
* * `uploading` - Uploading
* * `completed` - Completed
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 09a3b20d5318..7111b6398fec 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -831,7 +831,7 @@ const ExperimentMetricsRecalculationCreateSchema = () => {
const experimentMetricsRecalculationCreate = (): ToolBase<
ReturnType<typeof ExperimentMetricsRecalculationCreateSchema>,
- WithPostHogUrl<Schemas.ExperimentMetricsRecalculation>
+ WithPostHogUrl<Schemas.ExperimentMetricsRecalculationJob>
> => ({
name: 'experiment-metrics-recalculation-create',
schema: ExperimentMetricsRecalculationCreateSchema(),
@@ -840,7 +840,7 @@ const experimentMetricsRecalculationCreate = (): ToolBase<
params: z.infer<ReturnType<typeof ExperimentMetricsRecalculationCreateSchema>>
) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.ExperimentMetricsRecalculation>({
+ const result = await context.api.request<Schemas.ExperimentMetricsRecalculationJob>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/metrics_recalculation/`,
})
@@ -861,7 +861,7 @@ const ExperimentMetricsRecalculationLatestRetrieveSchema = () => {
const experimentMetricsRecalculationLatestRetrieve = (): ToolBase<
ReturnType<typeof ExperimentMetricsRecalculationLatestRetrieveSchema>,
- WithPostHogUrl<Schemas.ExperimentMetricsRecalculation>
+ WithPostHogUrl<Schemas.ExperimentMetricsRecalculationLatest>
> =>
withUiApp('experiment-results', {
name: 'experiment-metrics-recalculation-latest-retrieve',
@@ -871,7 +871,7 @@ const experimentMetricsRecalculationLatestRetrieve = (): ToolBase<
params: z.infer<ReturnType<typeof ExperimentMetricsRecalculationLatestRetrieveSchema>>
) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.ExperimentMetricsRecalculation>({
+ const result = await context.api.request<Schemas.ExperimentMetricsRecalculationLatest>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/metrics_recalculation/latest/`,
})
@@ -906,7 +906,7 @@ const ExperimentMetricsRecalculationRetrieveSchema = () => {
const experimentMetricsRecalculationRetrieve = (): ToolBase<
ReturnType<typeof ExperimentMetricsRecalculationRetrieveSchema>,
- WithPostHogUrl<Schemas.ExperimentMetricsRecalculation>
+ WithPostHogUrl<Schemas.ExperimentMetricsRecalculationRun>
> => ({
name: 'experiment-metrics-recalculation-retrieve',
schema: ExperimentMetricsRecalculationRetrieveSchema(),
@@ -915,7 +915,7 @@ const experimentMetricsRecalculationRetrieve = (): ToolBase<
params: z.infer<ReturnType<typeof ExperimentMetricsRecalculationRetrieveSchema>>
) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.ExperimentMetricsRecalculation>({
+ const result = await context.api.request<Schemas.ExperimentMetricsRecalculationRun>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/metrics_recalculation/${encodeURIComponent(String(params.recalculation_id))}/`,
})