: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): surface recalculation retries in the metrics UI (#72205)
Rodrigo Iloroa479440d059a
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsxindex 3def0a539b01..925335363d44 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx@@ -33,6 +33,7 @@ import { SkeletonResultCells } from '~/scenes/experiments/MetricsView/shared/Chaimport { ChartLoadingState } from '~/scenes/experiments/MetricsView/shared/ChartLoadingState'import { useChartColors } from '~/scenes/experiments/MetricsView/shared/colors'import { MetricHeader } from '~/scenes/experiments/MetricsView/shared/MetricHeader'+import { MetricRetryState } from '~/scenes/experiments/MetricsView/shared/MetricRetryState'import {FIXED_HEIGHT_STYLE,getMinHeightStyle,@@ -596,7 +597,7 @@ export function MetricRowGroup({useActions(experimentLogic)const { variants } = useValues(experimentLogic)const { featureFlags } = useValues(featureFlagLogic)- const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))+ const { isRecalculating, metricRetries } = useValues(experimentMetricsLogic({ experiment }))const { triggerRecalculation } = useActions(experimentMetricsLogic({ experiment }))/**@@ -727,6 +728,22 @@ export function MetricRowGroup({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'+ // Between failed attempts the chart column (and only it) explains the wait; every other cell keeps+ // its skeleton. One cell spans the variant rows, so subsequent rows omit theirs.+ const metricRetry = metric.uuid ? metricRetries[metric.uuid] : undefined+ const retryChartCell = metricRetry ? (+ <td+ className={clsx(+ 'p-0 align-middle text-center relative overflow-hidden',+ !isLastMetric && 'border-b',+ bg+ )}+ rowSpan={skeletonVariantKeys.length}+ style={getScaledHeightStyle(skeletonVariantKeys.length)}+ >+ <MetricRetryState retry={metricRetry} />+ </td>+ ) : undefinedreturn (<>@@ -754,6 +771,7 @@ export function MetricRowGroup({<SkeletonResultCellsvariantKey={skeletonVariantKeys[0]}className={clsx(bg, skeletonVariantKeys.length === 1 && 'border-b')}+ chartCell={retryChartCell}detailsCell={<tdclassName={clsx(@@ -784,6 +802,7 @@ export function MetricRowGroup({<SkeletonResultCellsvariantKey={variantKey}className={clsx(bg, index === skeletonVariantKeys.length - 2 && 'border-b')}+ chartCell={metricRetry ? null : undefined}/></tr>))}diff --git a/frontend/src/scenes/experiments/MetricsView/shared/ChartLoadingSkeleton.tsx b/frontend/src/scenes/experiments/MetricsView/shared/ChartLoadingSkeleton.tsxindex 1db3f5bc4f34..13fa3bcec639 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/ChartLoadingSkeleton.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/ChartLoadingSkeleton.tsx@@ -9,11 +9,15 @@ export function SkeletonResultCells({variantKey,className,detailsCell,+ chartCell,}: {variantKey: stringclassName: string// Rendered between P-value and Chart, with rowSpan, on the baseline row only; matches the real layoutdetailsCell?: JSX.Element+ // Replaces the chart-column skeleton: pass a custom cell (e.g. the retry state, with rowSpan, on the+ // baseline row) or null to omit the cell entirely (subsequent rows covered by that rowSpan)+ chartCell?: JSX.Element | null}): JSX.Element {return (<>@@ -52,14 +56,18 @@ export function SkeletonResultCells({{detailsCell}{/* Chart: mirrors ChartCell's wrapper so the bar lands where the real chart will */}- <td- className={clsx('p-0 align-middle text-center relative overflow-hidden', className)}- style={FIXED_HEIGHT_STYLE}- >- <div className="px-3">- <LemonSkeleton className="h-3 w-full" />- </div>- </td>+ {chartCell !== undefined ? (+ chartCell+ ) : (+ <td+ className={clsx('p-0 align-middle text-center relative overflow-hidden', className)}+ style={FIXED_HEIGHT_STYLE}+ >+ <div className="px-3">+ <LemonSkeleton className="h-3 w-full" />+ </div>+ </td>+ )}</>)}diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsxindex 8541675c8202..aad242b59f74 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx@@ -20,6 +20,7 @@ import type { Breakdown, EventsNode, ExperimentMetric } from '~/queries/schema/simport { NodeKind } from '~/queries/schema/schema-general'import type { Experiment } from '~/types'+import { MetricRetryDetails } from './MetricRetryState'import { MetricTitle } from './MetricTitle'import { getMetricTag } from './utils'@@ -200,8 +201,9 @@ export const MetricHeader = ({const canAddBreakdown = (metric.breakdownFilter?.breakdowns || []).length < MAX_BREAKDOWNSconst recalculationEnabled = useFeatureFlag('EXPERIMENTS_METRICS_RECALCULATION')- const { isMetricRecalculating } = useValues(experimentMetricsLogic({ experiment }))+ const { isMetricRecalculating, metricRetries } = useValues(experimentMetricsLogic({ experiment }))const showRecalculatingTag = recalculationEnabled && isMetricRecalculating(metric.uuid)+ const metricRetry = recalculationEnabled && metric.uuid ? metricRetries[metric.uuid] : undefinedreturn (<div className="text-xs font-semibold flex flex-col justify-between h-full">@@ -282,11 +284,24 @@ export const MetricHeader = ({)}</div><div className="flex flex-wrap items-center gap-1">- {showRecalculatingTag && (- <LemonTag type="highlight" size="medium" icon={<Spinner textColored />}>- Recalculating- </LemonTag>- )}+ {(showRecalculatingTag || metricRetry) &&+ (metricRetry ? (+ <LemonDropdown+ placement="bottom-start"+ showArrow+ trigger="hover"+ closeOnClickInside={false}+ overlay={<MetricRetryDetails retry={metricRetry} className="max-w-100 p-2" />}+ >+ <LemonTag type="warning" size="medium" icon={<Spinner textColored />}>+ Retry {metricRetry.attempt} of {metricRetry.max_attempts}+ </LemonTag>+ </LemonDropdown>+ ) : (+ <LemonTag type="highlight" size="medium" icon={<Spinner textColored />}>+ Recalculating+ </LemonTag>+ ))}<LemonTag type="muted" size="small">{getMetricTag(metric)}</LemonTag>diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricRetryState.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricRetryState.tsxnew file mode 100644index 000000000000..ef179ac057a7--- /dev/null+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricRetryState.tsx@@ -0,0 +1,86 @@+import clsx from 'clsx'+import { useEffect, useState } from 'react'++import { dayjs } from 'lib/dayjs'+import { Spinner } from 'lib/lemon-ui/Spinner'++import type { MetricRetryInfo } from '~/scenes/experiments/experimentMetricsLogic'++/** Placeholder until the background recalculation doc ships; nothing here changes when it does. */+export const RECALCULATION_RETRY_DOCS_URL = 'https://posthog.com/docs/experiments/background-recalculation'++const RETRY_REASONS: Record<string, string> = {+ rate_limited: 'The ClickHouse cluster is busy right now.',+ timeout: 'The query took too long to complete.',+ out_of_memory: 'The query ran out of memory.',+ server_error: 'Something went wrong while computing this metric.',+}++export function retryReason(errorType: string): string {+ return RETRY_REASONS[errorType] ?? RETRY_REASONS.server_error+}++function countdownLabel(target: string | null | undefined): string {+ if (!target) {+ return 'shortly'+ }+ const seconds = Math.round((new Date(target).getTime() - Date.now()) / 1000)+ if (seconds <= 0) {+ return 'any moment now'+ }+ if (seconds < 90) {+ return `in ${seconds}s`+ }+ return dayjs().to(dayjs(target))+}++/**+ * Human-readable countdown to an estimated retry ("in 45s", "in 3 minutes", "any moment now"),+ * ticking every second. The estimate comes from the backend's retry schedule; worker pickup adds+ * slack after it passes, hence "any moment now" rather than flipping to an error.+ */+export function useRetryCountdownLabel(target: string | null | undefined): string {+ const [label, setLabel] = useState<string>(() => countdownLabel(target))+ useEffect(() => {+ setLabel(countdownLabel(target))+ if (!target) {+ return+ }+ const intervalId = setInterval(() => setLabel(countdownLabel(target)), 1000)+ return () => clearInterval(intervalId)+ }, [target])+ return label+}++/** The full retry explanation: reason, the server error that triggered it, counter, countdown, help link.+ * Shared between the chart-cell state and the metric header tag's popover. */+export function MetricRetryDetails({ retry, className }: { retry: MetricRetryInfo; className?: string }): JSX.Element {+ const countdown = useRetryCountdownLabel(retry.next_retry_at)+ return (+ <div className={clsx('flex flex-col gap-0.5', className)}>+ <div className="flex items-center gap-1.5 text-xs font-medium">+ <Spinner textColored className="text-accent" />+ <span>{retryReason(retry.error_type)}</span>+ </div>+ {retry.message && (+ <div className="text-muted text-xs italic line-clamp-2" title={retry.message}>+ {retry.message}+ </div>+ )}+ <div className="text-muted text-xs">+ Retry {retry.attempt} of {retry.max_attempts} · next attempt {countdown} ·{' '}+ {/* <Link to={RECALCULATION_RETRY_DOCS_URL} target="_blank">+ Why do we retry?+ </Link> */}+ </div>+ </div>+ )+}++export function MetricRetryState({ retry }: { retry: MetricRetryInfo }): JSX.Element {+ return (+ <div className="flex h-full items-center justify-center px-3">+ <MetricRetryDetails retry={retry} className="items-center text-center" />+ </div>+ )+}diff --git a/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsxindex b3de78f85dc8..595c8dd99667 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx@@ -9,6 +9,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'import { 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'@@ -20,7 +21,7 @@ import type { ExperimentMetricsRecalculationApi } from 'products/experiments/fro* EXPERIMENTS_METRICS_RECALCULATION (see ExperimentView).*/export function RecalculationStatus({ experiment }: { experiment: Experiment }): JSX.Element | null {- const { recalculationDisplayState, currentRecalculation, liveRowsProgress } = useValues(+ const { recalculationDisplayState, currentRecalculation, liveRowsProgress, metricRetries, nextRetryAt } = useValues(experimentMetricsLogic({ experiment }))/**@@ -38,6 +39,8 @@ export function RecalculationStatus({ experiment }: { experiment: Experiment }):<InFlightStatusrecalculation={currentRecalculation}liveRowsProgress={liveRowsProgress}+ retryingCount={Object.keys(metricRetries).length}+ nextRetryAt={nextRetryAt}notifyWhenResultsReady={notifyWhenResultsReady}onSubscribe={subscribeToResultsNotification}/>@@ -47,26 +50,33 @@ export function RecalculationStatus({ experiment }: { experiment: Experiment }):function InFlightStatus({recalculation,liveRowsProgress,+ retryingCount,+ nextRetryAt,notifyWhenResultsReady,onSubscribe,}: {recalculation: ExperimentMetricsRecalculationApi | nullliveRowsProgress: { recalculationId: string; rowsRead: number; estimatedRows: number } | null+ retryingCount: number+ nextRetryAt: string | nullnotifyWhenResultsReady: booleanonSubscribe: () => void}): JSX.Element {const succeeded = recalculation?.completed_metrics ?? 0const failed = recalculation?.failed_metrics ?? 0const total = recalculation?.total_metrics ?? 0+ const nextRetryLabel = useRetryCountdownLabel(nextRetryAt)/*** Pending (not yet resolved, not currently sampled as running) keeps the segment truthful in those gaps.+ * Retrying metrics are unresolved too, but get their own slice so slow runs read as alive, not stuck.*/- const pending = Math.max(0, total - succeeded - failed)+ const pending = Math.max(0, total - succeeded - failed - retryingCount)return (<StatusBar><span className="flex items-center gap-1.5 whitespace-nowrap"><Spinner textColored className="text-sm text-accent" />- <CountsSegment pending={pending} succeeded={succeeded} failed={failed} />+ <CountsSegment pending={pending} retrying={retryingCount} succeeded={succeeded} failed={failed} />+ {retryingCount > 0 && <span className="text-muted text-xs">· next retry {nextRetryLabel}</span>}<span className="text-muted text-xs">· running in the background</span><Tooltip title="We're computing each metric against the latest data. This runs server-side so you can leave this page; results appear as each metric finishes."><IconInfo className="text-muted text-xs" />@@ -106,10 +116,12 @@ function StatusBar({ children }: { children: React.ReactNode }): JSX.Element {function CountsSegment({pending,+ retrying,succeeded,failed,}: {pending: number+ retrying: numbersucceeded: numberfailed: number}): JSX.Element {@@ -119,6 +131,13 @@ function CountsSegment({if (pending > 0) {parts.push(<span key="pending">{pending} pending</span>)}+ if (retrying > 0) {+ parts.push(+ <span key="retrying" className="text-warning">+ {retrying} retrying+ </span>+ )+ }parts.push(<span key="succeeded" className="text-success">{succeeded} succeededdiff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex 9ed4e00b54ef..abd65803062c 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -839,6 +839,48 @@ describe('experimentMetricsLogic', () => {logic.actions.setCurrentRecalculation(asRecalc({ ...inProgressRecalculation, id: 'recalc-3' }))expect(logic.values.liveRowsProgress).toBeNull()})++ it('metricRetries drops resolved entries and nextRetryAt picks the soonest', () => {+ // Server-side the terminal write clears entries, but a crash between the result write and the+ // clear can leave one behind; the outcome must win over the stale "retrying" state.+ const draft = { ...EXPERIMENT, status: undefined, start_date: null, end_date: null } as Experiment+ logic = experimentMetricsLogic({ experiment: draft })+ logic.mount()++ logic.actions.setCurrentRecalculation(+ asRecalc({+ ...inProgressRecalculation,+ metric_retries: {+ [PRIMARY_METRIC_UUID]: {+ attempt: 2,+ max_attempts: 8,+ error_type: 'rate_limited',+ next_retry_at: '2026-06-10T00:01:00Z',+ },+ [SECONDARY_METRIC_UUID]: { attempt: 1, max_attempts: 8, error_type: 'server_error' },+ 'resolved-uuid': {+ attempt: 1,+ max_attempts: 8,+ error_type: 'server_error',+ next_retry_at: '2026-06-10T00:00:30Z',+ },+ },+ results: [+ {+ metric_uuid: 'resolved-uuid',+ status: 'completed',+ result: primaryResult,+ error_message: null,+ },+ ],+ })+ )+ expect(Object.keys(logic.values.metricRetries).sort()).toEqual(+ [PRIMARY_METRIC_UUID, SECONDARY_METRIC_UUID].sort()+ )+ // The resolved metric's earlier next_retry_at must not win; entries without one are skipped.+ expect(logic.values.nextRetryAt).toEqual('2026-06-10T00:01:00Z')+ })})describe('tab focus does not clobber a loaded run', () => {diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex 66704038bc0c..6f4587bd26e5 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -57,6 +57,16 @@ export const RECALCULATION_STATUSES = {export type RecalculationStatuses = (typeof RECALCULATION_STATUSES)[keyof typeof RECALCULATION_STATUSES]+/** Transient per-metric retry state written by the calc activity between failed attempts. */+export interface MetricRetryInfo {+ attempt: number+ max_attempts: number+ error_type: string+ /** The server error that triggered the retry, surfaced so the UI can show why. */+ message?: string+ next_retry_at?: string+}+/*** transform shared metrics into experiment metrics.*/@@ -156,6 +166,8 @@ export interface experimentMetricsLogicValues {recalculationId: stringrowsRead: number} | null+ metricRetries: Record<string, MetricRetryInfo>+ nextRetryAt: string | nullprimaryMetricsResults: CachedNewExperimentQueryResponse[]primaryMetricsResultsErrors: (unknown | null)[]recalculatingMetricUuids: string[]@@ -262,6 +274,10 @@ export interface experimentMetricsLogicMeta {}totalMetricsCount: (arg: any) => numberlastRefresh: (currentRecalculation: ExperimentMetricsRecalculationApi | null) => string | null+ metricRetries: (+ currentRecalculation: ExperimentMetricsRecalculationApi | null+ ) => Record<string, MetricRetryInfo>+ nextRetryAt: (metricRetries: Record<string, MetricRetryInfo>) => string | nullrecalculationDisplayState: (recalculationLoading: boolean,currentRecalculation: ExperimentMetricsRecalculationApi | null@@ -392,6 +408,27 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([(s) => [s.currentRecalculation],(recalc: ExperimentMetricsRecalculationApi | null): string | null => recalc?.query_to ?? null,],+ metricRetries: [+ (s) => [s.currentRecalculation],+ (recalc: ExperimentMetricsRecalculationApi | null): Record<string, MetricRetryInfo> => {+ const raw = (recalc?.metric_retries ?? {}) as Record<string, MetricRetryInfo>+ const landed = new Set([+ ...(recalc?.results ?? []).map(({ metric_uuid }) => metric_uuid),+ ...Object.keys((recalc?.metric_errors as Record<string, unknown> | null) ?? {}),+ ])+ return Object.fromEntries(Object.entries(raw).filter(([uuid]) => !landed.has(uuid)))+ },+ ],+ nextRetryAt: [+ (s) => [s.metricRetries],+ (metricRetries: Record<string, MetricRetryInfo>): string | null => {+ const upcoming = Object.values(metricRetries)+ .map(({ next_retry_at }) => next_retry_at)+ .filter((value): value is string => !!value)+ .sort()+ return upcoming[0] ?? null+ },+ ],recalculationDisplayState: [(s) => [s.recalculationLoading, s.currentRecalculation],(