Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): experiment recalculation logic (#61721)

Rodrigo Iloro64fcb5e9aa50
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 526fca1d882f..e02edd81e63b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4947,9 +4947,9 @@ snapshots:
scenes-app-experiments--draft-experiment--light:
hash: v1.k794b7964.70dc18be765207610c6040e3f2c831c2c5ebaa1726a330e293fa8c00d49a5cd9.rPoZm0K5sQEKk_6Br3PLSxWDdh9BKzhs7EHtpqP54KM
scenes-app-experiments--experiment-asymmetric-intervals--dark:
- hash: v1.k794b7964.16714efab3de01b2493cb8a6b54c57ebc8a35c794f9a3de128031c3a5f53b086.fsBLZMEaO-B8vm419k-olm5zmSJxatxWS7dV0uKycC8
+ hash: v1.k794b7964.fc2050d652b4b774371f15f0ba4b990456bf2fb649ab8dc9adf9f4a2dc492225.5y1-n_EbA8M78Q3ZJAZFa7EI2MhApaJLBtmtxzMiMyE
scenes-app-experiments--experiment-asymmetric-intervals--light:
- hash: v1.k794b7964.fce1cce1ac8905e25fff816ea028c9b9446fc6aff025a246db7009700192b697.8WGowBmtZO2lG-3xIKK9P7eD3MYNjTRHGCBTxn1nog0
+ hash: v1.k794b7964.c8bb88e7e610f901989a0a06ad295ccb0cf9e20366a3f5bafac532116be38ca9.TsIYV_gxMZ9GzBxCBLMPuqhxiOVIg-eZ4wivz65yOfA
scenes-app-experiments--experiment-frequentist-five-variants--dark:
hash: v1.k794b7964.09d23fd44208249b4fd1555fcbdb941118bc2825dc7142bd6ba96335c9cb8f32.AipSypBKnQguXtQO9tkCsdO9IVj-_0bHqjCnFe0BE-U
scenes-app-experiments--experiment-frequentist-five-variants--light:
@@ -4959,9 +4959,9 @@ snapshots:
scenes-app-experiments--experiment-frequentist-two-variants--light:
hash: v1.k794b7964.8ee2590f5129b8a545e1f0029bacad4b43b58d943c207424f7cff0908b42bab5.Cax-2Fdq70E_grVVDy_Sa5OSmss7McsfaIVRFV4Vmfk
scenes-app-experiments--experiment-with-funnel-metric--dark:
- hash: v1.k794b7964.a6b8d933157f59f997c8e85e81316b2f1c57667880fc6184c8a0b5ebac8acf76.K_vAMn8GGLpJ0_ZzlpEiPeb98TwI8iWauzAZ6KjUYBM
+ hash: v1.k794b7964.2cac96d1b33c2486aee903970d242e08be029907d5fc61c990768fb7f7e5d614.UuVKdZyW3x7X0tudzz7cDmZPYovPoylKKKqrIsiAZeA
scenes-app-experiments--experiment-with-funnel-metric--light:
- hash: v1.k794b7964.052d9c26d1a9fdd501f1c1c70747733af00910fd869fffd84bd6f395b08a41ed.6ytL6IZuCRWo69vUBJJmtHXviUcl1Twtt-cB0dAVxYw
+ hash: v1.k794b7964.5e7a0c81eb042c762c634e2c69fef02a39891d9c66b65251a1e4675031150509.fcgUg9g-plu2c8pDYTMhggw9wWTVjvIJPkH5SQBCwo8
scenes-app-experiments--experiment-with-legacy-funnels-query--dark:
hash: v1.k794b7964.5d2468e37868c1f7eb92bd6194d06bb4c58ec1e67eb97f2381bb554b6a50c25c.A-5pOsMFnOdqWaayNMR2WpehMVHF6c-PZ4aGq6L4Gvg
scenes-app-experiments--experiment-with-legacy-funnels-query--light:
@@ -4971,21 +4971,21 @@ snapshots:
scenes-app-experiments--experiment-with-legacy-trends-query--light:
hash: v1.k794b7964.476bc34ecdbe85ef6886e553757264580dd35d0afc71b55b6bf607b88e2a0f5e.SL7IVmhf0cAXYdc1HVumK6BOfyp5v4FenuFRP3oAw4E
scenes-app-experiments--experiment-with-mean-metric--dark:
- hash: v1.k794b7964.f32fa3131603f30394bd13b14d4b53aadca18ca6d18e3bf71316f373d0454764.-sKoD2uDTLRtT9pkVgVelW-UtVv8E2jvkNuBYuSaa8c
+ hash: v1.k794b7964.ae5a863f1fc38edf2644a152758144c450199cfe550f6ff386ecb57724ff180f.aTBXlu3mSnnFkZI1PKUEGW-i8MFQJW5h01geDRc4aR4
scenes-app-experiments--experiment-with-mean-metric--light:
- hash: v1.k794b7964.6176f725a455c1064ffc4fcdc1a29cff4a2debb1496fc08e6efe67299250798b.HOBqtBdGgZaJWDxi15dzwlI_YojmUNRhHVIO43U3pMQ
+ hash: v1.k794b7964.d54c6393436339dff2ebadef137768c411729811cb44e1db07ae6a5c5a207aa4.wqbDtqAqziCJ5dCStxex83FmwFYQoEKG9-bnvYAo-Uk
scenes-app-experiments--experiment-with-multiple-metrics--dark:
- hash: v1.k794b7964.95fd3aff7460e851d88e3dd8d9dfa5c6023b715f7cda2c849cefb5c361ec9559.ZIwd8rMpnJ1bmP1Cd2ahFz2rJbmSmbLB5z5DJF3vWuA
+ hash: v1.k794b7964.a05a080c49cd653e4075ec6de5a8d8c20c31eb4d2b147aa4664d1ed8419805f4.f8lBvLUdUWq8xJJ7Ff6A7MP_RrrRHEmv3wdgNsAuGwI
scenes-app-experiments--experiment-with-multiple-metrics--light:
- hash: v1.k794b7964.606b4610f2e035fe660f6b8cb89b88d6f9757c5abe6117a0e7cfa84432fab17e.dNHaFfFq68PedICOmTDCzx6rCMc-MbG694Xc_YYAGbw
+ hash: v1.k794b7964.294576581159e9c30b2e279b435e4fc7f2fa4ab1db70221576f1f153911d3777.0aCfn8iANAt_E5b_n2fMiqfKmBTfnFC4jSxkid7AX50
scenes-app-experiments--experiment-with-multiple-metrics-reordered--dark:
- hash: v1.k794b7964.e18320b97b008a57060912dd3717b22426cc24000aac9503e8e3a007fe5806c0.8qbDFm5IEyL-a3Vh7W9EkSfWDqOplQHIAFHuX9x3elU
+ hash: v1.k794b7964.184f63b7c4c1ed980bbfa9c37c423eb62f4d1b0d8368739f48c8463b44551510.L_JnhI_mVojFqSh5yL_-xbq1R0930t7At-OxcMbPTA0
scenes-app-experiments--experiment-with-multiple-metrics-reordered--light:
- hash: v1.k794b7964.5e3fb29456b6d37dd4940ed634289719e528a383c73d1da2105107de24897ef4.dTifbyJDGSHo6uJNXII3aE6j3QLfDvDHHhNrOmdUlzQ
+ hash: v1.k794b7964.12d868ac89d24cda7f15c77293cbf6719fc2b4b0ab887c586d1571b283f7208a.1Ol7GRb2ZteHad6cvUINmdTWktppGFs2hMHS90O72wg
scenes-app-experiments--experiment-with-ratio-metric--dark:
- hash: v1.k794b7964.dcf1010d35a4ecede509be5982874859c63cfa89b13e0bcd959d37e2da30108f.km4IOS52Or5nvI09iUH_BegdhhI3V9B7dPbhjCBwOzQ
+ hash: v1.k794b7964.61d84aa429ea809c7329daa6a96e49ea0cc3f9b5f0fe8fded7822bf946c4b52e.9NG_sQ5iK-UCtJtG-FkpubLMfi3oRh22SqBPdaatBbk
scenes-app-experiments--experiment-with-ratio-metric--light:
- hash: v1.k794b7964.4d897668dc53961c46570a188a8f02492dfc40606017f6061a5a5a0009932890.N-ZnGJ24g7Ys7Lpnz8uXraVTFllUZga6NiVf4LliF2U
+ hash: v1.k794b7964.f6c8e0599290ef954d2e9fe6a2ce2ca07ec551dacd64c28f92ab301a8fbef7f1.RRFDWLVqvSkgpfxYm7PX8kH36RjG8AdQ2sXfSR5UpII
scenes-app-experiments--experiments--dark:
hash: v1.k794b7964.d359ae42a3424ffa55995455003617add8c164712aee0db6f85639d9745b938d.NUXv2bPuBdcPxfyQG3A-L0Y0SZ-GeOl3Yrj40ZCrzvo
scenes-app-experiments--experiments--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index acbc8d362b3e..7365404a3e6d 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -297,6 +297,7 @@ export const FEATURE_FLAGS = {
EXPERIMENTS_END_MODAL_CONCLUSION_FIRST: 'experiments-end-modal-conclusion-first', // owner: @ruby.c #team-experiments
EXPERIMENTS_EXCLUDED_VARIANTS: 'experiments-excluded-variants', // owner: @rodrigoi #team-experiments
EXPERIMENTS_LLM_PROMPTS: 'experiments-llm-prompts', // owner: @jurajmajerik #team-experiments
+ EXPERIMENTS_METRICS_RECALCULATION: 'experiments-metrics-recalculation', // owner: @rodrigoi #team-experiments
EXPERIMENTS_SHOW_SQL: 'experiments-show-sql', // owner: @jurajmajerik #team-experiments
EXPERIMENTS_SYNC_QUERIES: 'experiments-sync-queries', // owner: @andehen #team-experiments
EXPERIMENTS_TEMPLATES: 'experiments-templates', // owner: @rodrigoi #team-experiments
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 7908a182cb29..328d23dbef0e 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -783,6 +783,23 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
teamId,
context,
}),
+ // Single event for the whole recalc lifecycle — see docs/superpowers/specs/2026-06-04-experiment-metric-
+ // recalculation-events.md. status discriminates the moment ('triggered' / 'completed' / 'failed' —
+ // 'polled' is deliberately not emitted); the property bag carries the fields relevant to that moment.
+ reportExperimentMetricRecalculation: (
+ status: 'triggered' | 'completed' | 'failed',
+ properties: {
+ experiment_id: number
+ recalculation_id: string | null
+ trigger?: 'manual' | 'experiment_launch' | 'experiment_stop' | 'experiment_update'
+ is_existing?: boolean
+ total_metrics?: number
+ succeeded?: number
+ failed?: number
+ duration_ms?: number
+ poll_count?: number
+ }
+ ) => ({ status, properties }),
reportExperimentFeatureFlagModalOpened: () => ({}),
reportExperimentFeatureFlagSelected: (featureFlagKey: string) => ({ featureFlagKey }),
reportExperimentTimeseriesViewed: (experimentId: ExperimentIdType, metric: ExperimentMetric) => ({
@@ -1810,6 +1827,9 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
...context,
})
},
+ reportExperimentMetricRecalculation: ({ status, properties }) => {
+ posthog.capture('experiment metric recalculation', { status, ...properties })
+ },
reportExperimentFeatureFlagModalOpened: () => {
posthog.capture('experiment feature flag modal opened')
},
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx
index 0b0d8236470e..1da6820f61d7 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx
@@ -28,7 +28,7 @@ function useStaleDataCheck({
intervalSeconds,
onRefresh,
}: {
- lastRefresh: string
+ lastRefresh: string | null
enabled: boolean
intervalSeconds: number
onRefresh: () => void
@@ -65,7 +65,7 @@ function useStaleDataCheck({
}, [lastRefresh, enabled, intervalSeconds, onRefresh])
}
-export const ExperimentLastRefreshText = ({ lastRefresh }: { lastRefresh: string }): JSX.Element => {
+export const ExperimentLastRefreshText = ({ lastRefresh }: { lastRefresh: string | null }): JSX.Element => {
const colorClass = lastRefresh
? dayjs().diff(dayjs(lastRefresh), 'hours') > 12
? 'text-danger'
@@ -93,10 +93,12 @@ export const ExperimentReloadAction = ({
isRefreshing,
lastRefresh,
onClick,
+ progress,
}: {
isRefreshing: boolean
- lastRefresh: string
+ lastRefresh: string | null
onClick: () => void
+ progress?: { completed: number; total: number }
}): JSX.Element => {
const { autoRefresh } = useValues(experimentLogic)
const { setAutoRefresh, setPageVisibility, stopAutoRefreshInterval } = useActions(experimentLogic)
@@ -131,6 +133,9 @@ export const ExperimentReloadAction = ({
disabledReason: !autoRefresh.enabled ? 'Enable auto refresh to set the interval' : undefined,
}))
+ const loadingText =
+ progress && progress.total > 0 ? `Loading ${progress.completed} of ${progress.total}` : 'Loading…'
+
return (
<div className="flex flex-col">
<Label intent="menu">Last refreshed</Label>
@@ -190,7 +195,7 @@ export const ExperimentReloadAction = ({
},
}}
>
- {isRefreshing ? 'Loading…' : <ExperimentLastRefreshText lastRefresh={lastRefresh} />}
+ {isRefreshing ? loadingText : <ExperimentLastRefreshText lastRefresh={lastRefresh} />}
</LemonButton>
<LemonBadge
size="small"
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadActionContainer.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadActionContainer.tsx
new file mode 100644
index 000000000000..9317a609ba07
--- /dev/null
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadActionContainer.tsx
@@ -0,0 +1,85 @@
+import { useActions, useValues } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { Experiment } from '~/types'
+
+import { experimentLogic, previousRefreshAnalytics } from '../experimentLogic'
+import { experimentMetricsLogic } from '../experimentMetricsLogic'
+import { ExperimentReloadAction } from './ExperimentReloadAction'
+
+/**
+ * Wires the reload button to the right loading source: on the recalculation flow it reads
+ * experimentMetricsLogic (progress + isRecalculating, triggers a fresh recalculation on click);
+ * otherwise it mirrors the legacy primary/secondary loading rules from experimentLogic.
+ *
+ * Rendered only for non-draft experiments, so `experiment` is always real here.
+ */
+export function ExperimentReloadActionContainer({
+ experiment,
+ lastRefresh,
+}: {
+ experiment: Experiment
+ /** Legacy "last refreshed" timestamp from experimentLogic results, used only on the legacy path.
+ * The recalculation path derives its own from the completed run. */
+ lastRefresh: string
+}): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const recalculationFlow = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]
+
+ return recalculationFlow ? (
+ <RecalculationReloadAction experiment={experiment} />
+ ) : (
+ <LegacyReloadAction experiment={experiment} lastRefresh={lastRefresh} />
+ )
+}
+
+function RecalculationReloadAction({ experiment }: { experiment: Experiment }): JSX.Element {
+ const metricsLogic = experimentMetricsLogic({ experiment })
+ const { isRecalculating, recalculationProgress, lastRefresh } = useValues(metricsLogic)
+ const { triggerRecalculation } = useActions(metricsLogic)
+ const { autoRefresh, currentRefresh } = useValues(experimentLogic)
+ const { refreshExperimentResults, reportExperimentMetricsRefreshed } = useActions(experimentLogic)
+
+ return (
+ <ExperimentReloadAction
+ isRefreshing={isRecalculating}
+ lastRefresh={lastRefresh}
+ progress={recalculationProgress}
+ onClick={() => {
+ reportExperimentMetricsRefreshed(experiment, true, {
+ triggered_by: 'manual',
+ auto_refresh_enabled: autoRefresh.enabled,
+ auto_refresh_interval: autoRefresh.interval,
+ ...previousRefreshAnalytics(currentRefresh),
+ })
+ triggerRecalculation()
+ // Exposures still live in experimentLogic; keep refreshing them on manual reload.
+ refreshExperimentResults(true, 'manual')
+ }}
+ />
+ )
+}
+
+function LegacyReloadAction({ experiment, lastRefresh }: { experiment: Experiment; lastRefresh: string }): JSX.Element {
+ const { primaryMetricsResultsLoading, secondaryMetricsResultsLoading, autoRefresh, currentRefresh } =
+ useValues(experimentLogic)
+ const { refreshExperimentResults, reportExperimentMetricsRefreshed } = useActions(experimentLogic)
+
+ return (
+ <ExperimentReloadAction
+ isRefreshing={primaryMetricsResultsLoading || secondaryMetricsResultsLoading}
+ lastRefresh={lastRefresh}
+ onClick={() => {
+ reportExperimentMetricsRefreshed(experiment, true, {
+ triggered_by: 'manual',
+ auto_refresh_enabled: autoRefresh.enabled,
+ auto_refresh_interval: autoRefresh.interval,
+ ...previousRefreshAnalytics(currentRefresh),
+ })
+ refreshExperimentResults(true, 'manual')
+ }}
+ />
+ )
+}
diff --git a/frontend/src/scenes/experiments/ExperimentView/Info.tsx b/frontend/src/scenes/experiments/ExperimentView/Info.tsx
index 3697bbc5cf7a..ef1a799f228d 100644
--- a/frontend/src/scenes/experiments/ExperimentView/Info.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/Info.tsx
@@ -15,11 +15,11 @@ import { urls } from 'scenes/urls'
import { ExperimentStatsMethod, ExperimentStatus } from '~/types'
import { CONCLUSION_DISPLAY_CONFIG } from '../constants'
-import { experimentLogic, previousRefreshAnalytics } from '../experimentLogic'
+import { experimentLogic } from '../experimentLogic'
import { getExperimentStatus, isExperimentPaused } from '../experimentsLogic'
import { modalsLogic } from '../modalsLogic'
import { ExperimentDuration } from './ExperimentDuration'
-import { ExperimentReloadAction } from './ExperimentReloadAction'
+import { ExperimentReloadActionContainer } from './ExperimentReloadActionContainer'
import { RunningTime } from './RunningTime'
import { StatusTag } from './StatusTag'
@@ -28,16 +28,12 @@ export function Info(): JSX.Element {
experiment,
primaryMetricsResults,
secondaryMetricsResults,
- primaryMetricsResultsLoading,
- secondaryMetricsResultsLoading,
statsMethod,
isExperimentDraft,
isSingleVariantShipped,
shippedVariantKey,
- autoRefresh,
- currentRefresh,
} = useValues(experimentLogic)
- const { updateExperiment, refreshExperimentResults, reportExperimentMetricsRefreshed } = useActions(experimentLogic)
+ const { updateExperiment } = useActions(experimentLogic)
const { openEditConclusionModal, openDescriptionModal, closeDescriptionModal, openRunningTimeConfigModal } =
useActions(modalsLogic)
const { isDescriptionModalOpen } = useValues(modalsLogic)
@@ -204,20 +200,7 @@ export function Info(): JSX.Element {
isExperimentDraft={isExperimentDraft}
/>
{status !== ExperimentStatus.Draft && (
- <ExperimentReloadAction
- isRefreshing={primaryMetricsResultsLoading || secondaryMetricsResultsLoading}
- lastRefresh={lastRefresh}
- onClick={() => {
- // Track manual refresh click
- reportExperimentMetricsRefreshed(experiment, true, {
- triggered_by: 'manual',
- auto_refresh_enabled: autoRefresh.enabled,
- auto_refresh_interval: autoRefresh.interval,
- ...previousRefreshAnalytics(currentRefresh),
- })
- refreshExperimentResults(true, 'manual')
- }}
- />
+ <ExperimentReloadActionContainer experiment={experiment} lastRefresh={lastRefresh} />
)}
<div className="flex flex-col">
<Label intent="menu">Created by</Label>
diff --git a/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx b/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx
index d52f65e090d4..bedbc9b29bb2 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx
@@ -4,24 +4,49 @@ import { useEffect } from 'react'
import { IconClock } from '@posthog/icons'
import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { Experiment } from '~/types'
+
import { experimentLogic } from '../experimentLogic'
+import { experimentMetricsLogic } from '../experimentMetricsLogic'
+import { experimentResultsNotificationLogic } from '../experimentResultsNotificationLogic'
+import { isSavedExperiment } from '../utils'
+/**
+ * "Results are taking a while" banner. On the recalculation flow it reads the standalone
+ * experimentResultsNotificationLogic (driven by isRecalculating); the legacy flow keeps reading the
+ * equivalent state on experimentLogic.
+ */
export function ResultsNotificationBanner(): JSX.Element | null {
- const {
- showNotificationOffer,
- notifyWhenResultsReady,
- primaryMetricsResultsLoading,
- secondaryMetricsResultsLoading,
- } = useValues(experimentLogic)
- const { subscribeToResultsNotification, dismissNotificationOffer } = useActions(experimentLogic)
+ const { experiment } = useValues(experimentLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const recalculationFlow = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]
- const isLoading = primaryMetricsResultsLoading || secondaryMetricsResultsLoading
+ if (recalculationFlow && isSavedExperiment(experiment)) {
+ return <RecalculationNotificationBanner experiment={experiment} />
+ }
+ return <LegacyNotificationBanner />
+}
+function NotificationBannerView({
+ showNotificationOffer,
+ notifyWhenResultsReady,
+ isLoading,
+ onSubscribe,
+ onDismiss,
+}: {
+ showNotificationOffer: boolean
+ notifyWhenResultsReady: boolean
+ isLoading: boolean
+ onSubscribe: () => void
+ onDismiss: () => void
+}): JSX.Element | null {
useEffect(() => {
if (!notifyWhenResultsReady || !isLoading) {
return
}
-
const handler = (e: BeforeUnloadEvent): void => {
e.preventDefault()
}
@@ -41,14 +66,14 @@ export function ResultsNotificationBanner(): JSX.Element | null {
type="info"
className="mb-4"
icon={<IconClock />}
- onClose={notifyWhenResultsReady ? undefined : dismissNotificationOffer}
+ onClose={notifyWhenResultsReady ? undefined : onDismiss}
>
{notifyWhenResultsReady ? (
"We'll notify you when results are ready. Keep this tab open."
) : (
<div className="flex items-center gap-2">
<span>Results are taking a while.</span>
- <LemonButton type="secondary" size="xsmall" onClick={subscribeToResultsNotification}>
+ <LemonButton type="secondary" size="xsmall" onClick={onSubscribe}>
Notify me when ready
</LemonButton>
</div>
@@ -56,3 +81,40 @@ export function ResultsNotificationBanner(): JSX.Element | null {
</LemonBanner>
)
}
+
+function RecalculationNotificationBanner({ experiment }: { experiment: Experiment }): JSX.Element | null {
+ const notificationLogic = experimentResultsNotificationLogic({ experiment })
+ const { showNotificationOffer, notifyWhenResultsReady } = useValues(notificationLogic)
+ const { subscribeToResultsNotification, dismissNotificationOffer } = useActions(notificationLogic)
+ const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))
+
+ return (
+ <NotificationBannerView
+ showNotificationOffer={showNotificationOffer}
+ notifyWhenResultsReady={notifyWhenResultsReady}
+ isLoading={isRecalculating}
+ onSubscribe={subscribeToResultsNotification}
+ onDismiss={dismissNotificationOffer}
+ />
+ )
+}
+
+function LegacyNotificationBanner(): JSX.Element | null {
+ const {
+ showNotificationOffer,
+ notifyWhenResultsReady,
+ primaryMetricsResultsLoading,
+ secondaryMetricsResultsLoading,
+ } = useValues(experimentLogic)
+ const { subscribeToResultsNotification, dismissNotificationOffer } = useActions(experimentLogic)
+
+ return (
+ <NotificationBannerView
+ showNotificationOffer={showNotificationOffer}
+ notifyWhenResultsReady={notifyWhenResultsReady}
+ isLoading={primaryMetricsResultsLoading || secondaryMetricsResultsLoading}
+ onSubscribe={subscribeToResultsNotification}
+ onDismiss={dismissNotificationOffer}
+ />
+ )
+}
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
index ce7b3aa04340..dedead819c5f 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
@@ -1,13 +1,15 @@
import './MetricRowGroup.scss'
-import { useActions } from 'kea'
+import { useActions, useValues } from 'kea'
import React, { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { IconTrending } from '@posthog/icons'
+import { FEATURE_FLAGS } from 'lib/constants'
import { IconTrendingDown } from 'lib/lemon-ui/icons'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'
import { BreakdownTag } from 'scenes/insights/filters/BreakdownFilter/BreakdownTag'
@@ -21,6 +23,7 @@ import {
} from '~/queries/schema/schema-general'
import { NodeKind } from '~/queries/schema/schema-general'
import { experimentLogic } from '~/scenes/experiments/experimentLogic'
+import { experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'
import { isLaunched } from '~/scenes/experiments/experimentsLogic'
import { useColumnWidthSync } from '~/scenes/experiments/MetricsView/hooks/useColumnWidthSync'
import { ChartEmptyState } from '~/scenes/experiments/MetricsView/shared/ChartEmptyState'
@@ -112,6 +115,7 @@ interface CollapsibleBreakdownSectionProps {
isLastMetric: boolean
isLoading?: boolean
exposuresLoading?: boolean
+ isRecalculating?: boolean
colors: ReturnType<typeof useChartColors>
scale: ReturnType<typeof useAxisScale>
onRemoveBreakdown: (index: number) => void
@@ -130,6 +134,7 @@ function CollapsibleBreakdownSection({
isAlternatingRow,
isLoading,
exposuresLoading,
+ isRecalculating,
colors,
scale,
onRemoveBreakdown,
@@ -143,6 +148,16 @@ function CollapsibleBreakdownSection({
const mainTableRef = useRef<HTMLTableRowElement>(null)
const nestedTableRef = useRef<HTMLTableElement>(null)
+ /**
+ * Collapse the section when a recalculation starts. The results are stale and the panel is
+ * disabled, so close it rather than have it snap back open when fresh results land
+ */
+ useEffect(() => {
+ if (isRecalculating) {
+ setIsExpanded(false)
+ }
+ }, [isRecalculating])
+
const totalRows = 1 + (breakdownResults[0]?.variants?.length || 0)
const totalRowsHeightStyle = getScaledHeightStyle(totalRows)
@@ -176,6 +191,7 @@ function CollapsibleBreakdownSection({
<LemonCollapse
multiple={false}
embedded
+ activeKey={isExpanded ? 'breakdowns' : undefined}
className={`breakdown-collapse breakdown-collapse--${isAlternatingRow ? 'alt-row' : 'normal-row'}`}
panels={[
{
@@ -193,269 +209,282 @@ function CollapsibleBreakdownSection({
))}
</div>
),
- content: (
- <div className="p-0 -m-4">
- <table ref={nestedTableRef} className="w-full">
- <tbody>
- {breakdownResults.map((breakdownResult) => {
- const baselineResult = breakdownResult.baseline
- const variantResults = breakdownResult.variants || []
-
- if (variantResults.length === 0) {
- return (
- <tr
- key={breakdownResult.breakdown_value}
- className="hover:bg-bg-hover"
- style={FIXED_HEIGHT_STYLE}
- >
- <td
- className={`w-1/5 border-r p-3 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
- >
- {formatBreakdownLabel(
- breakdownResult.breakdown_value,
- metric.breakdownFilter,
- [],
- undefined,
- 0,
- undefined
- )}
- </td>
- <td
- colSpan={6}
- className={`p-3 text-center ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
- style={FIXED_HEIGHT_STYLE}
- >
- {isLoading || exposuresLoading ? (
- <ChartLoadingState height={CELL_HEIGHT} />
- ) : (
- <ChartEmptyState
- height={CELL_HEIGHT}
- experimentStarted={isLaunched(experiment)}
- metric={metric}
- query={query}
- onRetry={onRetry}
- />
- )}
- </td>
- </tr>
- )
- }
-
- return (
- <React.Fragment key={breakdownResult.breakdown_value}>
- {/* Baseline row */}
- <tr className="hover:bg-bg-hover" style={FIXED_HEIGHT_STYLE}>
- <td
- className={`w-1/5 border-r p-3 align-top border-b ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} text-xs`}
- rowSpan={totalRows}
- style={totalRowsHeightStyle}
- >
- {formatBreakdownLabel(
- breakdownResult.breakdown_value,
- metric.breakdownFilter,
- [],
- undefined,
- 0,
- undefined
- )}
- </td>
-
- <td
- className={`w-20 pt-1 pl-3 pr-3 pb-1 whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
- style={FIXED_HEIGHT_STYLE}
- >
- <VariantTag variantKey={baselineResult.key} />
- </td>
-
- <td
- className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ // Render no content (non-expandable disabled header) when recalculating (stale
+ // results) or when there are no breakdown results yet (freshly added, pending) —
+ // expanding onto an empty table looks broken.
+ content:
+ isRecalculating || breakdownResults.length === 0 ? null : (
+ <div className="p-0 -m-4">
+ <table ref={nestedTableRef} className="w-full">
+ <tbody>
+ {breakdownResults.map((breakdownResult) => {
+ const baselineResult = breakdownResult.baseline
+ const variantResults = breakdownResult.variants || []
+
+ if (variantResults.length === 0) {
+ return (
+ <tr
+ key={breakdownResult.breakdown_value}
+ className="hover:bg-bg-hover"
style={FIXED_HEIGHT_STYLE}
>
- <div className="metric-cell">
- <div>
- {formatMetricValue(baselineResult, metric)}
- </div>
- {ratioMetricLabel(baselineResult, metric)}
- </div>
- </td>
-
- <td
- className={`w-20 pt-1 pl-3 pr-3 pb-1 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
- style={FIXED_HEIGHT_STYLE}
- >
- <div />
- </td>
+ <td
+ className={`w-1/5 border-r p-3 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ >
+ {formatBreakdownLabel(
+ breakdownResult.breakdown_value,
+ metric.breakdownFilter,
+ [],
+ undefined,
+ 0,
+ undefined
+ )}
+ </td>
+ <td
+ colSpan={6}
+ className={`p-3 text-center ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ {isLoading || exposuresLoading ? (
+ <ChartLoadingState height={CELL_HEIGHT} />
+ ) : (
+ <ChartEmptyState
+ height={CELL_HEIGHT}
+ experimentStarted={isLaunched(experiment)}
+ metric={metric}
+ query={query}
+ onRetry={onRetry}
+ />
+ )}
+ </td>
+ </tr>
+ )
+ }
- <td
- className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
- style={FIXED_HEIGHT_STYLE}
- >
- <div />
- </td>
-
- {/* Empty Details column for alignment */}
- <td
- className={`w-20 pt-3 align-top relative overflow-hidden border-b ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
- rowSpan={totalRows}
- style={totalRowsHeightStyle}
- />
-
- <td
- className={`p-0 align-top text-center relative overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ return (
+ <React.Fragment key={breakdownResult.breakdown_value}>
+ {/* Baseline row */}
+ <tr
+ className="hover:bg-bg-hover"
style={FIXED_HEIGHT_STYLE}
>
- {axisRange && axisRange > 0 ? (
- <div className="relative h-full">
- <svg
- viewBox={`0 0 ${VIEW_BOX_WIDTH} ${CHART_CELL_VIEW_BOX_HEIGHT}`}
- preserveAspectRatio="none"
- className="h-full w-full"
- >
- <GridLines
- tickValues={getNiceTickValues(
- axisRange
- )}
- scale={scale}
- height={CHART_CELL_VIEW_BOX_HEIGHT}
- viewBoxWidth={VIEW_BOX_WIDTH}
- zeroLineColor={colors.ZERO_LINE}
- gridLineColor={colors.BOUNDARY_LINES}
- zeroLineWidth={1.25}
- gridLineWidth={0.75}
- opacity={GRID_LINES_OPACITY}
- />
- </svg>
+ <td
+ className={`w-1/5 border-r p-3 align-top border-b ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} text-xs`}
+ rowSpan={totalRows}
+ style={totalRowsHeightStyle}
+ >
+ {formatBreakdownLabel(
+ breakdownResult.breakdown_value,
+ metric.breakdownFilter,
+ [],
+ undefined,
+ 0,
+ undefined
+ )}
+ </td>
+
+ <td
+ className={`w-20 pt-1 pl-3 pr-3 pb-1 whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ <VariantTag variantKey={baselineResult.key} />
+ </td>
+
+ <td
+ className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ <div className="metric-cell">
+ <div>
+ {formatMetricValue(baselineResult, metric)}
+ </div>
+ {ratioMetricLabel(baselineResult, metric)}
</div>
- ) : (
- <div className="flex items-center justify-center h-full text-muted text-xs">
- —
- </div>
- )}
- </td>
- </tr>
-
- {/* Variant rows */}
- {variantResults.map(
- (variant: ExperimentVariantResult, index: number) => {
- const isLastRow = index === variantResults.length - 1
- const significant = isSignificant(variant)
- const deltaPositive = isDeltaPositive(variant)
- const winning = isWinning(variant, metric.goal)
- const deltaText = formatDeltaPercent(variant)
-
- return (
- <tr
- key={`${metric.uuid}-${variant.key}`}
- className="hover:bg-bg-hover"
- style={FIXED_HEIGHT_STYLE}
- onMouseEnter={(e) =>
- handleTooltipMouseEnter(e, variant)
- }
- onMouseLeave={handleTooltipMouseLeave}
- onMouseMove={(e) =>
- handleTooltipMouseMove(e, variant)
- }
- >
- <td
- className={`w-20 pt-1 pl-3 pr-3 pb-1 whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
+ </td>
+
+ <td
+ className={`w-20 pt-1 pl-3 pr-3 pb-1 ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ <div />
+ </td>
+
+ <td
+ className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ <div />
+ </td>
+
+ {/* Empty Details column for alignment */}
+ <td
+ className={`w-20 pt-3 align-top relative overflow-hidden border-b ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ rowSpan={totalRows}
+ style={totalRowsHeightStyle}
+ />
+
+ <td
+ className={`p-0 align-top text-center relative overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ {axisRange && axisRange > 0 ? (
+ <div className="relative h-full">
+ <svg
+ viewBox={`0 0 ${VIEW_BOX_WIDTH} ${CHART_CELL_VIEW_BOX_HEIGHT}`}
+ preserveAspectRatio="none"
+ className="h-full w-full"
+ >
+ <GridLines
+ tickValues={getNiceTickValues(
+ axisRange
+ )}
+ scale={scale}
+ height={CHART_CELL_VIEW_BOX_HEIGHT}
+ viewBoxWidth={VIEW_BOX_WIDTH}
+ zeroLineColor={colors.ZERO_LINE}
+ gridLineColor={
+ colors.BOUNDARY_LINES
+ }
+ zeroLineWidth={1.25}
+ gridLineWidth={0.75}
+ opacity={GRID_LINES_OPACITY}
+ />
+ </svg>
+ </div>
+ ) : (
+ <div className="flex items-center justify-center h-full text-muted text-xs">
+ —
+ </div>
+ )}
+ </td>
+ </tr>
+
+ {/* Variant rows */}
+ {variantResults.map(
+ (variant: ExperimentVariantResult, index: number) => {
+ const isLastRow =
+ index === variantResults.length - 1
+ const significant = isSignificant(variant)
+ const deltaPositive = isDeltaPositive(variant)
+ const winning = isWinning(variant, metric.goal)
+ const deltaText = formatDeltaPercent(variant)
+
+ return (
+ <tr
+ key={`${metric.uuid}-${variant.key}`}
+ className="hover:bg-bg-hover"
style={FIXED_HEIGHT_STYLE}
+ onMouseEnter={(e) =>
+ handleTooltipMouseEnter(e, variant)
+ }
+ onMouseLeave={handleTooltipMouseLeave}
+ onMouseMove={(e) =>
+ handleTooltipMouseMove(e, variant)
+ }
>
- <VariantTag variantKey={variant.key} />
- </td>
+ <td
+ className={`w-20 pt-1 pl-3 pr-3 pb-1 whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ <VariantTag variantKey={variant.key} />
+ </td>
- <td
- className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
- style={FIXED_HEIGHT_STYLE}
- >
- <div className="metric-cell">
- <div>
- {formatMetricValue(variant, metric)}
+ <td
+ className={`w-24 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ <div className="metric-cell">
+ <div>
+ {formatMetricValue(
+ variant,
+ metric
+ )}
+ </div>
+ {ratioMetricLabel(variant, metric)}
</div>
- {ratioMetricLabel(variant, metric)}
- </div>
- </td>
+ </td>
- <td
- className={`w-20 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
- style={FIXED_HEIGHT_STYLE}
- >
- <div className="flex items-center gap-1">
+ <td
+ className={`w-20 pt-1 pl-3 pr-3 pb-1 text-left whitespace-nowrap overflow-hidden ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'} ${isLastRow ? 'border-b' : ''}`}
+ style={FIXED_HEIGHT_STYLE}
+ >
+ <div className="flex items-center gap-1">
+ <span
+ className={`metric-cell font-bold ${significant ? (winning ? 'text-success' : 'text-danger') : ''}`}
+ >
+ {deltaText}
+ </span>
+ {significant &&
+ deltaPositive !== undefined && (
+ <span
+ className={`flex-shrink-0 ${winning ? 'text-success' : 'text-danger'}`}
+ >
+ {deltaPositive ? (
+ <IconTrending
+ className="w-5 h-5"
+ style={{
+ strokeWidth: 2.5,
+ }}
+ />
+ ) : (
+ <IconTrendingDown
+ className="w-5 h-5"
+ style={{
+ strokeWidth: 2.5,
+ }}
+ />
+ )}
+ </span>
+ )}
+ </div>
+ </td>
+
+ <td
+ className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center whitespace-nowrap overflow-hidden ${!significant ? (isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light') : ''} ${isLastRow ? 'border-b' : ''}`}
+ style={{
+ ...FIXED_HEIGHT_STYLE,
+ backgroundColor: significant
+ ? winning
+ ? `${colors.BAR_POSITIVE}30`
+ : `${colors.BAR_NEGATIVE}30`
+ : undefined,
+ }}
+ >
<span
- className={`metric-cell font-bold ${significant ? (winning ? 'text-success' : 'text-danger') : ''}`}
+ className={`metric-cell ${significant ? (winning ? 'text-success font-bold' : 'text-danger font-bold') : ''}`}
>
- {deltaText}
+ {isBayesianResult(variant)
+ ? formatChanceToWinForGoal(
+ variant,
+ metric.goal
+ )
+ : formatPValue(variant.p_value)}
</span>
- {significant &&
- deltaPositive !== undefined && (
- <span
- className={`flex-shrink-0 ${winning ? 'text-success' : 'text-danger'}`}
- >
- {deltaPositive ? (
- <IconTrending
- className="w-5 h-5"
- style={{
- strokeWidth: 2.5,
- }}
- />
- ) : (
- <IconTrendingDown
- className="w-5 h-5"
- style={{
- strokeWidth: 2.5,
- }}
- />
- )}
- </span>
- )}
- </div>
- </td>
-
- <td
- className={`w-20 pt-1 pl-3 pr-3 pb-1 text-center whitespace-nowrap overflow-hidden ${!significant ? (isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light') : ''} ${isLastRow ? 'border-b' : ''}`}
- style={{
- ...FIXED_HEIGHT_STYLE,
- backgroundColor: significant
- ? winning
- ? `${colors.BAR_POSITIVE}30`
- : `${colors.BAR_NEGATIVE}30`
- : undefined,
- }}
- >
- <span
- className={`metric-cell ${significant ? (winning ? 'text-success font-bold' : 'text-danger font-bold') : ''}`}
- >
- {isBayesianResult(variant)
- ? formatChanceToWinForGoal(
- variant,
- metric.goal
- )
- : formatPValue(variant.p_value)}
- </span>
- </td>
-
- <ChartCell
- variantResult={variant}
- metric={metric}
- axisRange={axisRange}
- metricUuid={metric.uuid}
- isAlternatingRow={isAlternatingRow}
- isLastRow={isLastRow}
- isSecondary={false}
- gradientSuffix={String(
- breakdownResult.breakdown_value
- )}
- />
- </tr>
- )
- }
- )}
- </React.Fragment>
- )
- })}
- </tbody>
- </table>
- </div>
- ),
+ </td>
+
+ <ChartCell
+ variantResult={variant}
+ metric={metric}
+ axisRange={axisRange}
+ metricUuid={metric.uuid}
+ isAlternatingRow={isAlternatingRow}
+ isLastRow={isLastRow}
+ isSecondary={false}
+ gradientSuffix={String(
+ breakdownResult.breakdown_value
+ )}
+ />
+ </tr>
+ )
+ }
+ )}
+ </React.Fragment>
+ )
+ })}
+ </tbody>
+ </table>
+ </div>
+ ),
},
]}
onChange={(activeKey) => setIsExpanded(activeKey === 'breakdowns')}
@@ -566,10 +595,20 @@ export function MetricRowGroup({
const scale = useAxisScale(axisRange, VIEW_BOX_WIDTH, SVG_EDGE_MARGIN)
- const { reportExperimentTimeseriesViewed, retryPrimaryMetric, retrySecondaryMetric } = useActions(experimentLogic)
+ const { reportExperimentTimeseriesViewed, retryPrimaryMetric, retrySecondaryMetric, refreshExperimentResults } =
+ useActions(experimentLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))
+ const { triggerRecalculation } = useActions(experimentMetricsLogic({ experiment }))
- // Build retry callback for this metric
+ // 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()
+ refreshExperimentResults(true, 'manual')
+ return
+ }
if (isSecondary) {
retrySecondaryMetric(metricIndex)
} else {
@@ -716,7 +755,7 @@ export function MetricRowGroup({
}`}
style={noResultStateStyle}
>
- {isLoading || exposuresLoading ? (
+ {!hasError && (isLoading || exposuresLoading) ? (
<ChartLoadingState height={noResultHeight} />
) : (
<ChartEmptyState
@@ -1019,10 +1058,10 @@ export function MetricRowGroup({
)
})}
- {/* Collapsible Breakdown Section */}
- {result.breakdown_results && result.breakdown_results.length > 0 && (
+ {/* Collapsible Breakdown Section. */}
+ {(metric.breakdownFilter?.breakdowns?.length ?? 0) > 0 && (
<CollapsibleBreakdownSection
- breakdownResults={result.breakdown_results}
+ breakdownResults={result.breakdown_results ?? []}
metric={metric}
experiment={experiment}
axisRange={axisRange}
@@ -1030,6 +1069,7 @@ export function MetricRowGroup({
isLastMetric={isLastMetric}
isLoading={isLoading}
exposuresLoading={exposuresLoading}
+ isRecalculating={isRecalculating}
colors={colors}
scale={scale}
onRemoveBreakdown={onRemoveBreakdown}
diff --git a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx
index 35962462d676..8f3e14fef22d 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx
@@ -3,47 +3,75 @@ import { useActions, useValues } from 'kea'
import { IconInfo, IconList } from '@posthog/icons'
import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
import { IconAreaChart } from 'lib/lemon-ui/icons'
-import { AddMetricButton } from 'scenes/experiments/Metrics/AddMetricButton'
-import { METRIC_CONTEXTS } from 'scenes/experiments/Metrics/experimentMetricModalLogic'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import type { CachedNewExperimentQueryResponse, ExperimentMetric } from '~/queries/schema/schema-general'
+import type { ExperimentMetric } from '~/queries/schema/schema-general'
+import { experimentLogic } from '~/scenes/experiments/experimentLogic'
+import { experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'
+import { AddMetricButton } from '~/scenes/experiments/Metrics/AddMetricButton'
+import { METRIC_CONTEXTS } from '~/scenes/experiments/Metrics/experimentMetricModalLogic'
+import { MetricsReorderModal } from '~/scenes/experiments/MetricsView/MetricsReorderModal'
+import { modalsLogic } from '~/scenes/experiments/modalsLogic'
+import { isSavedExperiment, metricResults } from '~/scenes/experiments/utils'
+import { Experiment } from '~/types'
-import { experimentLogic } from '../../experimentLogic'
-import { modalsLogic } from '../../modalsLogic'
-import { MetricsReorderModal } from '../MetricsReorderModal'
import { HowToReadTooltip } from './HowToReadTooltip'
import { MetricsTable } from './MetricsTable'
import { ResultDetails } from './ResultDetails'
export function Metrics({ isSecondary }: { isSecondary?: boolean }): JSX.Element | null {
+ const { experiment } = useValues(experimentLogic)
+
+ const variants = experiment?.feature_flag?.filters?.multivariate?.variants
+ // Guard here so the child can take a non-null, real experiment and mount keyed child logics safely.
+ if (!variants || !isSavedExperiment(experiment)) {
+ return null
+ }
+
+ return <MetricsContent experiment={experiment} isSecondary={isSecondary} />
+}
+
+function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; isSecondary?: boolean }): JSX.Element {
const {
- experiment,
getInsightType,
orderedPrimaryMetricsWithResults,
orderedSecondaryMetricsWithResults,
hasMinimumExposureForResults,
} = useValues(experimentLogic)
+ const {
+ primaryMetricsResults,
+ primaryMetricsResultsErrors,
+ secondaryMetricsResults,
+ secondaryMetricsResultsErrors,
+ } = useValues(experimentMetricsLogic({ experiment }))
+ const { featureFlags } = useValues(featureFlagLogic)
+ const recalculationFlow = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]
const { openPrimaryMetricsReorderModal, openSecondaryMetricsReorderModal } = useActions(modalsLogic)
- const variants = experiment?.feature_flag?.filters?.multivariate?.variants
- if (!variants) {
- return null
- }
+ const type = isSecondary ? 'secondary' : 'primary'
- const metricsWithResults = isSecondary ? orderedSecondaryMetricsWithResults : orderedPrimaryMetricsWithResults
+ const metricsWithResults = recalculationFlow
+ ? metricResults(experiment)(
+ isSecondary ? secondaryMetricsResults : primaryMetricsResults,
+ isSecondary ? secondaryMetricsResultsErrors : primaryMetricsResultsErrors,
+ type
+ )
+ : isSecondary
+ ? orderedSecondaryMetricsWithResults
+ : orderedPrimaryMetricsWithResults
- const metrics = metricsWithResults.map(({ metric }: { metric: ExperimentMetric }) => metric)
- const results = metricsWithResults.map(({ result }: { result: CachedNewExperimentQueryResponse }) => result)
- const errors = metricsWithResults.map(({ error }: { error: any }) => error)
- const metricIndexes = metricsWithResults.map(({ metricIndex }: { metricIndex: number }) => metricIndex)
+ const metrics = metricsWithResults.map(({ metric }) => metric)
+ const results = metricsWithResults.map(({ result }) => result)
+ const errors = metricsWithResults.map(({ error }) => error)
+ const metricIndexes = metricsWithResults.map(({ metricIndex }) => metricIndex)
const showResultDetails = metrics.length === 1 && results[0] && hasMinimumExposureForResults && !isSecondary
const hasSomeResults =
- results?.some(
- (result: CachedNewExperimentQueryResponse) => result?.variant_results && result.variant_results.length > 0
- ) && hasMinimumExposureForResults
+ results?.some((result) => result?.variant_results && result.variant_results.length > 0) &&
+ hasMinimumExposureForResults
return (
<div className="mb-4 -mt-2" data-attr="experiment-creation-goal-metric">
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
index ce1ae05f2a83..08cd2b30e814 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx
@@ -11,6 +11,7 @@ import {
import { ExperimentStatsMethod, InsightType } from '~/types'
import { experimentLogic } from '../../experimentLogic'
+import { experimentMetricsLogic } from '../../experimentMetricsLogic'
import { isLaunched } from '../../experimentsLogic'
import { resolveSequentialEnabled } from '../../ExperimentView/sequential'
import { type ExperimentVariantResult, getVariantInterval } from '../shared/utils'
@@ -38,6 +39,7 @@ export function MetricsTable({
showDetailsModal = true,
}: MetricsTableProps): JSX.Element {
const { experiment, exposuresLoading } = useValues(experimentLogic)
+ const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))
const { experimentsConfig } = useValues(experimentsConfigLogic)
const teamDefaultSequentialEnabled = experimentsConfig?.default_sequential_testing_enabled ?? false
const sequentialTestingEnabled = resolveSequentialEnabled(
@@ -109,6 +111,7 @@ export function MetricsTable({
axisRange={axisRange}
statsMethod={experiment.stats_config?.method || ExperimentStatsMethod.Bayesian}
sequentialTestingEnabled={sequentialTestingEnabled}
+ loading={isRecalculating}
/>
<tbody>
{metrics.map((metric, index) => {
diff --git a/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsx b/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsx
index 05e9ee9ba237..2d1e89242962 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsx
@@ -3,6 +3,8 @@ import { useEffect, useMemo, useState } from 'react'
import { IconInfo } from '@posthog/icons'
import { Tooltip } from '@posthog/lemon-ui'
+import { LemonTableLoader } from 'lib/lemon-ui/LemonTable/LemonTableLoader'
+
import { ExperimentStatsMethod } from '~/types'
import { useSvgResizeObserver } from '../hooks/useSvgResizeObserver'
@@ -15,9 +17,15 @@ interface TableHeaderProps {
axisRange?: number
statsMethod?: ExperimentStatsMethod
sequentialTestingEnabled?: boolean
+ loading?: boolean
}
-export function TableHeader({ axisRange, statsMethod, sequentialTestingEnabled }: TableHeaderProps): JSX.Element {
+export function TableHeader({
+ axisRange,
+ statsMethod,
+ sequentialTestingEnabled,
+ loading = false,
+}: TableHeaderProps): JSX.Element {
const [svgWidth, setSvgWidth] = useState<number | undefined>(undefined)
// Set up tick values and scaling for the header
@@ -107,6 +115,13 @@ export function TableHeader({ axisRange, statsMethod, sequentialTestingEnabled }
)}
</th>
</tr>
+ {/* Thin loader line spanning the full table width, pinned to the header's bottom edge.
+ Mirrors LemonTable's loader row: a zero-height positioning host for the absolute line. */}
+ <tr>
+ <th colSpan={7} className="relative h-0 overflow-visible !border-none !p-0 leading-none">
+ <LemonTableLoader loading={loading} tag="div" placement="bottom" />
+ </th>
+ </tr>
</thead>
)
}
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index a354a6042a77..6a4fedaf4b1d 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -6,6 +6,7 @@ import { router } from 'kea-router'
import api from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
+import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
@@ -78,6 +79,7 @@ import {
MetricInsightId,
} from './constants'
import type { experimentLogicType } from './experimentLogicType'
+import { experimentMetricsLogic } from './experimentMetricsLogic'
import { experimentSceneLogic } from './experimentSceneLogic'
import {
experimentsLogic,
@@ -1457,8 +1459,8 @@ export const experimentLogic = kea<experimentLogicType>([
const duration = experiment?.start_date ? dayjs().diff(experiment.start_date, 'second') : null
experiment && actions.reportExperimentViewed(experiment, duration)
- // Load metrics for launched experiments (sets up auto-refresh once the load completes).
- // Shows cached results immediately, then force-refreshes once if the experiment is warming up.
+ // Load metrics for launched experiments (will set up auto-refresh after load completes).
+ // refreshExperimentResults branches on the recalculation feature flag internally.
if (experiment && isLaunched(experiment)) {
actions.refreshExperimentResults(false, payload?.triggeredBy ?? 'manual', true)
}
@@ -1598,11 +1600,26 @@ export const experimentLogic = kea<experimentLogicType>([
let caughtError = false
try {
- await Promise.all([
- asyncActions.loadPrimaryMetricsResults(forceRefresh, refreshId),
- asyncActions.loadSecondaryMetricsResults(forceRefresh, refreshId),
- asyncActions.loadExposures(forceRefresh),
- ])
+ const recalculationFlow = values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]
+ if (recalculationFlow) {
+ // A config change (date / metric / exposure criteria / settings) invalidates the
+ // cached results, so kick off a fresh recalculation. Page loads, manual reloads and
+ // auto-refresh are handled elsewhere (afterMount / the reload button), so don't
+ // re-trigger here for those. Fire BEFORE loading exposures so an exposures failure
+ // can't skip the metric recalculation — the two are independent.
+ if (triggeredBy === 'config_change' && values.experiment) {
+ experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation()
+ }
+ // Metric results come from experimentMetricsLogic (mounted by the metrics view);
+ // here we only refresh exposures, which still live in experimentLogic.
+ await asyncActions.loadExposures(forceRefresh)
+ } else {
+ await Promise.all([
+ asyncActions.loadPrimaryMetricsResults(forceRefresh, refreshId),
+ asyncActions.loadSecondaryMetricsResults(forceRefresh, refreshId),
+ asyncActions.loadExposures(forceRefresh),
+ ])
+ }
} catch (error) {
caughtError = true
throw error
@@ -2392,7 +2409,11 @@ export const experimentLogic = kea<experimentLogicType>([
actions.updateExperiment(updatePayload)
- if (isPrimary) {
+ // Adding a breakdown changes how the metric is computed, so re-run results — recalculation
+ // flow triggers a fresh recalc via config_change; legacy flow reloads per-metric results.
+ if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
+ actions.refreshExperimentResults(true, 'config_change')
+ } else if (isPrimary) {
actions.loadPrimaryMetricsResults(true)
} else {
actions.loadSecondaryMetricsResults(true)
@@ -2423,7 +2444,12 @@ export const experimentLogic = kea<experimentLogicType>([
actions.updateExperiment(updatePayload)
- if (isPrimary) {
+ // Removing a breakdown changes how the metric is computed, so re-run results. On the
+ // recalculation flow this routes through refreshExperimentResults('config_change') (which
+ // triggers a fresh recalculation); the legacy flow reloads the per-metric results directly.
+ if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
+ actions.refreshExperimentResults(true, 'config_change')
+ } else if (isPrimary) {
actions.loadPrimaryMetricsResults(true)
} else {
actions.loadSecondaryMetricsResults(true)
@@ -2450,9 +2476,15 @@ export const experimentLogic = kea<experimentLogicType>([
},
}
)
- // Re-fetch metric and exposure results since the variant set changed.
- actions.loadPrimaryMetricsResults(true)
- actions.loadSecondaryMetricsResults(true)
+ // Re-fetch results since the variant set changed. On the recalculation flow this means a
+ // fresh recalc; on the legacy flow it's the per-metric loaders. Exposures refresh either way.
+ if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
+ values.experiment &&
+ experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation()
+ } else {
+ actions.loadPrimaryMetricsResults(true)
+ actions.loadSecondaryMetricsResults(true)
+ }
actions.loadExposures(true)
} catch (error) {
lemonToast.error('Could not update variant exclusion. Please try again.')
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
new file mode 100644
index 000000000000..91df2eb040d8
--- /dev/null
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
@@ -0,0 +1,552 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { projectLogic } from 'scenes/projectLogic'
+
+import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { Experiment } from '~/types'
+
+import { experimentMetricsLogic } from './experimentMetricsLogic'
+
+jest.mock('@posthog/lemon-ui', () => ({
+ ...jest.requireActual('@posthog/lemon-ui'),
+ lemonToast: { error: jest.fn(), success: jest.fn(), info: jest.fn() },
+}))
+
+// Mirrors the private poll interval in experimentMetricsLogic.
+const POLL_INTERVAL_MS = 2000
+// Mirrors the private MAX_POLL_RETRIES in experimentMetricsLogic.
+const MAX_POLL_RETRIES = 5
+
+const EXPERIMENT = experimentJson as unknown as Experiment
+const PRIMARY_METRIC_UUID = '434cb6ba-7fa6-4ca1-b7a0-8970b2d9a47d'
+const SECONDARY_METRIC_UUID = 'cbdd02f8-4a27-4017-a8d8-5f989b304ada'
+
+const primaryResult = { some: 'primary-result' }
+const secondaryResult = { some: 'secondary-result' }
+
+const baseRecalculation = {
+ experiment_id: EXPERIMENT.id,
+ total_metrics: 2,
+ completed_metrics: 0,
+ failed_metrics: 0,
+ metric_errors: {},
+ trigger: 'manual',
+ created_at: '2026-06-10T00:00:00Z',
+ started_at: null,
+ completed_at: null,
+ is_existing: false,
+ results: [],
+}
+
+const completedRecalculation = {
+ ...baseRecalculation,
+ id: 'recalc-1',
+ status: 'completed',
+ completed_metrics: 2,
+ started_at: new Date().toISOString(),
+ // Fresh by default (within the 24h window) so tests using this fixture don't auto-trigger.
+ completed_at: new Date().toISOString(),
+ results: [
+ { metric_uuid: PRIMARY_METRIC_UUID, status: 'completed', result: primaryResult, error_message: null },
+ { metric_uuid: SECONDARY_METRIC_UUID, status: 'completed', result: secondaryResult, error_message: null },
+ ],
+}
+
+// completed_at far in the past → older than the 24h staleness threshold.
+const staleCompletedRecalculation = {
+ ...completedRecalculation,
+ completed_at: '2020-01-01T00:00:00Z',
+}
+const freshCompletedRecalculation = completedRecalculation
+
+const pendingRecalculation = { ...baseRecalculation, id: 'recalc-2', status: 'pending' }
+const inProgressRecalculation = { ...baseRecalculation, id: 'recalc-2', status: 'in_progress' }
+const completedRecalculation2 = { ...completedRecalculation, id: 'recalc-2' }
+
+// Run finished but the primary metric failed and the secondary succeeded — a partial failure.
+const partialFailureRecalculation = {
+ ...baseRecalculation,
+ id: 'recalc-2',
+ status: 'failed',
+ total_metrics: 2,
+ completed_metrics: 1,
+ failed_metrics: 1,
+ completed_at: new Date().toISOString(),
+ metric_errors: { [PRIMARY_METRIC_UUID]: { step: 'calculation', message: 'boom' } },
+ results: [
+ { metric_uuid: PRIMARY_METRIC_UUID, status: 'failed', result: null, error_message: 'boom' },
+ { metric_uuid: SECONDARY_METRIC_UUID, status: 'completed', result: secondaryResult, error_message: null },
+ ],
+}
+
+describe('experimentMetricsLogic', () => {
+ let logic: ReturnType<typeof experimentMetricsLogic.build>
+
+ beforeEach(async () => {
+ // Default handlers so every afterMount-driven load/trigger has a mock; tests override per-case.
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [201, pendingRecalculation],
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {
+ [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,
+ })
+ // Wait for the bootstrap to populate currentProjectId — the loader guards on it.
+ await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })
+ })
+
+ afterEach(async () => {
+ // Let the afterMount load settle before unmount so its promise can't bleed into the next test.
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ logic?.unmount()
+ })
+
+ const mountLogic = (): void => {
+ logic = experimentMetricsLogic({ experiment: EXPERIMENT })
+ logic.mount()
+ }
+
+ it('is keyed by the experiment id', () => {
+ mountLogic()
+ expect(logic.key).toEqual(EXPERIMENT.id)
+ })
+
+ describe('loadLatestRecalculation', () => {
+ it.each([
+ // Draft: never launched (no start_date, no status).
+ ['draft', { ...EXPERIMENT, status: undefined, start_date: null, end_date: null } as Experiment],
+ // Stopped/completed: launched then ended (has an end_date).
+ ['stopped', { ...EXPERIMENT, status: undefined, end_date: '2025-01-01T00:00:00Z' } as Experiment],
+ ])('does not fetch latest on mount for a %s experiment', async (_label, experiment) => {
+ const latestMock = jest.fn(() => [200, completedRecalculation])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': latestMock,
+ },
+ })
+ logic = experimentMetricsLogic({ experiment })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadLatestRecalculation'])
+ // Gated before the request: a non-running experiment has nothing to recalculate.
+ expect(latestMock).not.toHaveBeenCalled()
+ expect(logic.values.currentRecalculation).toBeNull()
+ })
+
+ it('loads the latest completed recalculation and maps results by metric position', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ completedRecalculation,
+ ],
+ },
+ })
+ mountLogic()
+
+ // afterMount fires loadLatestRecalculation on its own — no manual dispatch needed.
+ await expectLogic(logic).toDispatchActions([
+ 'setCurrentRecalculation',
+ 'setPrimaryMetricsResults',
+ 'setSecondaryMetricsResults',
+ ])
+
+ expect(logic.values.currentRecalculation).toEqual(
+ expect.objectContaining({ id: 'recalc-1', status: 'completed' })
+ )
+ // saved_metrics in the fixture have no query uuid, so they map to undefined positions —
+ // the inline metric result lands first.
+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)
+ expect(logic.values.secondaryMetricsResults[0]).toEqual(secondaryResult)
+ expect(logic.values.recalculationLoading).toBe(false)
+ })
+
+ it('shows no error toast on 404 (a fresh recalc is triggered instead)', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 404,
+ { detail: 'No completed recalculation found' },
+ ],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [201, pendingRecalculation],
+ },
+ })
+ mountLogic()
+
+ // 404 routes to triggerRecalculation, not an error; results stay empty until it completes.
+ await expectLogic(logic).toDispatchActions(['loadLatestRecalculation', 'triggerRecalculation'])
+
+ expect(lemonToast.error).not.toHaveBeenCalled()
+ expect(logic.values.primaryMetricsResults).toEqual([])
+ expect(logic.values.secondaryMetricsResults).toEqual([])
+ })
+
+ it('toggles recalculationLoading true while in flight then false when done', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ completedRecalculation,
+ ],
+ },
+ })
+ mountLogic()
+
+ // afterMount fires the load synchronously enough that loading flips true immediately.
+ expect(logic.values.recalculationLoading).toBe(true)
+
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+ expect(logic.values.recalculationLoading).toBe(false)
+ })
+
+ it('triggers a new recalculation when latest returns 404', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [201, pendingRecalculation],
+ },
+ })
+ mountLogic()
+
+ // afterMount → loadLatestRecalculation → 404 → triggerRecalculation → create → store pending
+ await expectLogic(logic).toDispatchActions(['triggerRecalculation', 'setCurrentRecalculation'])
+ expect(logic.values.currentRecalculation).toEqual(
+ expect.objectContaining({ id: 'recalc-2', status: 'pending' })
+ )
+ })
+
+ it('auto-triggers a fresh recalculation when the latest completed run is stale (>24h)', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ staleCompletedRecalculation,
+ ],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [201, pendingRecalculation],
+ },
+ })
+ mountLogic()
+
+ // Stale results still load, but a fresh run is kicked off in the background.
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation', 'triggerRecalculation'])
+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)
+ })
+
+ it('does not auto-trigger when the latest completed run is fresh', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ freshCompletedRecalculation,
+ ],
+ },
+ })
+ mountLogic()
+
+ await expectLogic(logic)
+ .toDispatchActions(['setCurrentRecalculation'])
+ .toNotHaveDispatchedActions(['triggerRecalculation'])
+ })
+
+ it('starts polling after triggering a non-terminal recalculation', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
+ 201,
+ inProgressRecalculation,
+ ],
+ },
+ })
+ mountLogic()
+
+ await expectLogic(logic).toDispatchActions(['triggerRecalculation', 'pollRecalculation'])
+ })
+
+ it('does not poll when the triggered recalculation is already terminal', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
+ 201,
+ completedRecalculation2,
+ ],
+ },
+ })
+ mountLogic()
+
+ await expectLogic(logic)
+ .toDispatchActions(['triggerRecalculation', 'setCurrentRecalculation', 'setPrimaryMetricsResults'])
+ .toNotHaveDispatchedActions(['pollRecalculation'])
+
+ // A terminal create response must still load its results (not just store the recalc).
+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)
+ })
+ })
+
+ describe('triggerRecalculation', () => {
+ it.each([
+ // Draft: never launched (no start_date, no status).
+ ['draft', { ...EXPERIMENT, status: undefined, start_date: null, end_date: null } as Experiment],
+ // Stopped/completed: launched then ended (has an end_date).
+ ['stopped', { ...EXPERIMENT, status: undefined, end_date: '2025-01-01T00:00:00Z' } as Experiment],
+ ])('does not create a recalculation for a %s experiment', async (_label, experiment) => {
+ const createMock = jest.fn(() => [201, pendingRecalculation])
+ useMocks({
+ get: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}] },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ logic = experimentMetricsLogic({ experiment })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.triggerRecalculation()
+ }).toNotHaveDispatchedActions(['pollRecalculation', 'setCurrentRecalculation'])
+ expect(createMock).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('loading + progress selectors', () => {
+ it('exposes progress and isRecalculating while a run is in progress', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ { ...inProgressRecalculation, total_metrics: 5, completed_metrics: 2 },
+ ],
+ },
+ })
+ mountLogic()
+
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+
+ expect(logic.values.recalculationProgress).toEqual({ completed: 2, total: 5 })
+ // in_progress is non-terminal → still recalculating
+ expect(logic.values.isRecalculating).toBe(true)
+ })
+
+ it('is not recalculating once the run is completed', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ completedRecalculation,
+ ],
+ },
+ })
+ mountLogic()
+
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+
+ expect(logic.values.recalculationProgress).toEqual({ completed: 2, total: 2 })
+ expect(logic.values.isRecalculating).toBe(false)
+ // lastRefresh comes from the completed run's completion time.
+ expect(logic.values.lastRefresh).toEqual(completedRecalculation.completed_at)
+ })
+
+ it('defaults progress to zeroes and lastRefresh to null when there is no recalculation', () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ },
+ })
+ mountLogic()
+
+ expect(logic.values.recalculationProgress).toEqual({ completed: 0, total: 0 })
+ expect(logic.values.lastRefresh).toBeNull()
+ })
+ })
+
+ describe('pollRecalculation', () => {
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('polls until completed, then loads results and stops', async () => {
+ // First retrieve still in progress, second completed.
+ let call = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/:recalc_id/': () => {
+ call += 1
+ return [200, call === 1 ? inProgressRecalculation : completedRecalculation2]
+ },
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
+ 201,
+ inProgressRecalculation,
+ ],
+ },
+ })
+ // Fake timers BEFORE mount so the breakpoint's very first setTimeout is fake too.
+ jest.useFakeTimers()
+ mountLogic()
+
+ // Flush the afterMount → 404 → trigger → poll(create) promise chain, then drive the loop.
+ await jest.advanceTimersByTimeAsync(0)
+ for (let i = 0; i < 4; i++) {
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)
+ }
+
+ expect(logic.values.currentRecalculation).toEqual(expect.objectContaining({ status: 'completed' }))
+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)
+ })
+
+ it('on partial failure: loads successes, sets per-metric errors, and shows a tailored toast', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/:recalc_id/': () => [
+ 200,
+ partialFailureRecalculation,
+ ],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
+ 201,
+ inProgressRecalculation,
+ ],
+ },
+ })
+ jest.useFakeTimers()
+ mountLogic()
+
+ await jest.advanceTimersByTimeAsync(0)
+ for (let i = 0; i < 2; i++) {
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)
+ }
+
+ // Tailored toast counts the failures against the total.
+ expect(lemonToast.error).toHaveBeenCalledWith('1 of 2 metrics failed to load')
+ expect(logic.values.currentRecalculation).toEqual(expect.objectContaining({ status: 'failed' }))
+ // The successful secondary metric still loads its result.
+ expect(logic.values.secondaryMetricsResults[0]).toEqual(secondaryResult)
+ // The failed primary metric gets an error with the failure message for its in-row box.
+ expect(logic.values.primaryMetricsResultsErrors[0]).toEqual({ detail: 'boom' })
+ })
+
+ it('gives up after MAX_POLL_RETRIES consecutive retrieve failures', async () => {
+ let retrieveCalls = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/:recalc_id/': () => {
+ retrieveCalls += 1
+ return [500, {}]
+ },
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
+ 201,
+ inProgressRecalculation,
+ ],
+ },
+ })
+ jest.useFakeTimers()
+ mountLogic()
+
+ // Flush afterMount → 404 → trigger → poll(create), then drive enough ticks to exhaust retries.
+ await jest.advanceTimersByTimeAsync(0)
+ for (let i = 0; i < MAX_POLL_RETRIES + 2; i++) {
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)
+ }
+
+ // Stops retrieving once the cap is hit and surfaces an error; never loops forever.
+ expect(retrieveCalls).toBe(MAX_POLL_RETRIES)
+ expect(lemonToast.error).toHaveBeenCalledWith(
+ 'Failed to load recalculation results. Please reload to try again.'
+ )
+ })
+ })
+
+ describe('tab focus does not clobber a loaded run', () => {
+ it('does not reload latest on focus once a run is already loaded', async () => {
+ const latestMock = jest.fn(() => [200, completedRecalculation])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': latestMock,
+ },
+ })
+ mountLogic()
+
+ // Mount fires one load.
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+ expect(latestMock).toHaveBeenCalledTimes(1)
+
+ // Simulate tab focus — the handler must NOT reload, because a run is already loaded.
+ document.dispatchEvent(new Event('visibilitychange'))
+ await expectLogic(logic).toNotHaveDispatchedActions(['loadLatestRecalculation'])
+ expect(latestMock).toHaveBeenCalledTimes(1)
+ })
+ })
+
+ describe('feature flag disabled (legacy path)', () => {
+ it('is a no-op on mount: no API calls, no recalc state', async () => {
+ // Flip the flag off — the legacy flow owns metrics; this logic must do nothing.
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {
+ [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: false,
+ })
+ const latestMock = jest.fn(() => [200, completedRecalculation])
+ const createMock = jest.fn(() => [201, pendingRecalculation])
+ useMocks({
+ get: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': latestMock },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ mountLogic()
+
+ // afterMount still dispatches loadLatestRecalculation, but the flag guard bails immediately.
+ await expectLogic(logic)
+ .toDispatchActions(['loadLatestRecalculation'])
+ .toNotHaveDispatchedActions(['setCurrentRecalculation', 'triggerRecalculation', 'pollRecalculation'])
+
+ // No recalculation endpoints were ever called, and state stays at its defaults.
+ expect(latestMock).not.toHaveBeenCalled()
+ expect(createMock).not.toHaveBeenCalled()
+ expect(logic.values.currentRecalculation).toBeNull()
+ expect(logic.values.recalculationLoading).toBe(false)
+ expect(logic.values.isRecalculating).toBe(false)
+ })
+
+ it('triggerRecalculation and loadLatestRecalculation no-op when the flag is off', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {
+ [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: false,
+ })
+ const createMock = jest.fn(() => [201, pendingRecalculation])
+ useMocks({
+ get: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}] },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ mountLogic()
+
+ // Even an explicit trigger does nothing while the flag is off.
+ await expectLogic(logic, () => {
+ logic.actions.triggerRecalculation()
+ }).toNotHaveDispatchedActions(['pollRecalculation', 'setCurrentRecalculation'])
+ expect(createMock).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
new file mode 100644
index 000000000000..f6b4a6c8d854
--- /dev/null
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -0,0 +1,495 @@
+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { projectLogic } from 'scenes/projectLogic'
+
+import type { Breakdown, CachedNewExperimentQueryResponse, ExperimentMetric } from '~/queries/schema/schema-general'
+import { Experiment } from '~/types'
+
+import {
+ experimentsMetricsRecalculationCreate,
+ experimentsMetricsRecalculationLatestRetrieve,
+ experimentsMetricsRecalculationRetrieve,
+} from 'products/experiments/frontend/generated/api'
+import type { ExperimentMetricsRecalculationApi } from 'products/experiments/frontend/generated/api.schemas'
+
+import type { experimentMetricsLogicType } from './experimentMetricsLogicType'
+import { hasEnded, isLaunched } from './experimentsLogic'
+
+type ExperimentSavedMetric = {
+ metadata: {
+ type: 'primary' | 'secondary'
+ breakdowns?: Breakdown[]
+ }
+ query: ExperimentMetric
+}
+
+/**
+ * This logic can only handle state when an experiment is present.
+ */
+export interface ExperimentMetricsLogicProps {
+ experiment: Experiment
+}
+
+const RECALCULATION_POLL_INTERVAL_MS = 2000
+const RECALCULATION_STALE_AFTER_HOURS = 24
+const MAX_POLL_RETRIES = 5
+
+export const RECALCULATION_STATUSES = {
+ pending: 'pending',
+ in_progress: 'in_progress',
+ completed: 'completed',
+ failed: 'failed',
+} as const
+
+export type RecalculationStatuses = (typeof RECALCULATION_STATUSES)[keyof typeof RECALCULATION_STATUSES]
+
+const isRecalculationStale = (recalculation: ExperimentMetricsRecalculationApi): boolean => {
+ if (!recalculation.completed_at) {
+ return false
+ }
+ return dayjs().diff(dayjs(recalculation.completed_at), 'hours') >= RECALCULATION_STALE_AFTER_HOURS
+}
+
+/**
+ * transform shared metrics into experiment metrics.
+ */
+const sharedMetricsToExperimentMetrics = (
+ sharedMetrics: ExperimentSavedMetric[],
+ type: 'primary' | 'secondary'
+): ExperimentMetric[] =>
+ sharedMetrics
+ .filter(({ metadata }) => metadata.type === type)
+ .map(({ query, metadata }) => ({
+ ...query,
+ breakdownFilter: {
+ ...query?.breakdownFilter,
+ breakdowns: metadata?.breakdowns || [],
+ },
+ }))
+
+// 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) || []
+ return [...(inline as ExperimentMetric[]), ...sharedMetrics]
+}
+
+type MetricErrorState = { detail: string } | null
+type ResolveByUuid<T> = (uuid: string) => T
+
+/**
+ * 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.
+ */
+const alignByMetricPosition =
+ (experiment: Experiment, type: 'primary' | 'secondary') =>
+ <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.
+const resolveResultByUuid = (
+ polledResults: readonly { metric_uuid: string; result: unknown }[] | undefined
+): ResolveByUuid<CachedNewExperimentQueryResponse> => {
+ const resultByUuid = new Map((polledResults ?? []).map((r) => [r.metric_uuid, r.result]))
+ return (uuid) => resultByUuid.get(uuid) as CachedNewExperimentQueryResponse
+}
+
+/**
+ * Resolver: a metric's failure as `{ detail }` (the MetricErrorState shape), or null. `metric_errors`
+ * 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 metricErrors = (recalculation.metric_errors as Record<string, { message?: string }> | null) ?? {}
+ const failedResultMessageByUuid = new Map(
+ (recalculation.results ?? [])
+ .filter((r) => r.status === 'failed' && r.error_message)
+ .map((r) => [r.metric_uuid, r.error_message as string])
+ )
+ return (uuid) => {
+ const message = metricErrors[uuid]?.message ?? failedResultMessageByUuid.get(uuid)
+ return message ? { detail: message } : null
+ }
+}
+
+export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
+ props({} as ExperimentMetricsLogicProps),
+ key((props) => props.experiment.id),
+ path((key) => ['scenes', 'experiment', 'experimentMetricsLogic', String(key)]),
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],
+ actions: [eventUsageLogic, ['reportExperimentMetricRecalculation']],
+ })),
+ actions({
+ setCurrentRecalculation: (recalculation: ExperimentMetricsRecalculationApi | null) => ({ recalculation }),
+ loadLatestRecalculation: true,
+ triggerRecalculation: true,
+ pollRecalculation: (recalculationId: string) => ({ recalculationId }),
+ setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),
+ setSecondaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),
+ setPrimaryMetricsResultsErrors: (errors: (unknown | null)[]) => ({ errors }),
+ setSecondaryMetricsResultsErrors: (errors: (unknown | null)[]) => ({ errors }),
+ setRecalculationLoading: (loading: boolean) => ({ loading }),
+ }),
+ reducers({
+ currentRecalculation: [
+ null as ExperimentMetricsRecalculationApi | null,
+ {
+ setCurrentRecalculation: (_, { recalculation }) => recalculation,
+ },
+ ],
+ recalculationLoading: [
+ false,
+ {
+ setRecalculationLoading: (_, { loading }) => loading,
+ loadLatestRecalculation: () => true,
+ setCurrentRecalculation: () => false,
+ },
+ ],
+ primaryMetricsResults: [
+ [] as CachedNewExperimentQueryResponse[],
+ {
+ setPrimaryMetricsResults: (_, { results }) => results,
+ },
+ ],
+ secondaryMetricsResults: [
+ [] as CachedNewExperimentQueryResponse[],
+ {
+ setSecondaryMetricsResults: (_, { results }) => results,
+ },
+ ],
+ primaryMetricsResultsErrors: [
+ [] as (unknown | null)[],
+ {
+ setPrimaryMetricsResultsErrors: (_, { errors }) => errors,
+ },
+ ],
+ secondaryMetricsResultsErrors: [
+ [] as (unknown | null)[],
+ {
+ setSecondaryMetricsResultsErrors: (_, { errors }) => errors,
+ },
+ ],
+ }),
+ selectors({
+ // True while a recalculation is being fetched or is still running.
+ isRecalculating: [
+ (s) => [s.recalculationLoading, s.currentRecalculation],
+ (recalculationLoading, recalculation): boolean =>
+ recalculationLoading ||
+ recalculation?.status === RECALCULATION_STATUSES.pending ||
+ recalculation?.status === RECALCULATION_STATUSES.in_progress,
+ ],
+ recalculationProgress: [
+ (s) => [s.currentRecalculation],
+ (recalc): { completed: number; total: number } => ({
+ completed: recalc?.completed_metrics ?? 0,
+ total: recalc?.total_metrics ?? 0,
+ }),
+ ],
+ lastRefresh: [(s) => [s.currentRecalculation], (recalc): string | null => recalc?.completed_at ?? null],
+ }),
+ listeners(({ actions, values, props, cache }) => {
+ const flagEnabled = (): boolean => !!values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]
+
+ /**
+ * Recalculations only make sense for a running experiment: a draft has no results to fetch, and a
+ * stopped one is frozen. Gates both the latest-fetch and triggering a new run.
+ */
+ const experimentIsRunning = (): boolean => isLaunched(props.experiment) && !hasEnded(props.experiment)
+
+ /**
+ * some local helpers for the listeners closure
+ */
+
+ /**
+ * extracts project id and experiment id from values and props.
+ */
+ const ids = (): { projectId: number; experimentId: number } | null => {
+ const projectId = values.currentProjectId
+ const experimentId = props.experiment.id
+ if (!projectId || typeof experimentId !== 'number') {
+ return null
+ }
+ return { projectId, experimentId }
+ }
+
+ /**
+ * 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 startMs = cache.recalcStartMs ?? Date.now()
+ actions.reportExperimentMetricRecalculation(
+ recalculation.status === RECALCULATION_STATUSES.completed ? 'completed' : 'failed',
+ {
+ experiment_id: props.experiment.id as number,
+ recalculation_id: recalculation.id,
+ total_metrics: recalculation.total_metrics,
+ succeeded: recalculation.completed_metrics,
+ failed: recalculation.failed_metrics,
+ duration_ms: Date.now() - startMs,
+ poll_count: cache.pollCount ?? 0,
+ }
+ )
+ }
+
+ /**
+ * 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 resultFor = resolveResultByUuid(recalculation.results)
+ const errorFor = resolveErrorByUuid(recalculation)
+
+ const alignPrimary = alignByMetricPosition(props.experiment, 'primary')
+ const alignSecondary = alignByMetricPosition(props.experiment, 'secondary')
+
+ actions.setPrimaryMetricsResults(alignPrimary(resultFor))
+ actions.setSecondaryMetricsResults(alignSecondary(resultFor))
+ actions.setPrimaryMetricsResultsErrors(alignPrimary(errorFor))
+ actions.setSecondaryMetricsResultsErrors(alignSecondary(errorFor))
+ }
+
+ return {
+ loadLatestRecalculation: async () => {
+ /**
+ * bail if feature not enabled. Clear recalculation loading state
+ */
+ if (!flagEnabled()) {
+ actions.setRecalculationLoading(false)
+ return
+ }
+ // Don't fetch for draft or stopped experiments — there's nothing to recalculate.
+ if (!experimentIsRunning()) {
+ actions.setRecalculationLoading(false)
+ return
+ }
+ /**
+ * guard against invalid project or experiment. bail and clear recalculation
+ * loading state
+ */
+ const resolvedIds = ids()
+ if (!resolvedIds) {
+ actions.setRecalculationLoading(false)
+ return
+ }
+
+ try {
+ const { projectId, experimentId } = resolvedIds
+ /**
+ * retrieve the latest complete recalculation so we always show results, even if stale.
+ * store it in state and apply the results.
+ */
+ const recalculation = await experimentsMetricsRecalculationLatestRetrieve(
+ String(projectId),
+ experimentId
+ )
+ actions.setCurrentRecalculation(recalculation)
+ applyResults(recalculation)
+
+ /**
+ * if the recalculation resutls are stale, trigger a new recalculation
+ * without hiding the existing resutls.
+ */
+ if (isRecalculationStale(recalculation)) {
+ actions.triggerRecalculation()
+ }
+ } catch (error: any) {
+ if (error?.status === 404) {
+ /**
+ * if there are no completed recalculations, kick off a new one.
+ * this should only run on page loads, so no need to load exposures.
+ */
+ actions.triggerRecalculation()
+ return
+ }
+
+ lemonToast.error('Failed to load latest recalculation')
+ } finally {
+ actions.setRecalculationLoading(false)
+ }
+ },
+ triggerRecalculation: async () => {
+ /**
+ * bail if feature not enabled
+ */
+ if (!flagEnabled()) {
+ return
+ }
+ /**
+ * Don't recalculate draft or stopped experiments; a config-change edit on either shouldn't
+ * kick off a run.
+ */
+ if (!experimentIsRunning()) {
+ return
+ }
+ /**
+ * guard against invalid project or experiment. bail and clear recalculation
+ * loading state
+ */
+ const resolvedIds = ids()
+ if (!resolvedIds) {
+ return
+ }
+ try {
+ const { projectId, experimentId } = resolvedIds
+ // 201 with a new pending run, or 200 with the already-active one. No results yet.
+ // Create a recalculation workflow. 201: a new run. 200: one is already running, poll it.
+ const recalculation = await experimentsMetricsRecalculationCreate(String(projectId), experimentId, {
+ trigger: 'manual',
+ })
+
+ /**
+ * Mark the active run. A terminal-on-create run (below) applies results without
+ * dispatching pollRecalculation, so breakpoint can't abort an older poll; pollRecalculation
+ * re-checks this id after its fetch and bails if a newer run took over.
+ */
+ cache.activeRecalculationId = recalculation.id
+ /**
+ * Lifecycle clock + poll count for the terminal-state analytics event. Reset on every
+ * trigger so duration_ms / poll_count are anchored to THIS run.
+ */
+ cache.recalcStartMs = Date.now()
+ cache.pollCount = 0
+ cache.pollRetryCount = 0
+ actions.setCurrentRecalculation(recalculation)
+ actions.reportExperimentMetricRecalculation('triggered', {
+ experiment_id: experimentId,
+ recalculation_id: recalculation.id,
+ trigger: 'manual',
+ is_existing: recalculation.is_existing,
+ })
+
+ if (
+ recalculation.status === RECALCULATION_STATUSES.completed ||
+ recalculation.status === RECALCULATION_STATUSES.failed
+ ) {
+ /**
+ * Create can return an already-terminal run (e.g. a completed one finished between
+ * request and response). Load its results directly rather than polling.
+ */
+ applyResults(recalculation)
+ emitTerminalEvent(recalculation)
+ } else {
+ actions.pollRecalculation(recalculation.id)
+ }
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Failed to trigger metrics recalculation')
+ }
+ },
+ /**
+ * Polls one run to terminal status, re-arming one tick at a time rather than looping in place.
+ * `breakpoint` is kea's cancellation primitive: `await breakpoint(ms)` paces the poll and throws
+ * if pollRecalculation re-fires or the logic unmounts; `breakpoint()` re-checks without delaying.
+ * So a newer poll auto-cancels this one's in-flight breakpoint before it can write stale results:
+ * free poll-vs-poll supersession, no interval to clear. The gap: a terminal-on-create run applies
+ * results without dispatching pollRecalculation, so cache.activeRecalculationId covers that case.
+ */
+ pollRecalculation: async ({ recalculationId }, breakpoint) => {
+ if (!flagEnabled()) {
+ return
+ }
+ const resolvedIds = ids()
+ if (!resolvedIds) {
+ return
+ }
+ const { projectId, experimentId } = resolvedIds
+ // First tick of a new run (the active id changed): reset the retry streak so a prior run that
+ // exhausted its retries doesn't leave the counter at the cap for this one.
+ if (cache.activeRecalculationId !== recalculationId) {
+ cache.pollRetryCount = 0
+ }
+ cache.activeRecalculationId = recalculationId
+
+ // Pace this tick; aborts here if a newer poll superseded us or the logic unmounted.
+ await breakpoint(RECALCULATION_POLL_INTERVAL_MS)
+
+ let recalculation: ExperimentMetricsRecalculationApi
+ try {
+ recalculation = await experimentsMetricsRecalculationRetrieve(
+ String(projectId),
+ experimentId,
+ recalculationId
+ )
+ } catch {
+ /**
+ * Retry on transient errors, but give up after MAX_POLL_RETRIES consecutive failures so a
+ * persistently failing endpoint can't poll forever.
+ */
+ cache.pollRetryCount = (cache.pollRetryCount ?? 0) + 1
+ if (cache.pollRetryCount >= MAX_POLL_RETRIES) {
+ lemonToast.error('Failed to load recalculation results. Please reload to try again.')
+ return
+ }
+ actions.pollRecalculation(recalculationId)
+ return
+ }
+ // Healthy response; reset the retry streak so an earlier blip doesn't count against later ticks.
+ cache.pollRetryCount = 0
+ // A newer poll may have started while the request was in flight; abort before writing results.
+ breakpoint()
+ /**
+ * breakpoint covers a newer POLL; this covers a newer terminal-on-create run that applied
+ * results directly without dispatching pollRecalculation (so breakpoint never fired for us).
+ */
+ if (cache.activeRecalculationId !== recalculationId) {
+ return
+ }
+
+ /**
+ * Count only polls that pass the supersession check so the analytics event reflects the work
+ * THIS run actually paid for; superseded ticks would otherwise inflate the number.
+ */
+ cache.pollCount = (cache.pollCount ?? 0) + 1
+
+ actions.setCurrentRecalculation(recalculation)
+
+ if (
+ recalculation.status === RECALCULATION_STATUSES.pending ||
+ recalculation.status === RECALCULATION_STATUSES.in_progress
+ ) {
+ actions.pollRecalculation(recalculationId)
+ return
+ }
+
+ // Successful metrics load, failed metrics surface their error in-row.
+ applyResults(recalculation)
+ emitTerminalEvent(recalculation)
+ if (recalculation.failed_metrics > 0) {
+ lemonToast.error(
+ `${recalculation.failed_metrics} of ${recalculation.total_metrics} metrics failed to load`
+ )
+ }
+ },
+ }
+ }),
+ afterMount(({ actions, values, cache }) => {
+ // Fetch the latest completed recalculation on mount; the listener no-ops when the flag is off.
+ actions.loadLatestRecalculation()
+
+ /**
+ * On tab visible, re-fetch the latest only when nothing is loaded: refetching would overwrite a
+ * displayed failure state with the last completed run.
+ */
+ cache.disposables.add(
+ () => {
+ const handler = (): void => {
+ if (document.visibilityState === 'visible' && !values.currentRecalculation) {
+ actions.loadLatestRecalculation()
+ }
+ }
+ document.addEventListener('visibilitychange', handler)
+ return () => document.removeEventListener('visibilitychange', handler)
+ },
+ 'recalculationVisibility',
+ { pauseOnPageHidden: false }
+ )
+ }),
+])
diff --git a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts
new file mode 100644
index 000000000000..183d36e686df
--- /dev/null
+++ b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts
@@ -0,0 +1,102 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { projectLogic } from 'scenes/projectLogic'
+
+import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { Experiment } from '~/types'
+
+import { experimentMetricsLogic } from './experimentMetricsLogic'
+import { experimentResultsNotificationLogic } from './experimentResultsNotificationLogic'
+
+const EXPERIMENT = experimentJson as unknown as Experiment
+const OFFER_DELAY_MS = 10_000
+
+describe('experimentResultsNotificationLogic', () => {
+ let logic: ReturnType<typeof experimentResultsNotificationLogic.build>
+ let metricsLogic: ReturnType<typeof experimentMetricsLogic.build>
+
+ beforeEach(async () => {
+ // Latest returns a completed run so the metrics logic's afterMount settles to a stable
+ // terminal (isRecalculating=false) state — the tests then drive transitions deterministically.
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ {
+ id: 'seed',
+ status: 'completed',
+ total_metrics: 0,
+ completed_metrics: 0,
+ failed_metrics: 0,
+ completed_at: new Date().toISOString(),
+ results: [],
+ },
+ ],
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {
+ [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,
+ })
+ await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })
+
+ metricsLogic = experimentMetricsLogic({ experiment: EXPERIMENT })
+ metricsLogic.mount()
+ logic = experimentResultsNotificationLogic({ experiment: EXPERIMENT })
+ logic.mount()
+ // Let the metrics logic's afterMount load settle so isRecalculating is a stable false.
+ await expectLogic(metricsLogic).toDispatchActions(['setCurrentRecalculation'])
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ logic?.unmount()
+ metricsLogic?.unmount()
+ })
+
+ it('offers the notification banner once a recalculation has run for the delay', async () => {
+ jest.useFakeTimers()
+ // Recalculation starts → the offer timer begins.
+ metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'in_progress' } as any)
+ expect(logic.values.showNotificationOffer).toBe(false)
+
+ await jest.advanceTimersByTimeAsync(OFFER_DELAY_MS)
+ expect(logic.values.showNotificationOffer).toBe(true)
+ })
+
+ it('resets the offer when the recalculation finishes', async () => {
+ jest.useFakeTimers()
+ metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'in_progress' } as any)
+ await jest.advanceTimersByTimeAsync(OFFER_DELAY_MS)
+ expect(logic.values.showNotificationOffer).toBe(true)
+
+ // Recalculation completes → offer is cleared.
+ metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'completed' } as any)
+ await expectLogic(logic).toDispatchActions(['notifyResultsReady'])
+ expect(logic.values.showNotificationOffer).toBe(false)
+ expect(logic.values.notifyWhenResultsReady).toBe(false)
+ })
+
+ it('dismissNotificationOffer clears both flags', () => {
+ logic.actions.setShowNotificationOffer(true)
+ logic.actions.setNotifyWhenResultsReady(true)
+ logic.actions.dismissNotificationOffer()
+ expect(logic.values.showNotificationOffer).toBe(false)
+ expect(logic.values.notifyWhenResultsReady).toBe(false)
+ })
+
+ it('dismissing the offer disposes the pending timer so it cannot re-show the banner', async () => {
+ jest.useFakeTimers()
+ metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'in_progress' } as any)
+ // Dismiss before the offer timer fires.
+ logic.actions.dismissNotificationOffer()
+ await jest.advanceTimersByTimeAsync(OFFER_DELAY_MS)
+ // The timer was disposed, so the offer must stay dismissed.
+ expect(logic.values.showNotificationOffer).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.ts b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.ts
new file mode 100644
index 000000000000..efdf296434eb
--- /dev/null
+++ b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.ts
@@ -0,0 +1,126 @@
+import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { subscriptions } from 'kea-subscriptions'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { Experiment } from '~/types'
+
+import { experimentMetricsLogic } from './experimentMetricsLogic'
+import type { experimentResultsNotificationLogicType } from './experimentResultsNotificationLogicType'
+
+export interface ExperimentResultsNotificationLogicProps {
+ experiment: Experiment
+}
+
+// How long a recalculation must run before we offer the "notify me when ready" banner.
+const NOTIFICATION_OFFER_DELAY_MS = 10_000
+
+/**
+ * Standalone "results are taking a while" notification for the recalculation flow: offers a banner
+ * once a recalculation has been running for a bit, and (if the user opts in) fires a browser
+ * notification when it finishes. Driven entirely by `experimentMetricsLogic.isRecalculating` so it's
+ * decoupled from how results are loaded. The legacy equivalent still lives in experimentLogic.
+ */
+export const experimentResultsNotificationLogic = kea<experimentResultsNotificationLogicType>([
+ props({} as ExperimentResultsNotificationLogicProps),
+ key((props) => props.experiment.id),
+ path((key) => ['scenes', 'experiment', 'experimentResultsNotificationLogic', String(key)]),
+ connect((props: ExperimentResultsNotificationLogicProps) => ({
+ values: [experimentMetricsLogic({ experiment: props.experiment }), ['isRecalculating']],
+ })),
+ actions({
+ setShowNotificationOffer: (show: boolean) => ({ show }),
+ setNotifyWhenResultsReady: (notify: boolean) => ({ notify }),
+ dismissNotificationOffer: true,
+ subscribeToResultsNotification: true,
+ notifyResultsReady: true,
+ }),
+ reducers({
+ showNotificationOffer: [
+ false,
+ {
+ setShowNotificationOffer: (_, { show }) => show,
+ dismissNotificationOffer: () => false,
+ },
+ ],
+ notifyWhenResultsReady: [
+ false,
+ {
+ setNotifyWhenResultsReady: (_, { notify }) => notify,
+ dismissNotificationOffer: () => false,
+ },
+ ],
+ }),
+ listeners(({ props, values, actions, cache }) => ({
+ dismissNotificationOffer: () => {
+ // Stop the pending offer timer so it can't re-show the banner after the user dismissed it.
+ cache.disposables.dispose('notificationOfferTimer')
+ },
+ subscribeToResultsNotification: async () => {
+ if (!('Notification' in window)) {
+ lemonToast.error('Your browser does not support notifications.')
+ return
+ }
+ let permission = Notification.permission
+ if (permission === 'default') {
+ permission = await Notification.requestPermission()
+ }
+ if (permission === 'granted') {
+ actions.setNotifyWhenResultsReady(true)
+ } else if (permission === 'denied') {
+ lemonToast.info(
+ 'Notifications are blocked. Enable them in your browser address bar or system settings.'
+ )
+ }
+ },
+ // Fire the browser notification (if subscribed) once a recalculation finishes.
+ notifyResultsReady: () => {
+ if (values.notifyWhenResultsReady && 'Notification' in window && Notification.permission === 'granted') {
+ const notification = new Notification('Experiment results ready', {
+ body: `Results for "${props.experiment.name}" are now available.`,
+ icon: '/static/posthog-icon.svg',
+ tag: `experiment-results-${props.experiment.id}`,
+ })
+ notification.onclick = () => {
+ window.focus()
+ notification.close()
+ }
+ }
+ cache.disposables.dispose('notificationOfferTimer')
+ actions.setShowNotificationOffer(false)
+ actions.setNotifyWhenResultsReady(false)
+ },
+ })),
+ /**
+ * Subscriptions (not listeners) on purpose: we react to the EDGE of `isRecalculating`, a derived
+ * boolean composed from two upstream actions (setCurrentRecalculation + setRecalculationLoading) on
+ * experimentMetricsLogic. There's no single action whose handler cleanly expresses "the derived value
+ * just flipped", so this is the skill's sanctioned subscriptions case. The (next, prev) args give us
+ * the transition for free instead of hand-tracking a previous value across two listeners.
+ */
+ subscriptions(({ actions, cache }) => ({
+ isRecalculating: (isRecalculating: boolean, previous: boolean | undefined) => {
+ if (isRecalculating && !previous) {
+ /**
+ * A recalculation just started: offer the banner after it has been running a while. The
+ * timer must keep running while the tab is hidden (the point is to notify a user who has
+ * navigated away), so it opts out of pause-on-page-hide.
+ */
+ cache.disposables.add(
+ () => {
+ const timer = setTimeout(
+ () => actions.setShowNotificationOffer(true),
+ NOTIFICATION_OFFER_DELAY_MS
+ )
+ return () => clearTimeout(timer)
+ },
+ 'notificationOfferTimer',
+ { pauseOnPageHidden: false }
+ )
+ } else if (!isRecalculating && previous) {
+ // Fire the notification (if subscribed) and reset the offer.
+ actions.notifyResultsReady()
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index 44cd97a86170..18fe3a19c97b 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -39,6 +39,7 @@ import {
isEvenlyDistributed,
isLegacyExperiment,
isLegacyExperimentQuery,
+ metricResults,
percentageDistribution,
} from './utils'
@@ -1352,6 +1353,206 @@ describe('getOrderedMetricsWithResults', () => {
})
})
+describe('metricResults', () => {
+ const baseExperiment = {
+ ...experimentJson,
+ metrics: [],
+ metrics_secondary: [],
+ saved_metrics: [],
+ primary_metrics_ordered_uuids: [],
+ secondary_metrics_ordered_uuids: [],
+ } as unknown as Experiment
+
+ const mockResult = (data: Record<string, any>): CachedNewExperimentQueryResponse =>
+ data as CachedNewExperimentQueryResponse
+
+ const inlineMetric = (uuid: string, event: string): ExperimentMetric =>
+ ({
+ uuid,
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ source: { kind: NodeKind.EventsNode, event },
+ }) as unknown as ExperimentMetric
+
+ it('returns an empty array when the experiment has no metrics', () => {
+ expect(metricResults(baseExperiment)([], [], 'primary')).toEqual([])
+ })
+
+ it('returns an empty array when no ordered uuids reference existing metrics', () => {
+ const experiment = {
+ ...baseExperiment,
+ metrics: [inlineMetric('metric-1', 'test')],
+ // ordered uuids point at a metric that no longer exists
+ primary_metrics_ordered_uuids: ['stale-uuid'],
+ }
+ expect(metricResults(experiment)([mockResult({ result: 'data' })], [null], 'primary')).toEqual([])
+ })
+
+ it('zips inline metrics with their results and errors', () => {
+ const experiment = {
+ ...baseExperiment,
+ metrics: [inlineMetric('metric-1', 'test')],
+ primary_metrics_ordered_uuids: ['metric-1'],
+ }
+
+ const ordered = metricResults(experiment)([mockResult({ result: 'data1' })], [null], 'primary')
+
+ expect(ordered).toEqual([
+ {
+ metric: expect.objectContaining({ uuid: 'metric-1' }),
+ result: { result: 'data1' },
+ error: null,
+ displayIndex: 0,
+ metricIndex: 0,
+ },
+ ])
+ })
+
+ it('respects the display ordering, not the metric array order', () => {
+ const experiment = {
+ ...baseExperiment,
+ metrics: [inlineMetric('metric-1', 'test1'), inlineMetric('metric-2', 'test2')],
+ primary_metrics_ordered_uuids: ['metric-2', 'metric-1'],
+ }
+
+ const ordered = metricResults(experiment)(
+ [mockResult({ result: 'data1' }), mockResult({ result: 'data2' })],
+ [null, null],
+ 'primary'
+ )
+
+ expect(ordered.map((o) => o.metric.uuid)).toEqual(['metric-2', 'metric-1'])
+ // displayIndex follows the ordering; metricIndex stays the original array position
+ expect(ordered.map((o) => o.displayIndex)).toEqual([0, 1])
+ expect(ordered.map((o) => o.metricIndex)).toEqual([1, 0])
+ // results map by uuid, so metric-2 keeps data2 despite being shown first
+ expect(ordered.map((o) => o.result)).toEqual([{ result: 'data2' }, { result: 'data1' }])
+ })
+
+ it('enriches shared metrics and merges metadata breakdowns', () => {
+ const breakdowns: Breakdown[] = [{ property: '$browser', type: 'event' }]
+ const experiment = {
+ ...baseExperiment,
+ saved_metrics: [
+ {
+ saved_metric: 123,
+ name: 'Shared Metric',
+ query: {
+ uuid: 'shared-uuid',
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ source: { kind: NodeKind.EventsNode, event: 'test' },
+ },
+ metadata: { type: 'primary', breakdowns },
+ },
+ ],
+ primary_metrics_ordered_uuids: ['shared-uuid'],
+ }
+
+ const ordered = metricResults(experiment)([mockResult({ result: 'shared' })], [null], 'primary')
+
+ expect(ordered).toHaveLength(1)
+ expect(ordered[0].metric.uuid).toBe('shared-uuid')
+ expect(ordered[0].metric.name).toBe('Shared Metric')
+ expect(ordered[0].metric.sharedMetricId).toBe(123)
+ expect(ordered[0].metric.isSharedMetric).toBe(true)
+ expect(ordered[0].metric.breakdownFilter?.breakdowns).toEqual(breakdowns)
+ })
+
+ it('only includes shared metrics whose metadata type matches', () => {
+ const experiment = {
+ ...baseExperiment,
+ saved_metrics: [
+ {
+ saved_metric: 1,
+ name: 'Primary Shared',
+ query: { uuid: 'p-uuid', kind: NodeKind.ExperimentMetric, source: {} },
+ metadata: { type: 'primary' },
+ },
+ {
+ saved_metric: 2,
+ name: 'Secondary Shared',
+ query: { uuid: 's-uuid', kind: NodeKind.ExperimentMetric, source: {} },
+ metadata: { type: 'secondary' },
+ },
+ ],
+ primary_metrics_ordered_uuids: ['p-uuid'],
+ secondary_metrics_ordered_uuids: ['s-uuid'],
+ }
+
+ const zip = metricResults(experiment)
+ expect(zip([mockResult({ r: 1 })], [null], 'primary').map((o) => o.metric.uuid)).toEqual(['p-uuid'])
+ expect(zip([mockResult({ r: 2 })], [null], 'secondary').map((o) => o.metric.uuid)).toEqual(['s-uuid'])
+ })
+
+ it('drops metrics that have no uuid', () => {
+ const experiment = {
+ ...baseExperiment,
+ metrics: [
+ { kind: NodeKind.ExperimentMetric, source: {} } as unknown as ExperimentMetric, // no uuid
+ inlineMetric('metric-2', 'test'),
+ ],
+ primary_metrics_ordered_uuids: ['metric-2'],
+ }
+
+ const ordered = metricResults(experiment)(
+ [mockResult({ result: 'data1' }), mockResult({ result: 'data2' })],
+ [null, null],
+ 'primary'
+ )
+
+ expect(ordered).toHaveLength(1)
+ expect(ordered[0].metric.uuid).toBe('metric-2')
+ // metric-2 is at original index 1, so it picks results[1]
+ expect(ordered[0].result).toEqual({ result: 'data2' })
+ expect(ordered[0].metricIndex).toBe(1)
+ })
+
+ it('yields undefined result/error when the arrays are shorter than the metric list', () => {
+ const experiment = {
+ ...baseExperiment,
+ metrics: [inlineMetric('metric-1', 'test')],
+ primary_metrics_ordered_uuids: ['metric-1'],
+ }
+
+ const ordered = metricResults(experiment)([], [], 'primary')
+
+ expect(ordered).toHaveLength(1)
+ expect(ordered[0].result).toBeUndefined()
+ expect(ordered[0].error).toBeUndefined()
+ })
+
+ it('surfaces a per-metric error alongside its metric', () => {
+ const experiment = {
+ ...baseExperiment,
+ metrics: [inlineMetric('metric-1', 'test')],
+ primary_metrics_ordered_uuids: ['metric-1'],
+ }
+ const error = { detail: 'boom' }
+
+ const ordered = metricResults(experiment)([mockResult({})], [error], 'primary')
+
+ expect(ordered[0].error).toBe(error)
+ })
+
+ it('can be bound once and reused for primary and secondary (currying)', () => {
+ const experiment = {
+ ...baseExperiment,
+ metrics: [inlineMetric('p-1', 'p')],
+ metrics_secondary: [inlineMetric('s-1', 's')],
+ primary_metrics_ordered_uuids: ['p-1'],
+ secondary_metrics_ordered_uuids: ['s-1'],
+ }
+
+ const zip = metricResults(experiment)
+ const primary = zip([mockResult({ result: 'p' })], [null], 'primary')
+ const secondary = zip([mockResult({ result: 's' })], [null], 'secondary')
+
+ expect(primary.map((o) => o.metric.uuid)).toEqual(['p-1'])
+ expect(secondary.map((o) => o.metric.uuid)).toEqual(['s-1'])
+ })
+})
+
describe('getEventCountQuery', () => {
it('includes product analytics tags in the query', () => {
const metric: ExperimentMetric = {
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 14c3718a3ebd..b0fff55ac5d5 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -951,3 +951,87 @@ export function getOrderedMetricsWithResults(
metricIndex: originalIndexMap.get(metric.uuid) ?? index, // Original position for retry
}))
}
+
+export type MetricWithResult = {
+ metric: ExperimentMetric
+ result: CachedNewExperimentQueryResponse | undefined
+ error: unknown
+ displayIndex: number
+ metricIndex: number
+}
+
+/**
+ * Narrows to a real, saved experiment: present and not the "new"/draft sentinel id. Used by the
+ * recalculation-flow component wrappers before mounting experiment-keyed child logics.
+ */
+export const isSavedExperiment = (experiment: Experiment | null | undefined): experiment is Experiment =>
+ experiment?.id != null && experiment.id !== 'new'
+
+/**
+ * Pure zip of one metric type (`primary` | `secondary`) with its results and errors, in display order.
+ * Same shaping as {@link getOrderedMetricsWithResults} but curried over the experiment, so a caller can
+ * bind it once per experiment instance and reuse it for both primary and secondary:
+ *
+ * const zip = metricResults(experiment)
+ * const primary = zip(primaryResults, primaryErrors, 'primary')
+ * const secondary = zip(secondaryResults, secondaryErrors, 'secondary')
+ *
+ * Used by the recalculation flow; the legacy per-metric path keeps using getOrderedMetricsWithResults.
+ */
+export const metricResults =
+ (experiment: Experiment) =>
+ (
+ results: CachedNewExperimentQueryResponse[],
+ errors: unknown[],
+ type: 'primary' | 'secondary'
+ ): MetricWithResult[] => {
+ const regularMetrics = (
+ type === 'secondary' ? experiment.metrics_secondary || [] : experiment.metrics || []
+ ) as ExperimentMetric[]
+
+ /**
+ * Reshape saved/shared metrics into the inline ExperimentMetric shape so both can be merged and
+ * ordered together below.
+ */
+ const sharedMetrics = (experiment.saved_metrics || [])
+ .filter((sharedMetric) => sharedMetric.metadata?.type === type)
+ .map((sharedMetric) => ({
+ ...sharedMetric.query,
+ name: sharedMetric.name,
+ sharedMetricId: sharedMetric.saved_metric,
+ isSharedMetric: true,
+ breakdownFilter: {
+ ...sharedMetric.query?.breakdownFilter,
+ breakdowns: sharedMetric.metadata?.breakdowns || [],
+ },
+ })) as ExperimentMetric[]
+
+ /**
+ * Merge inline + shared metrics, dropping any without a uuid (defensive). One entry per metric
+ * carries everything the output row needs, keyed by uuid for the ordering pass below.
+ */
+ const byUuid = new Map(
+ [...regularMetrics, ...sharedMetrics]
+ .map((metric, index) => ({ metric, result: results[index], error: errors[index], index }))
+ .filter((entry): entry is { metric: ExperimentMetric & { uuid: string } } & typeof entry =>
+ Boolean(entry.metric.uuid)
+ )
+ .map((entry) => [entry.metric.uuid, entry])
+ )
+
+ const orderedUuids =
+ type === 'secondary'
+ ? experiment.secondary_metrics_ordered_uuids || []
+ : experiment.primary_metrics_ordered_uuids || []
+
+ return orderedUuids
+ .map((uuid) => byUuid.get(uuid))
+ .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry))
+ .map(({ metric, result, error, index }, displayIndex) => ({
+ metric,
+ result,
+ error,
+ displayIndex,
+ metricIndex: index,
+ }))
+ }