:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): heal metric recalculation gaps on page load (#108119)
Rodrigo Iloro69f5a1c9418e
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsxindex 4db021de8043..22cab1d48a58 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx@@ -663,12 +663,13 @@ export function MetricRowGroup({const { triggerRecalculation } = useActions(experimentMetricsLogic({ experiment }))/**- * On the recalculation flow, retrying a single metric just re-runs the whole recalculation (plus- * exposures), same as the manual reload. The legacy flow retries the single metric in place.+ * On the recalculation flow, retrying a single metric re-runs the whole recalculation (plus exposures)+ * as a manual_retry: the run reuses the latest window, so metrics with rows load from cache and only+ * the failed ones recompute. The legacy flow retries the single metric in place.*/const handleRetry = (): void => {if (featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- triggerRecalculation()+ triggerRecalculation('manual_retry')refreshExperimentResults(true, 'manual')return}diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex ba45fa890f6c..bebc1ba23673 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -323,7 +323,10 @@ describe('experimentMetricsLogic', () => {})mountLogic()- await expectLogic(logic).toDispatchActions(['setCurrentRecalculation', 'setPrimaryMetricsResultsErrors'])+ await expectLogic(logic)+ .toDispatchActions(['setCurrentRecalculation', 'setPrimaryMetricsResultsErrors'])+ // Every metric has a result row, failed or not, so the failure alone must not start a new run.+ .toNotHaveDispatchedActions(['triggerRecalculation'])// The successful secondary metric loads its result.expect(logic.values.secondaryMetricsResults[0]).toEqual(secondaryResult)@@ -392,37 +395,85 @@ describe('experimentMetricsLogic', () => {expect(capturedBody).toEqual({ trigger: 'cold_run' })})- it('heals a completed run that is missing a metric added after it finished', async () => {- // A metric added after the last run finished is absent from that run's results. The run's own- // counts look complete, so only a uuid comparison catches the gap; without the heal the new metric- // stays stuck loading on every page load.- // Derive the extra metric from a real fixture metric so it stays fully typed; only the uuid differs.- const addedMetric = { ...EXPERIMENT.metrics[0], uuid: 'added-after-run-uuid' }- const experimentWithExtraMetric: Experiment = {- ...EXPERIMENT,- metrics: [...EXPERIMENT.metrics, addedMetric],- }+ // Derive the extra metric from a real fixture metric so it stays fully typed; only the uuid differs.+ const experimentWithExtraMetric: Experiment = {+ ...EXPERIMENT,+ metrics: [...EXPERIMENT.metrics, { ...EXPERIMENT.metrics[0], uuid: 'added-after-run-uuid' }],+ }++ it.each([+ {+ // The run's own counts look complete; only a uuid comparison catches the added metric.+ name: 'a completed run that is missing a metric added after it finished',+ latest: completedRecalculation,+ experiment: experimentWithExtraMetric,+ },+ {+ // A transient error that ran out of attempts: the backend marks it retriable, so a new run+ // can fix it. The window is reused, so only this metric recomputes.+ name: 'a failed run whose failure is retriable',+ latest: {+ ...partialFailureRecalculation,+ metric_errors: {+ [PRIMARY_METRIC_UUID]: {+ step: 'calculation',+ message: 'boom',+ error_type: 'timeout',+ retriable: true,+ },+ },+ },+ experiment: EXPERIMENT,+ },+ ])('heals $name with a heal_latest_run', async ({ latest, experiment }) => {let capturedBody: anyuseMocks({get: {- // Completed run that covers only the two original metrics, not the newly added one.- '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [- 200,- completedRecalculation,- ],+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [200, latest],},post: {+ // Return a terminal run so triggerRecalculation finishes without arming a poll timer.'/api/projects/:team_id/experiments/:id/metrics_recalculation/': async ({ request }) => {capturedBody = await request.json()return [201, completedRecalculation2]},},})- logic = experimentMetricsLogic({ experiment: experimentWithExtraMetric })+ logic = experimentMetricsLogic({ experiment })logic.mount()await expectLogic(logic).toDispatchActions(['triggerRecalculation']).toFinishAllListeners()- expect(capturedBody).toEqual({ trigger: 'experiment_config_change' })+ expect(capturedBody).toEqual({ trigger: 'heal_latest_run' })+ })++ it.each([+ {+ // The metric config, the data, or a resource limit must change first: only a user retry re-runs it.+ name: 'a non-retriable failure',+ metricError: { step: 'calculation', message: 'boom', error_type: 'validation_error', retriable: false },+ },+ {+ // A run recorded before the flag existed: never heal it, or every page load would start a run.+ name: 'a failure recorded without the retriable flag',+ metricError: { step: 'calculation', message: 'boom' },+ },+ ])('does not heal $name', async ({ metricError }) => {+ const createMock = jest.fn(() => [201, completedRecalculation2])+ useMocks({+ get: {+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [+ 200,+ { ...partialFailureRecalculation, metric_errors: { [PRIMARY_METRIC_UUID]: metricError } },+ ],+ },+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },+ })+ logic = experimentMetricsLogic({ experiment: EXPERIMENT })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadLatestRecalculation']).toFinishAllListeners()+ expect(createMock).not.toHaveBeenCalled()+ expect(logic.values.primaryMetricsResultsErrors[0]).toEqual({ detail: 'boom' })})it('applies terminal results and resumes polling the active run (reload while recalculating)', async () => {@@ -551,7 +602,7 @@ describe('experimentMetricsLogic', () => {.toFinishAllListeners()// The placeholder timeseries result is shown immediately for the metric it covered.expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)- // A real cold_run is fired to fill the gap (secondary).+ // The fallback is not a run, so there is no window to heal: a cold_run starts fresh.expect(capturedBody).toEqual({ trigger: 'cold_run' })})diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex eea7d134529a..c2be3252ba20 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -22,6 +22,7 @@ import type {ExperimentMetricsRecalculationJobApi,ExperimentMetricsRecalculationRequestTriggerEnumApi,ExperimentMetricsRecalculationRunApi,+ ResultSourceEnumApi,} from 'products/experiments/frontend/generated/api.schemas'import { type ExperimentSavedMetric, sharedMetricsToExperimentMetrics } from './utils'@@ -104,21 +105,60 @@ const currentMetricUuids = (experiment: Experiment): string[] =>...metricsInOrder(experiment, 'secondary').map((metric) => metric.uuid),].filter((uuid): uuid is string => !!uuid)-/** Metric uuids a run resolved: a computed result or a recorded failure. */-const coveredMetricUuids = (recalculation: RecalculationPayload): string[] => [- ...(recalculation.results ?? []).map(({ metric_uuid }) => metric_uuid),- ...Object.keys((recalculation.metric_errors as Record<string, unknown> | null) ?? {}),-]+/** One entry of `metric_errors`: a metric's terminal failure, as the backend records it. */+type MetricErrorEntry = { step?: string; message?: string; error_type?: string; retriable?: boolean }++const metricErrorEntries = (recalculation: RecalculationPayload): Record<string, MetricErrorEntry> =>+ (recalculation.metric_errors as Record<string, MetricErrorEntry> | null) ?? {}++/**+ * Metric uuids a run resolved: a result, or a failure a new run cannot fix. A retriable failure reads as a+ * gap and heals; an entry without the flag predates it and counts as covered, so an old run never heals in a loop.+ */+const coveredMetricUuids = (recalculation: RecalculationPayload): string[] => {+ const errors = metricErrorEntries(recalculation)+ const retriable = new Set(Object.keys(errors).filter((uuid) => errors[uuid]?.retriable === true))+ return [...(recalculation.results ?? []).map(({ metric_uuid }) => metric_uuid), ...Object.keys(errors)].filter(+ (uuid) => !retriable.has(uuid)+ )+}++/**+ * The trigger that fills a gap, by where the latest payload came from. A real run is healed in place:+ * heal_latest_run reuses its window, so metrics with rows load from cache. The timeseries fallback is+ * not a run, so there is no window to reuse and nothing to dim; a cold_run starts fresh.+ */+const HEAL_TRIGGER_BY_RESULT_SOURCE = {+ recalculation: 'heal_latest_run',+ timeseries_fallback: 'cold_run',+} as const satisfies Record<ResultSourceEnumApi, ExperimentMetricsRecalculationRequestTriggerEnumApi>++const recalculationHasGap = (experiment: Experiment, recalculation: RecalculationPayload): boolean => {+ if (+ recalculation.status === RECALCULATION_STATUSES.pending ||+ recalculation.status === RECALCULATION_STATUSES.in_progress+ ) {+ return false+ }++ const coveredUuids = new Set(coveredMetricUuids(recalculation))++ return (+ recalculation.completed_metrics + recalculation.failed_metrics < recalculation.total_metrics ||+ currentMetricUuids(experiment).some((uuid) => !coveredUuids.has(uuid))+ )+}type MetricErrorState = { detail: string } | nulltype ResolveByUuid<T> = (uuid: string) => T/**- * Metric uuids that currently show something, a result OR an error, across primary and secondary. These- * are the metrics a non-cold recalculation dims in place: they have a stale value (or a stale error) to- * keep on screen while the fresh one loads. Errored metrics must be included so they dim on reload too.+ * Metric uuids that currently show something, a result OR an error, across primary and secondary. A+ * non-cold recalculation marks these as recalculating: the stale value (or stale error) stays on screen and+ * the metric header shows a loading tag until the fresh one lands. Errored metrics are included so a+ * retry shows the tag too.*/-const metricUuidsToDim = (+const metricUuidsToMarkRecalculating = (experiment: Experiment,primaryResults: readonly (CachedNewExperimentQueryResponse | undefined)[],secondaryResults: readonly (CachedNewExperimentQueryResponse | undefined)[],@@ -158,7 +198,7 @@ const resolveResultByUuid = (* failed row's error_message.*/const resolveErrorByUuid = (recalculation: RecalculationPayload): ResolveByUuid<MetricErrorState> => {- const metricErrors = (recalculation.metric_errors as Record<string, { message?: string }> | null) ?? {}+ const metricErrors = metricErrorEntries(recalculation)const failedResultMessageByUuid = new Map((recalculation.results ?? []).filter((r) => r.status === 'failed' && r.error_message)@@ -570,7 +610,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([// metrics that failed this poll...Object.keys((recalculation.metric_errors as Record<string, unknown> | null) ?? {}),])- // Un-dim each metric whose fresh result or failure just landed; the rest stay dimmed until they do.+ // Clear the tag on each metric whose fresh result or failure just landed; the rest keep it until they do.actions.setRecalculatingMetricUuids(values.recalculatingMetricUuids.filter((uuid) => !landed.has(uuid)))}}@@ -633,7 +673,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([*/if (recalculation.active_run) {actions.setRecalculatingMetricUuids(- metricUuidsToDim(+ metricUuidsToMarkRecalculating(props.experiment,values.primaryMetricsResults,values.secondaryMetricsResults,@@ -650,40 +690,12 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([}/**- * A run has a gap when its own resolved count fell short of its total (also after a reset and- * relaunch), or when a metric was added after it finished so a current metric uuid is absent- * from its results. The run's own counts look complete in the second case, so only a uuid- * comparison catches it.+ * Fill any gap in a terminal latest (a real run, a failed run, or the timeseries fallback);+ * otherwise the uncovered metric shows a perpetual loading state, since nothing else re-runs+ * on page load. What is already shown stays visible and cells update in place as the run polls.*/- const coveredUuids = new Set(coveredMetricUuids(recalculation))- const missingCurrentMetric = currentMetricUuids(props.experiment).some(- (uuid) => !coveredUuids.has(uuid)- )- const hasGap =- recalculation.completed_metrics + recalculation.failed_metrics < recalculation.total_metrics ||- missingCurrentMetric-- /**- * The timeseries fallback is daily data the backend serves when no run exists yet. Accept it- * as is: a cold_run only when a metric has no point (the daily workflow never computes- * retention metrics, for one), so a page load does not recompute results the timeseries- * already holds. The placeholder stays visible and cells update in place as the run polls.- */- if (recalculation.result_source === 'timeseries_fallback') {- if (hasGap) {- actions.triggerRecalculation('cold_run')- }- return- }-- /**- * Heal a completed run with a gap; otherwise the new metric shows a perpetual loading state,- * since nothing else re-runs on page load. Advance the window with experiment_config_change- * rather than reuse a cutoff that may predate the new start_date.- */- if (recalculation.status === RECALCULATION_STATUSES.completed && hasGap) {- actions.triggerRecalculation('experiment_config_change')- return+ if (recalculationHasGap(props.experiment, recalculation)) {+ actions.triggerRecalculation(HEAL_TRIGGER_BY_RESULT_SOURCE[recalculation.result_source])}} catch (error: any) {if (error?.status === 404) {@@ -756,12 +768,13 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([return}/**- * Dim the metrics that already show something (a value or an error) so they read as- * "refreshing" until the new result streams in. Cold runs have nothing prior, so nothing to dim.+ * Mark the metrics that already show something (a value or an error) as recalculating, so+ * they keep their value and show a loading tag until the new result streams in. Cold runs+ * have nothing prior, so nothing to mark.*/if (trigger !== 'cold_run') {actions.setRecalculatingMetricUuids(- metricUuidsToDim(+ metricUuidsToMarkRecalculating(props.experiment,values.primaryMetricsResults,values.secondaryMetricsResults,diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex b0d7ecf10534..660e0bdf8234 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1494,7 +1494,14 @@ class _ExperimentMetricsRecalculationBaseSerializer(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_errors = serializers.JSONField(+ read_only=True,+ help_text=(+ "Terminal failure per metric_uuid: {step, message, error_type, retriable, timestamp}. retriable is "+ "true when a transient error exhausted its attempts, so a heal_latest_run or manual_retry can "+ "succeed; false when the metric config, the data, or a resource limit must change first"+ ),+ )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")diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex 90e06ea680d3..95fd64c81245 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -132,7 +132,67 @@ Between the edit and that run, it shows no result for a metric whose fingerprint### Triggers and the cold-start payload-A recalc row records what caused it, in `trigger` (`Trigger` on the model). The set is more than a manual click: `MANUAL`, `AGENT_MCP`, `COLD_RUN`, `STALE_REFRESH`, `AUTO_REFRESH`, config-change triggers (`EXPERIMENT_CONFIG_CHANGE`, `METRIC_CONFIG_CHANGE`), and experiment lifecycle triggers (`EXPERIMENT_LAUNCH`, `EXPERIMENT_STOP`, `EXPERIMENT_UPDATE`). This lets the analytics and the UI tell a user click apart from an automatic refresh.+A recalc row records what caused it, in `trigger` (`Trigger` on the model).+The set is more than a manual click.+User and frontend triggers: `MANUAL`, `MANUAL_RETRY`, `COLD_RUN`, `HEAL_LATEST_RUN`, `EXPERIMENT_CONFIG_CHANGE`, `METRIC_CONFIG_CHANGE`.+Server-side triggers: `AGENT_MCP` (set by the view from the client header), `TIMESERIES_SYNC` and `SCHEDULED` (written by their workflows).+Deprecated values stay for old rows: `STALE_REFRESH`, `AUTO_REFRESH`, `CONFIG_CHANGE`, `EXPERIMENT_LAUNCH`, `EXPERIMENT_STOP`, `EXPERIMENT_UPDATE`.+`RequestTrigger` is the subset a client may send on POST; the request serializer rejects the rest.+This lets the analytics and the UI tell a user click apart from an automatic heal.++The trigger decides the window.+`_resolve_query_to` reuses the latest terminal run's `query_to` for `METRIC_CONFIG_CHANGE`, `MANUAL_RETRY` and `HEAL_LATEST_RUN` (`_REUSE_WINDOW_TRIGGERS`), so the metrics that already have rows load from cache and only the missing or failed ones recompute.+Every other trigger advances the window to now, so every metric recomputes.+A window-reusing run keeps the current values on screen and shows a loading tag on the metrics it recomputes; a `cold_run` has nothing prior to keep.++#### What the frontend sends, by the state of `latest`++The frontend reads `GET /metrics_recalculation/latest` on page load and starts at most one run from it.+It never heals a pending or in-progress run; it polls that run instead.++| State of `latest` | Trigger | Window |+| --------------------------------------------------------------------- | ---------------------------------------------- | -------- |+| 404: no run and no timeseries point | `cold_run` | advances |+| Timeseries fallback with a gap (`result_source: timeseries_fallback`) | `cold_run` | advances |+| Terminal run with a result row missing, and no error for that metric | `heal_latest_run` | reuses |+| Terminal run with a failed metric whose error is retriable | `heal_latest_run` | reuses |+| Terminal run with a failed metric whose error is not retriable | nothing; the retry button sends `manual_retry` | reuses |+| Refresh button | `manual` | advances |+| Metric added or changed | `metric_config_change` | reuses |+| Experiment config changed | `experiment_config_change` | advances |++A run that failed before discovery has no metrics and no anchored window.+The frontend treats it as a gap and sends `heal_latest_run`; `_resolve_query_to` skips a run without `query_to`, so it reuses the newest earlier window, or advances when there is none, as a `cold_run` would.+This is rare: Temporal retries the workflow before it reaches that state.++```mermaid+flowchart TD+ latest[GET latest] --> status{status}+ status -->|404| cold[cold_run]+ status -->|pending or in_progress| poll[poll the active run]+ status -->|terminal| source{result_source}+ source -->|timeseries_fallback with a gap| cold+ source -->|recalculation| gap{missing row or retriable failure?}+ gap -->|yes| heal[heal_latest_run]+ gap -->|no, non-retriable failure| retry[retry button sends manual_retry]+ gap -->|no| done[show results]+ classDef advance fill:#f54e00,stroke:#f54e00,color:#fff;+ classDef reuse fill:#1d4aff,stroke:#1d4aff,color:#fff;+ class cold advance;+ class heal,retry reuse;+```++Red nodes advance the window; blue nodes reuse it.++#### Retriable failures++A metric's terminal failure lands in `metric_errors` as `{step, message, error_type, retriable, timestamp}`.+`error_type` is the same taxonomy as the `experiment metric error` event (`classify_experiment_query_error`).+`retriable` is the backend's own decision, not a frontend mapping of `error_type`: it is true when a transient error (`timeout`, `rate_limited`, `server_error`) used its final attempt, and false when the calc activity failed permanently (`validation_error`, `out_of_memory`, `byte_limit`, `insufficient_data`, a `ValueError`, or a discovery failure).+A retriable failure reads as a gap, so the page load heals it; a non-retriable one waits for the user, because a new run with the same inputs fails the same way.+An entry without the flag predates it and counts as non-retriable, so an old run never heals in a loop.++#### The cold-start payload`TIMESERIES_SYNC` is the one trigger no user or lifecycle event emits. The daily timeseries workflows write it as soon as each experiment's own metric activities finish: one completed row per experiment per daily run, with the run's timeseries points copied under the recalc fingerprint at a shared `query_to`, so the `latest` read serves fresh daily data without a recompute. The inline and saved metric workflows share that row: the first to finish creates it, the second adds the copies it lacks. See "Handing fresh points to the recalculation reader" in `posthog/temporal/experiments/README.md`.diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 3d190c5238aa..acf607309667 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -405,17 +405,26 @@ def _capture_results_refresh_completed(update: RecalculationProgressUpdate) -> N# ----------------------------------------------------------------------------def _record_failure(recalculation_id: str, metric_uuid: str, step: str, message: str) -> None:+def _record_failure(+ recalculation_id: str, metric_uuid: str, step: str, message: str, *, error_type: str, retriable: bool+) -> None:"""Merge the error entry into metric_errors under a row lock (no lost updates between concurrent failures).Idempotent on Temporal retries: the dict is keyed by metric_uuid, so re-running this for the same metric- just overwrites the existing entry with a fresh timestamp.+ just overwrites the existing entry with a fresh timestamp. retriable is True only when a transient error+ exhausted its attempts, so the frontend heals that metric on page load and leaves the rest to a user retry."""capped = message[:_MAX_ERROR_MESSAGE_LENGTH]with transaction.atomic():recalc = ExperimentMetricsRecalculation.objects.select_for_update().get(id=recalculation_id)metric_errors = recalc.metric_errors or {}- metric_errors[metric_uuid] = {"step": step, "message": capped, "timestamp": timezone.now().isoformat()}+ metric_errors[metric_uuid] = {+ "step": step,+ "message": capped,+ "error_type": error_type,+ "retriable": retriable,+ "timestamp": timezone.now().isoformat(),+ }recalc.metric_errors = metric_errorsrecalc.save(update_fields=["metric_errors"])@@ -525,9 +534,11 @@ def _store_result()-def _fail(recalculation_id: str, metric_uuid: str, step: str, message: str) -> MetricRecalculationResult:- """Record a failure on the job (lookup step: job-only; calculation step: also persists a result row upstream)."""- _record_failure(recalculation_id, metric_uuid, step, message)+def _fail(+ recalculation_id: str, metric_uuid: str, step: str, message: str, *, error_type: str+) -> MetricRecalculationResult:+ """Record a permanent failure on the job (lookup step: job-only; calculation step: also persists a result row upstream)."""+ _record_failure(recalculation_id, metric_uuid, step, message, error_type=error_type, retriable=False)_clear_retry(recalculation_id, metric_uuid)return MetricRecalculationResult(metric_uuid=metric_uuid, success=False, error_step=step, error_message=message[:_MAX_ERROR_MESSAGE_LENGTH]@@ -687,7 +698,13 @@ def _calculate_experiment_metric_for_recalculation_sync(try:experiment = Experiment.objects.get(id=experiment_id, deleted=False)except Experiment.DoesNotExist:- return _fail(recalculation_id, metric_uuid, "discovery", f"Experiment {experiment_id} not found or deleted")+ return _fail(+ recalculation_id,+ metric_uuid,+ "discovery",+ f"Experiment {experiment_id} not found or deleted",+ error_type="validation_error",+ )metric_dict = find_metric_dict(experiment, metric_uuid)if metric_dict is None:@@ -696,10 +713,17 @@ def _calculate_experiment_metric_for_recalculation_sync(metric_uuid,"discovery",f"Metric {metric_uuid} not found in experiment {experiment_id}",+ error_type="validation_error",)if not experiment.start_date:- return _fail(recalculation_id, metric_uuid, "discovery", f"Experiment {experiment_id} has no start_date")+ return _fail(+ recalculation_id,+ metric_uuid,+ "discovery",+ f"Experiment {experiment_id} has no start_date",+ error_type="validation_error",+ )config_fp = compute_metric_fingerprint(metric_dict,@@ -731,7 +755,7 @@ def _calculate_experiment_metric_for_recalculation_sync(calc_started_at = time.perf_counter()query_from = experiment.start_date- def record_terminal_error(message: str, error_type: str) -> None:+ def record_terminal_error(message: str, error_type: str, *, retriable: bool) -> None:_store_result(recalculation_id=recalculation_id,experiment_id=experiment_id,@@ -744,7 +768,9 @@ def _calculate_experiment_metric_for_recalculation_sync(error_message=message,query_id=client_query_id,)- _record_failure(recalculation_id, metric_uuid, "calculation", message)+ _record_failure(+ recalculation_id, metric_uuid, "calculation", message, error_type=error_type, retriable=retriable+ )_capture_experiment_metric_event(experiment,metric_uuid,@@ -847,12 +873,12 @@ def _calculate_experiment_metric_for_recalculation_sync(},trigger=state.trigger,)- return _fail(recalculation_id, metric_uuid, "calculation", message)+ return _fail(recalculation_id, metric_uuid, "calculation", message, error_type="insufficient_data")except (ConcurrencyLimitExceeded, ClickHouseAtCapacity) as e:message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]if is_final_attempt:- record_terminal_error(message, classify_experiment_query_error(e))+ record_terminal_error(message, classify_experiment_query_error(e), retriable=True)logger.warning("Experiment metric recalculation deferred by ClickHouse backpressure",experiment_id=experiment_id,@@ -912,7 +938,7 @@ def _calculate_experiment_metric_for_recalculation_sync(},)if is_final_attempt or is_permanent:- record_terminal_error(message, error_type)+ record_terminal_error(message, error_type, retriable=not is_permanent)logger.exception("Experiment metric recalculation failed",experiment_id=experiment_id,diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex b6cab72f5ba3..7a37a91b3d15 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -670,7 +670,8 @@ class TestCalculateActivity(BaseTest):assert result.error_step == "discovery"recalc.refresh_from_db()assert len(recalc.metric_errors) == 1- assert "m1" in recalc.metric_errors+ assert recalc.metric_errors["m1"]["error_type"] == "validation_error"+ assert recalc.metric_errors["m1"]["retriable"] is Falsedef test_bad_metric_type_fails_at_calculation(self):# An unknown metric_type is unschedulable, so the calc lookup fails the metric permanently@@ -798,6 +799,31 @@ class TestCalculateActivity(BaseTest):recalc.refresh_from_db()assert recalc.metric_retries == {}+ @parameterized.expand(+ [+ # A transient error that used its final attempt: a heal or manual retry can still succeed.+ ("exhausted_transient", RuntimeError("transient blip"), "server_error", True),+ # Permanent errors stop on the first attempt and need a config or data change first.+ ("validation", ValidationError("bad hogql"), "validation_error", False),+ ("value_error", ValueError("bad metric"), "server_error", False),+ ]+ )+ def test_terminal_failure_records_error_type_and_retriability(+ self, name: str, exc: Exception, expected_error_type: str, expected_retriable: bool+ ):+ exp = self._experiment(flag_key=f"calc-terminal-{name}", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ with patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:+ mock_runner.return_value.run.side_effect = exc+ with pytest.raises(Exception):+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=True)++ recalc.refresh_from_db()+ entry = recalc.metric_errors["m1"]+ assert entry["error_type"] == expected_error_type+ assert entry["retriable"] is expected_retriable+def test_terminal_failure_clears_retry_state(self):# A metric that retried and then failed for good must not keep a stale "retrying" entry alongside# its terminal error.diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 7176d0ba7e36..5e1de05b847d 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2216,7 +2216,7 @@ export interface ExperimentMetricsRecalculationJobApi {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 */+ /** Terminal failure per metric_uuid: {step, message, error_type, retriable, timestamp}. retriable is true when a transient error exhausted its attempts, so a heal_latest_run or manual_retry can succeed; false when the metric config, the data, or a resource limit must change first */readonly metric_errors: unknown/** When the job was created */readonly created_at: string@@ -2295,7 +2295,7 @@ export interface ExperimentMetricsRecalculationRunApi {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 */+ /** Terminal failure per metric_uuid: {step, message, error_type, retriable, timestamp}. retriable is true when a transient error exhausted its attempts, so a heal_latest_run or manual_retry can succeed; false when the metric config, the data, or a resource limit must change first */readonly metric_errors: unknown/** When the job was created */readonly created_at: string@@ -2377,7 +2377,7 @@ export interface ExperimentMetricsRecalculationLatestApi {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 */+ /** Terminal failure per metric_uuid: {step, message, error_type, retriable, timestamp}. retriable is true when a transient error exhausted its attempts, so a heal_latest_run or manual_retry can succeed; false when the metric config, the data, or a resource limit must change first */readonly metric_errors: unknown/** When the job was created */readonly created_at: stringdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fb69ca67ce6b..fb172ec55e54 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42684,7 +42684,7 @@ export namespace Schemas {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 */+ /** Terminal failure per metric_uuid: {step, message, error_type, retriable, timestamp}. retriable is true when a transient error exhausted its attempts, so a heal_latest_run or manual_retry can succeed; false when the metric config, the data, or a resource limit must change first */readonly metric_errors: unknown;/** When the job was created */readonly created_at: string;@@ -42775,7 +42775,7 @@ export namespace Schemas {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 */+ /** Terminal failure per metric_uuid: {step, message, error_type, retriable, timestamp}. retriable is true when a transient error exhausted its attempts, so a heal_latest_run or manual_retry can succeed; false when the metric config, the data, or a resource limit must change first */readonly metric_errors: unknown;/** When the job was created */readonly created_at: string;@@ -42858,7 +42858,7 @@ export namespace Schemas {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 */+ /** Terminal failure per metric_uuid: {step, message, error_type, retriable, timestamp}. retriable is true when a transient error exhausted its attempts, so a heal_latest_run or manual_retry can succeed; false when the metric config, the data, or a resource limit must change first */readonly metric_errors: unknown;/** When the job was created */readonly created_at: string;