: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): dim metric results when recalculating, and isolate loading indicators (#65672)
Rodrigo Iloroc6e1083e473c
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsxindex 6d32ffa2e41b..94b007133ab1 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx@@ -591,11 +591,18 @@ export function MetricRowGroup({useActions(experimentLogic)const { variants } = useValues(experimentLogic)const { featureFlags } = useValues(featureFlagLogic)- const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))+ const { isRecalculating, isMetricRecalculating } = useValues(experimentMetricsLogic({ experiment }))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.+ /**+ * Dim the stale value in place while a non-cold recalc refreshes this metric; block clicks on it.+ */+ const recalculatingClassName = isMetricRecalculating(metric.uuid) ? 'opacity-40 pointer-events-none' : ''++ /**+ * 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.+ */const handleRetry = (): void => {if (featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {triggerRecalculation()@@ -713,8 +720,11 @@ export function MetricRowGroup({})}- // Skeleton-with-variants while results compute: keeps the final row layout so data fills in place- if (!error && (isLoading || exposuresLoading)) {+ /**+ * Skeleton-with-variants only when there's no result yet. A metric that already has a value renders+ * its result, dimmed while recalculating, so a refresh never flashes the skeleton over real data.+ */+ if (!result && !error && (isLoading || exposuresLoading)) {const skeletonVariantKeys = variants.length > 0 ? variants.map((variant) => variant.key) : ['control']const bg = isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'@@ -787,7 +797,10 @@ export function MetricRowGroup({return (<>- <tr className="hover:bg-bg-hover group [&:last-child>td]:border-b-0" style={noResultStateStyle}>+ <tr+ className={clsx('hover:bg-bg-hover group [&:last-child>td]:border-b-0', recalculatingClassName)}+ style={noResultStateStyle}+ >{/* Metric column - always visible */}<tdclassName={`w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${@@ -892,7 +905,10 @@ export function MetricRowGroup({)}{/* Baseline row */}- <tr className="hover:bg-bg-hover group [&:last-child>td]:border-b-0" style={FIXED_HEIGHT_STYLE}>+ <tr+ className={clsx('hover:bg-bg-hover group [&:last-child>td]:border-b-0', recalculatingClassName)}+ style={FIXED_HEIGHT_STYLE}+ >{/* Metric column - with rowspan */}<tdclassName={`w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${!isLastMetric ? 'border-b' : ''} ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}@@ -1022,7 +1038,7 @@ export function MetricRowGroup({return (<trkey={`${metric.uuid}-${variant.key}`}- className="hover:bg-bg-hover group [&:last-child>td]:border-b-0"+ className={clsx('hover:bg-bg-hover group [&:last-child>td]:border-b-0', recalculatingClassName)}style={FIXED_HEIGHT_STYLE}onMouseEnter={(e) => handleTooltipMouseEnter(e, variant)}onMouseLeave={handleTooltipMouseLeave}diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsxindex 08cd2b30e814..d2271f201a2d 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx@@ -19,6 +19,15 @@ import { MAX_AXIS_RANGE } from './constants'import { MetricRowGroup } from './MetricRowGroup'import { TableHeader } from './TableHeader'+/**+ * True when any metric in this section is still being recalculated. Curried by the section's metrics so+ * each table judges only its own; exposures loading is the caller's concern.+ */+const sectionHasRecalculatingMetric =+ (metrics: ExperimentMetric[]) =>+ (recalculatingMetricUuids: string[]): boolean =>+ metrics.some(({ uuid }) => !!uuid && recalculatingMetricUuids.includes(uuid))+interface MetricsTableProps {metrics: ExperimentMetric[]results: NewExperimentQueryResponse[]@@ -39,7 +48,7 @@ export function MetricsTable({showDetailsModal = true,}: MetricsTableProps): JSX.Element {const { experiment, exposuresLoading } = useValues(experimentLogic)- const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))+ const { recalculatingMetricUuids } = useValues(experimentMetricsLogic({ experiment }))const { experimentsConfig } = useValues(experimentsConfigLogic)const teamDefaultSequentialEnabled = experimentsConfig?.default_sequential_testing_enabled ?? falseconst sequentialTestingEnabled = resolveSequentialEnabled(@@ -95,6 +104,14 @@ export function MetricsTable({)}+ /**+ * Show this section's loader while any of its own metrics is loading: recalculating in place, or cold+ * (no result and no error yet). Exposures load globally, so they count for whichever section has metrics.+ */+ const hasColdMetric = metrics.some((_, index) => !results[index] && !errors[index])+ const sectionLoading =+ sectionHasRecalculatingMetric(metrics)(recalculatingMetricUuids) || hasColdMetric || exposuresLoading+return (<div className="w-full overflow-x-auto rounded-md border"><table className="w-full border-collapse text-sm">@@ -111,7 +128,7 @@ export function MetricsTable({axisRange={axisRange}statsMethod={experiment.stats_config?.method || ExperimentStatsMethod.Bayesian}sequentialTestingEnabled={sequentialTestingEnabled}- loading={isRecalculating}+ loading={sectionLoading}/><tbody>{metrics.map((metric, index) => {diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex 64835a7d91fc..cb0566a6b9bc 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -82,7 +82,7 @@ const coldRunInProgressPartial = {completed_metrics: 1,results: [{ metric_uuid: PRIMARY_METRIC_UUID, status: 'completed', result: primaryResult, error_message: null }],}-// Same intermediate payload but for a manual run — must NOT apply mid-flight.+// Same intermediate payload but for a manual run; it now applies mid-flight, same as cold runs.const manualInProgressPartial = { ...coldRunInProgressPartial, trigger: 'manual' }// Create responses that seed the stored trigger for the polled run.const coldRunPending = { ...pendingRecalculation, trigger: 'cold_run', total_metrics: 2 }@@ -219,6 +219,109 @@ describe('experimentMetricsLogic', () => {expect(logic.values.recalculationLoading).toBe(false)})+ it('surfaces a discovery-step failure (metric_errors entry, no result row) loaded on mount', async () => {+ // A discovery/query-build failure records a metric_errors entry but never writes a result row,+ // so `results` has no entry for the failed metric. The error must still surface.+ const discoveryFailure = {+ ...completedRecalculation,+ id: 'recalc-3',+ completed_metrics: 1,+ failed_metrics: 1,+ metric_errors: { [PRIMARY_METRIC_UUID]: { step: 'discovery', message: 'no events' } },+ results: [+ {+ metric_uuid: SECONDARY_METRIC_UUID,+ status: 'completed',+ result: secondaryResult,+ error_message: null,+ },+ ],+ }+ useMocks({+ get: {+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [+ 200,+ discoveryFailure,+ ],+ },+ })+ mountLogic()++ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation', 'setPrimaryMetricsResultsErrors'])++ expect(logic.values.primaryMetricsResultsErrors[0]).toEqual({ detail: 'no events' })+ })++ it('counts failures toward progress and surfaces errors while a run is still in progress', async () => {+ // Mirrors a real poll response: both computed metrics failed, the rest is still pending.+ const inProgressWithFailures = {+ ...baseRecalculation,+ id: 'recalc-fail',+ status: 'in_progress',+ trigger: 'manual',+ total_metrics: 3,+ completed_metrics: 0,+ failed_metrics: 2,+ metric_errors: {+ [PRIMARY_METRIC_UUID]: { step: 'calculation', message: 'boom-primary' },+ [SECONDARY_METRIC_UUID]: { step: 'calculation', message: 'boom-secondary' },+ },+ results: [+ { metric_uuid: PRIMARY_METRIC_UUID, status: 'failed', result: null, error_message: 'boom-primary' },+ {+ metric_uuid: SECONDARY_METRIC_UUID,+ status: 'failed',+ result: null,+ error_message: 'boom-secondary',+ },+ ],+ }+ useMocks({+ get: {+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/:recalc_id/': () => [+ 200,+ inProgressWithFailures,+ ],+ },+ post: {+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [201, manualPending],+ },+ })+ jest.useFakeTimers()+ mountLogic()++ await jest.advanceTimersByTimeAsync(0)+ for (let i = 0; i < 2; i++) {+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)+ }++ // Errors must surface in-row even mid-flight.+ expect(logic.values.primaryMetricsResultsErrors[0]).toEqual({ detail: 'boom-primary' })+ // Progress must count failures, not just completes; otherwise a fully-failing run shows 0/3 forever.+ expect(logic.values.recalculationProgress).toEqual({ completed: 2, total: 3 })+ jest.useRealTimers()+ })++ it('surfaces per-metric errors when the latest run loaded on mount is a partial failure', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [+ 200,+ partialFailureRecalculation,+ ],+ },+ })+ mountLogic()++ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation', 'setPrimaryMetricsResultsErrors'])++ // The successful secondary metric loads its result.+ expect(logic.values.secondaryMetricsResults[0]).toEqual(secondaryResult)+ // The failed primary metric must keep its error for the in-row box, not be cleared by its null result.+ expect(logic.values.primaryMetricsResultsErrors[0]).toEqual({ detail: 'boom' })+ })+it('shows no error toast on 404 (a fresh recalc is triggered instead)', async () => {useMocks({get: {@@ -640,7 +743,7 @@ describe('experimentMetricsLogic', () => {expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)})- it('on a non-cold_run, does not apply results until the run is terminal', async () => {+ it('on a non-cold_run, applies partial results mid-flight so refreshed values stream in', async () => {useMocks({get: {'/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],@@ -661,9 +764,9 @@ describe('experimentMetricsLogic', () => {await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)}- // In progress with the same partial payload, but a manual run leaves cells untouched mid-flight.+ // Still in progress, but the finished metric from the partial payload is already on screen.expect(logic.values.currentRecalculation).toEqual(expect.objectContaining({ status: 'in_progress' }))- expect(logic.values.primaryMetricsResults).toEqual([])+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)})})diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex d6233fe09d7d..9b387442e83a 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -76,7 +76,9 @@ const sharedMetricsToExperimentMetrics = (},}))-// One metric type's metrics (inline + shared) in the order results are positionally mapped against.+/**+ * One metric type's metrics (inline + shared) in the order results are positionally mapped against.+ */const metricsInOrder = (experiment: Experiment, type: 'primary' | 'secondary'): ExperimentMetric[] => {const sharedMetrics = sharedMetricsToExperimentMetrics(experiment.saved_metrics as ExperimentSavedMetric[], type)const inline = (type === 'primary' ? experiment.metrics : experiment.metrics_secondary) || []@@ -86,6 +88,26 @@ const metricsInOrder = (experiment: Experiment, type: 'primary' | 'secondary'):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.+ */+const metricUuidsToDim = (+ experiment: Experiment,+ primaryResults: readonly (CachedNewExperimentQueryResponse | undefined)[],+ secondaryResults: readonly (CachedNewExperimentQueryResponse | undefined)[],+ primaryErrors: readonly (unknown | null)[],+ secondaryErrors: readonly (unknown | null)[]+): string[] => [+ ...metricsInOrder(experiment, 'primary')+ .map((metric) => metric.uuid as string)+ .filter((_, index) => primaryResults[index] !== undefined || !!primaryErrors[index]),+ ...metricsInOrder(experiment, 'secondary')+ .map((metric) => metric.uuid as string)+ .filter((_, index) => secondaryResults[index] !== undefined || !!secondaryErrors[index]),+]+/*** One value per metric, in `metricsInOrder` order. Curried: bind (experiment, type) once, then feed a* per-uuid resolver, the only thing that differs between results and errors.@@ -95,7 +117,9 @@ const alignByMetricPosition =<T>(resolve: ResolveByUuid<T>): T[] =>metricsInOrder(experiment, type).map((metric) => resolve(metric.uuid as string))-// Resolver: a polled metric's computed result, or undefined if the run hasn't produced one yet.+/**+ * Resolver: a polled metric's computed result, or undefined if the run hasn't produced one yet.+ */const resolveResultByUuid = (polledResults: readonly { metric_uuid: string; result: unknown }[] | undefined): ResolveByUuid<CachedNewExperimentQueryResponse> => {@@ -139,6 +163,8 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([setPrimaryMetricsResultsErrors: (errors: (unknown | null)[]) => ({ errors }),setSecondaryMetricsResultsErrors: (errors: (unknown | null)[]) => ({ errors }),setRecalculationLoading: (loading: boolean) => ({ loading }),+ // The metrics still showing a stale value while a non-cold recalc refreshes them in place.+ setRecalculatingMetricUuids: (uuids: string[]) => ({ uuids }),}),reducers({currentRecalculation: [@@ -179,6 +205,12 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([setSecondaryMetricsResultsErrors: (_, { errors }) => errors,},],+ recalculatingMetricUuids: [+ [] as string[],+ {+ setRecalculatingMetricUuids: (_, { uuids }) => uuids,+ },+ ],}),selectors({// True while a recalculation is being fetched or is still running.@@ -191,12 +223,22 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([],recalculationProgress: [(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): { completed: number; total: number } => ({- completed: recalc?.completed_metrics ?? 0,+ completed: (recalc?.completed_metrics ?? 0) + (recalc?.failed_metrics ?? 0),total: recalc?.total_metrics ?? 0,}),],lastRefresh: [(s) => [s.currentRecalculation], (recalc): string | null => recalc?.query_to ?? null],+ // Predicate the table uses to dim a metric whose stale value is still being refreshed.+ isMetricRecalculating: [+ (s) => [s.recalculatingMetricUuids],+ (uuids): ((metricUuid: string | undefined) => boolean) => {+ const recalculating = new Set(uuids)+ return (metricUuid) => !!metricUuid && recalculating.has(metricUuid)+ },+ ],}),listeners(({ actions, values, props, cache }) => {const flagEnabled = (): boolean => !!values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]@@ -310,6 +352,17 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([actions.setSecondaryMetricsResultsErrors(mergeErrors(values.secondaryMetricsResultsErrors, nextSecondaryErrors, nextSecondaryResults))++ if (values.recalculatingMetricUuids.length > 0) {+ const landed = new Set([+ // metrics that produced a fresh result this poll+ ...(recalculation.results ?? []).map(({ metric_uuid }) => metric_uuid),+ // 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.+ actions.setRecalculatingMetricUuids(values.recalculatingMetricUuids.filter((uuid) => !landed.has(uuid)))+ }}return {@@ -407,6 +460,21 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([if (!experimentIsLaunched()) {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.+ */+ if (trigger !== 'cold_run') {+ actions.setRecalculatingMetricUuids(+ metricUuidsToDim(+ props.experiment,+ values.primaryMetricsResults,+ values.secondaryMetricsResults,+ values.primaryMetricsResultsErrors,+ values.secondaryMetricsResultsErrors+ )+ )+ }/*** guard against invalid project or experiment. bail and clear recalculation* loading state@@ -533,12 +601,11 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([recalculation.status === RECALCULATION_STATUSES.in_progress) {/**- * Cold-start runs have no prior results to preserve, so surface each metric as it lands- * (applyResults is positional and idempotent); other triggers keep terminal-only apply.+ * Surface each metric as it lands rather than waiting for terminal. applyResults is+ * positional and idempotent, and it un-dims each recalculating metric as its result+ * arrives, so the table streams fresh values in place.*/- if (recalculation.trigger === 'cold_run') {- applyResults(recalculation)- }+ applyResults(recalculation)actions.pollRecalculation(recalculationId)return}diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pyindex 8fb836f013d2..27fe12766d40 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -13,6 +13,10 @@ ALL_OUTCOMES = (OUTCOME_PASS, OUTCOME_DIVERGENCE, OUTCOME_PATH_FLIP, OUTCOME_ERR# Cap CanaryMetricResult.detail so a pathological error message can't bloat the Temporal payload.MAX_CANARY_DETAIL_LENGTH = 1000+# Max attempts for the per-metric recalculation activity. Shared between the workflow's RetryPolicy and the+# activity so the activity knows when it's on its final attempt.+MAX_METRIC_ATTEMPTS = 5+@dataclasses.dataclassclass ExperimentMetricsRecalculationWorkflowInputs:diff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.pyindex 19d6afec803a..bbc74dadf98e 100644--- a/products/experiments/backend/temporal/recalculation_activities.py+++ b/products/experiments/backend/temporal/recalculation_activities.py@@ -8,6 +8,7 @@ and lets the logic be unit-tested without the activity decorator.import temporalio.activityfrom products.experiments.backend.temporal.models import (+ MAX_METRIC_ATTEMPTS,ExperimentMetricToRecalculate,MetricRecalculationResult,RecalculationProgressUpdate,@@ -49,6 +50,9 @@ async def calculate_experiment_metric_for_recalculation(PostHog event so the capture path doesn't have to re-query the saved-metric M2M to resolve it. Defaults to"primary" so existing call sites and tests that don't pass it remain valid."""+ # Temporal attempt is 1-based. On the final attempt, a transient failure must be persisted rather than+ # re-raised, so the row reflects the real outcome once retries are exhausted.+ is_final_attempt = temporalio.activity.info().attempt >= MAX_METRIC_ATTEMPTSreturn await _calculate_experiment_metric_for_recalculation_sync(- experiment_id, metric_uuid, recalculation_id, query_to, metric_type+ experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt)diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex a6af39f4fd37..83fa2561c802 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -420,6 +420,7 @@ def _calculate_experiment_metric_for_recalculation_sync(recalculation_id: str,query_to: str,metric_type: str = "primary",+ is_final_attempt: bool = True,) -> MetricRecalculationResult:close_old_connections()@@ -574,8 +575,9 @@ def _calculate_experiment_metric_for_recalculation_sync(except Exception as e:# Could be transient (ClickHouse connection blip, network glitch, or other infrastructure issue).- # Record the failure so the UI sees it, then re-raise so Temporal's retry policy gets a chance.- # If all attempts fail, the workflow's gather(return_exceptions=True) counts this metric as failed.+ # Persist the failure ONLY on the final attempt, then re-raise; on earlier attempts we re-raise+ # without persisting so Temporal retries while the metric stays in its loading/dim state on the+ # frontend, rather than flashing an error for a failure that may yet succeed on the next attempt.# StatisticError and ZeroDivisionError are handled above as permanent and return success=False.message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]capture_exception(@@ -586,22 +588,24 @@ def _calculate_experiment_metric_for_recalculation_sync("recalculation_id": recalculation_id,},)- _store_result(- experiment_id=experiment_id,- metric_uuid=metric_uuid,- recalc_fp=recalc_fp,- query_from=experiment.start_date,- query_to=query_to_dt,- status=ExperimentMetricResult.Status.FAILED,- result=None,- error_message=message,- query_id=client_query_id,- )- _record_failure(recalculation_id, metric_uuid, "calculation", message)+ if is_final_attempt:+ _store_result(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ recalc_fp=recalc_fp,+ query_from=experiment.start_date,+ query_to=query_to_dt,+ status=ExperimentMetricResult.Status.FAILED,+ result=None,+ error_message=message,+ query_id=client_query_id,+ )+ _record_failure(recalculation_id, metric_uuid, "calculation", message)logger.exception("Experiment metric recalculation failed",experiment_id=experiment_id,metric_uuid=metric_uuid,+ is_final_attempt=is_final_attempt,)# No 'experiment metric error' event here: this path re-raises and Temporal retries, so# emitting would double-count per attempt. The final failed count is reported once at thediff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.pyindex d09f7f3ec7d0..8ae4299e02e9 100644--- a/products/experiments/backend/temporal/recalculation_workflow.py+++ b/products/experiments/backend/temporal/recalculation_workflow.py@@ -9,6 +9,7 @@ from posthog.temporal.common.base import PostHogWorkflowwith temporalio.workflow.unsafe.imports_passed_through():from products.experiments.backend.temporal.models import (+ MAX_METRIC_ATTEMPTS,ExperimentMetricsRecalculationWorkflowInputs,RecalculationProgressUpdate,)@@ -120,7 +121,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):# metrics don't re-stampede in lockstep. Permanent failures don't reach here# (StatisticError/ZeroDivisionError are recorded and returned, never raised).retry_policy=RetryPolicy(- maximum_attempts=5,+ maximum_attempts=MAX_METRIC_ATTEMPTS,initial_interval=timedelta(seconds=5),backoff_coefficient=2.0,maximum_interval=timedelta(seconds=60),diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex 55a6c4c806f6..8ca9718fb708 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -48,9 +48,10 @@ def _calculate(recalculation_id: str,query_to: str,metric_type: str = "primary",+ is_final_attempt: bool = True,):with patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"):- return _calculate_raw(experiment_id, metric_uuid, recalculation_id, query_to, metric_type)+ return _calculate_raw(experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt)@pytest.mark.django_db(transaction=True)@@ -415,6 +416,29 @@ class TestCalculateActivity(BaseTest):recalc.refresh_from_db()assert "s1" in recalc.metric_errors+ def test_transient_failure_is_not_persisted_until_the_final_attempt(self):+ # A retryable (transient) failure on a non-final attempt re-raises for Temporal to retry but must NOT+ # persist a FAILED row or a metric_errors entry, so the frontend keeps the metric loading instead of+ # flashing an error for a failure that may still succeed. The final attempt persists it.+ exp = self._experiment(flag_key="calc-transient", 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 = RuntimeError("transient blip")++ # Non-final attempt: re-raises, but nothing is recorded.+ with pytest.raises(RuntimeError, match="transient blip"):+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False)+ recalc.refresh_from_db()+ assert recalc.metric_errors == {}+ assert not ExperimentMetricResult.objects.filter(experiment=exp, metric_uuid="m1").exists()++ # Final attempt: now the failure is persisted for the UI.+ with pytest.raises(RuntimeError, match="transient blip"):+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=True)+ recalc.refresh_from_db()+ assert "m1" in recalc.metric_errors+def test_query_to_is_passed_as_override_end_date_to_runner(self):# The run's shared query_to MUST be threaded into the ClickHouse query bounds via# override_end_date, not just stored on the result row. Without override_end_date the runner falls back