:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(experiments): remove the non-recalculations code path (#114305)
Rodrigo Iloro8f9e684062dc
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 16407bab8aaf..6f770b3f9aee 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -350,7 +350,6 @@ export const FEATURE_FLAGS = {EXPERIMENTS_EXCLUDED_VARIANTS: 'experiments-excluded-variants', // owner: @rodrigoi #team-experimentsEXPERIMENTS_FREEZE_EXPOSURE_AA_TEST: 'experiments-freeze-exposure-aa-test', // owner: @mp-hog #team-experiments multivariate=control,test, dogfood A/A used to validate the freeze-exposure lifecycle actionEXPERIMENTS_LEGACY_DEPRECATION_NOTICE: 'experiments-legacy-deprecation-notice', // owner: @andehen #team-experiments, shows the legacy experiments deprecation banner- EXPERIMENTS_METRICS_RECALCULATION: 'experiments-metrics-recalculation', // owner: @rodrigoi #team-experimentsEXPERIMENTS_RECALCULATION_RATE_LIMIT: 'experiment-metric-recalculation-rate-limit', // owner: @rodrigoi #team-experiments, five-minute window between manual metric reloadsEXPERIMENTS_SHOW_SQL: 'experiments-show-sql', // owner: @jurajmajerik #team-experimentsEXPERIMENTS_SYNC_QUERIES: 'experiments-sync-queries', // owner: @andehen #team-experimentsdiff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex ce5d3be9cb60..6c1123272286 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -2038,9 +2038,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([queryId,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.reportExperimentFeatureFlagModalOpened: () => ({}),reportExperimentTimeseriesViewed: (experimentId: ExperimentIdType, metric: ExperimentMetric) => ({experimentId,diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsxindex 3c7ce617970c..c28045491b70 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx@@ -3,8 +3,6 @@ import { useActions, useValues } from 'kea'import { LemonBanner, LemonTab, LemonTabs } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { PendingChangeRequestBanner } from 'scenes/approvals/PendingChangeRequestBanner'import { WebExperimentImplementationDetails } from 'scenes/experiments/WebExperimentImplementationDetails'@@ -44,22 +42,11 @@ import { LoadingState } from './LoadingState'import { MultiVariantBiasWarning } from './MultiVariantBiasWarning'import { PageHeaderCustom } from './PageHeader'import { ReleaseConditionsModal, ReleaseConditionsTable } from './ReleaseConditionsTable'-import { ResultsNotificationBanner } from './ResultsNotificationBanner'import { SettingsTab } from './SettingsTab'const MetricsTab = (): JSX.Element => {- const {- experiment,- orderedPrimaryMetricsWithResults,- orderedSecondaryMetricsWithResults,- isExperimentLaunched,- healthFindings,- browserNoMetricsWarning,- } = useValues(experimentLogic)- const { featureFlags } = useValues(featureFlagLogic)-- const hasMetrics = orderedPrimaryMetricsWithResults.length > 0 || orderedSecondaryMetricsWithResults.length > 0- const showRecalculationStatus = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION] && hasMetrics+ const { experiment, hasMetrics, isExperimentLaunched, healthFindings, browserNoMetricsWarning } =+ useValues(experimentLogic)// With health findings, the health panel above the tabs shows the "No metrics defined" and bias warnings.const showsHealthPanel = healthFindings !== null@@ -75,8 +62,6 @@ const MetricsTab = (): JSX.Element => {return (<>- <ResultsNotificationBanner />-<div className="w-full mb-4 flex flex-col gap-4"><Hypothesis /><div>@@ -85,7 +70,7 @@ const MetricsTab = (): JSX.Element => {</div></div>- {showRecalculationStatus && <RecalculationStatus experiment={experiment} />}+ {hasMetrics && <RecalculationStatus experiment={experiment} />}{/* Modern metrics view */}{!hasMetrics ? (diff --git a/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx b/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsxdeleted file mode 100644index c2b8b9cf4ef7..000000000000--- a/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx+++ /dev/null@@ -1,94 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect } from 'react'--import { IconClock } from '@posthog/icons'-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'--import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'--import { experimentLogic } from '../experimentLogic'--/**- * Legacy "results are taking a while" banner. On the recalculation flow the RecalculationStatus bar- * owns the notify affordance, so this renders nothing there.- */-export function ResultsNotificationBanner(): JSX.Element | null {- const recalculationFlow = useFeatureFlag('EXPERIMENTS_METRICS_RECALCULATION')-- if (recalculationFlow) {- return null- }- 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()- }- window.addEventListener('beforeunload', handler)- return () => window.removeEventListener('beforeunload', handler)- }, [notifyWhenResultsReady, isLoading])-- if (!showNotificationOffer && !notifyWhenResultsReady) {- return null- }- if (!isLoading) {- return null- }-- return (- <LemonBanner- type="info"- className="mb-4"- icon={<IconClock />}- 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={onSubscribe}>- Notify me when ready- </LemonButton>- </div>- )}- </LemonBanner>- )-}--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.tsxindex 22cab1d48a58..ba0906eee8a8 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx@@ -7,11 +7,9 @@ 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 { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { humanFriendlyLargeNumber } from 'lib/utils/numbers'import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'import { MetricBreakdownError } from 'scenes/experiments/MetricBreakdowns/MetricBreakdownError'@@ -518,7 +516,6 @@ interface MetricRowGroupProps {result: NewExperimentQueryResponse | nullexperiment: ExperimentmetricType: InsightType- metricIndex: numberdisplayOrder: numberaxisRange: numberisSecondary: boolean@@ -551,7 +548,6 @@ export function MetricRowGroup({result,experiment,metricType,- metricIndex,displayOrder,axisRange,isSecondary,@@ -655,29 +651,14 @@ export function MetricRowGroup({const scale = useAxisScale(axisRange, VIEW_BOX_WIDTH, SVG_EDGE_MARGIN)- const { reportExperimentTimeseriesViewed, retryPrimaryMetric, retrySecondaryMetric, refreshExperimentResults } =- useActions(experimentLogic)+ const { reportExperimentTimeseriesViewed, refreshExperimentResults } = useActions(experimentLogic)const { variants } = useValues(experimentLogic)- const { featureFlags } = useValues(featureFlagLogic)const { isRecalculating, metricRetries } = useValues(experimentMetricsLogic({ experiment }))const { triggerRecalculation } = useActions(experimentMetricsLogic({ experiment }))- /**- * On the recalculation flow, retrying a single metric re-runs the whole recalculation (plus exposures)- * as a manual_retry: the run reuses the latest window, so metrics with rows load from cache and only- * the failed ones recompute. The legacy flow retries the single metric in place.- */const handleRetry = (): void => {- if (featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- triggerRecalculation('manual_retry')- refreshExperimentResults(true, 'manual')- return- }- if (isSecondary) {- retrySecondaryMetric(metricIndex)- } else {- retryPrimaryMetric(metricIndex)- }+ triggerRecalculation('manual_retry')+ refreshExperimentResults(true, 'manual')}// Build query for debugger linkdiff --git a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsxindex 6d0e68df81ea..6a4b382b1133 100644--- a/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/Metrics.tsx@@ -3,9 +3,7 @@ import { useValues } from 'kea'import { IconInfo } from '@posthog/icons'import { Tooltip } from '@posthog/lemon-ui'-import { FEATURE_FLAGS } from 'lib/constants'import { IconAreaChart } from 'lib/lemon-ui/icons'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { ExperimentMetric } from '~/queries/schema/schema-general'import { experimentLogic } from '~/scenes/experiments/experimentLogic'@@ -34,39 +32,28 @@ export function Metrics({ isSecondary }: { isSecondary?: boolean }): JSX.Element}function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; isSecondary?: boolean }): JSX.Element {- const {- getInsightType,- orderedPrimaryMetricsWithResults,- orderedSecondaryMetricsWithResults,- hasMinimumExposureForResults,- } = useValues(experimentLogic)+ const { getInsightType, hasMinimumExposureForResults } = useValues(experimentLogic)const {primaryMetricsResults,primaryMetricsResultsErrors,secondaryMetricsResults,secondaryMetricsResultsErrors,} = useValues(experimentMetricsLogic({ experiment }))- const { featureFlags } = useValues(featureFlagLogic)- const recalculationFlow = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]const type = isSecondary ? 'secondary' : 'primary'- const metricsWithResults = recalculationFlow- ? metricResults(experiment)(- isSecondary ? secondaryMetricsResults : primaryMetricsResults,- isSecondary ? secondaryMetricsResultsErrors : primaryMetricsResultsErrors,- type- )- : isSecondary- ? orderedSecondaryMetricsWithResults- : orderedPrimaryMetricsWithResults+ const metricsWithResults = metricResults(experiment)(+ isSecondary ? secondaryMetricsResults : primaryMetricsResults,+ isSecondary ? secondaryMetricsResultsErrors : primaryMetricsResultsErrors,+ type+ )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+ // A single primary metric with a result shows its details inline under the table.+ const detailResult = metrics.length === 1 && hasMinimumExposureForResults && !isSecondary ? results[0] : undefinedconst hasSomeResults =results?.some((result) => result?.variant_results && result.variant_results.length > 0) &&hasMinimumExposureForResults@@ -102,13 +89,12 @@ function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; i</div></div>{metrics.length > 0 ? (- showResultDetails ? (+ detailResult ? (<div className="rounded-md border bg-surface-primary overflow-hidden divide-y divide-border"><MetricsTablemetrics={metrics}results={results}errors={errors}- metricIndexes={metricIndexes}isSecondary={!!isSecondary}getInsightType={getInsightType}showDetailsModal={false}@@ -116,7 +102,7 @@ function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; i/><ResultDetailsmetric={metrics[0] as ExperimentMetric}- result={results[0]}+ result={detailResult}experiment={experiment}embedded/>@@ -126,7 +112,6 @@ function MetricsContent({ experiment, isSecondary }: { experiment: Experiment; imetrics={metrics}results={results}errors={errors}- metricIndexes={metricIndexes}isSecondary={!!isSecondary}getInsightType={getInsightType}/>diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsxindex a254eeee2faf..2db2defb4066 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx@@ -39,9 +39,8 @@ const sectionHasRecalculatingMetric =interface MetricsTableProps {metrics: ExperimentMetric[]- results: NewExperimentQueryResponse[]+ results: (NewExperimentQueryResponse | undefined)[]errors: any[]- metricIndexes: number[]isSecondary: booleangetInsightType: (metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery) => InsightTypeshowDetailsModal?: boolean@@ -53,7 +52,6 @@ export function MetricsTable({metrics,results,errors,- metricIndexes,isSecondary,getInsightType,showDetailsModal = true,@@ -126,7 +124,7 @@ export function MetricsTable({// Calculate shared axisRange across all metricslet hasBreakdowns = false- const allIntervalValues = results.flatMap((result: NewExperimentQueryResponse) => {+ const allIntervalValues = results.flatMap((result: NewExperimentQueryResponse | undefined) => {const allVariants: ExperimentVariantResult[] = []// Include main variant results@@ -199,9 +197,8 @@ export function MetricsTable({/><SortableContext items={orderedUuids} strategy={verticalListSortingStrategy}>{metrics.map((metric, index) => {- const result = results[index]+ const result = results[index] ?? nullconst error = errors[index]- const metricIndex = metricIndexes[index]const isLoading = !result && !error && isLaunched(experiment)@@ -220,7 +217,6 @@ export function MetricsTable({result={result}experiment={experiment}metricType={getInsightType(metric)}- metricIndex={metricIndex}displayOrder={index}axisRange={axisRange}isSecondary={isSecondary}diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsxindex 4adef7139cd2..0c37bc7e5fc6 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx@@ -7,7 +7,6 @@ import { LemonButton, LemonDialog, LemonDropdown, LemonMenu, LemonTag, Tooltip }import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { Spinner } from 'lib/lemon-ui/Spinner'import { experimentLogic, getSectionMetricUuids } from 'scenes/experiments/experimentLogic'import { experimentMetricsLogic } from 'scenes/experiments/experimentMetricsLogic'@@ -246,15 +245,13 @@ export const MetricHeader = ({if (!metricUuid) {return}- // Flips shared-metric links, prunes the ordering arrays and realigns existing- // results in one update.+moveMetricsBetweenSections(isPrimaryMetric === false, sectionUuids, [], [metricUuid])}- const recalculationEnabled = useFeatureFlag('EXPERIMENTS_METRICS_RECALCULATION')const { isMetricRecalculating, metricRetries } = useValues(experimentMetricsLogic({ experiment }))- const showRecalculatingTag = recalculationEnabled && isMetricRecalculating(metric.uuid)- const metricRetry = recalculationEnabled && metric.uuid ? metricRetries[metric.uuid] : undefined+ const showRecalculatingTag = isMetricRecalculating(metric.uuid)+ const metricRetry = metric.uuid ? metricRetries[metric.uuid] : undefinedreturn (// The handle and the order number are their own columns, so the title and the tags below itdiff --git a/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsxindex 836e2b77ed2a..52b1d0278079 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx@@ -15,8 +15,7 @@ import { Experiment } from '~/types'/*** Status line for an in-flight recalculation. Renders only while a run is actually executing* (`cold` / `refreshing`); loading-from-latest and terminal states show nothing — the metric rows- * carry their own loading and error affordances. Only rendered behind- * EXPERIMENTS_METRICS_RECALCULATION (see ExperimentView).+ * carry their own loading and error affordances. ExperimentView renders it once the experiment has metrics.*/export function RecalculationStatus({ experiment }: { experiment: Experiment }): JSX.Element | null {const { recalculationDisplayState, currentRecalculation, liveRowsProgress, metricRetries, nextRetryAt } = useValues(diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.tsindex 60e3d1a55fef..2c736f095633 100644--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts@@ -2,9 +2,7 @@ import { api } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'-import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -57,26 +55,44 @@ const experiment = {version: 3,} as unknown as Experiment-const metricResultsWithBaseline = [- {- metric_uuid: METRIC_UUID,- baseline: { key: 'control', number_of_samples: 600, sum: 120, sum_squares: 48 },- variant_results: [{ key: 'test', number_of_samples: 600, sum: 130, sum_squares: 52 }],- },-] as any[]+const metricResultWithBaseline = {+ metric_uuid: METRIC_UUID,+ baseline: { key: 'control', number_of_samples: 600, sum: 120, sum_squares: 48 },+ variant_results: [{ key: 'test', number_of_samples: 600, sum: 130, sum_squares: 52 }],+}++// The latest completed run covers the one primary metric, so the metrics logic applies the baseline on mount.+const latestRecalculation = {+ id: 'recalc-1',+ experiment_id: EXPERIMENT_ID,+ status: 'completed',+ trigger: 'manual',+ total_metrics: 1,+ completed_metrics: 1,+ failed_metrics: 0,+ metric_errors: {},+ created_at: new Date().toISOString(),+ started_at: new Date().toISOString(),+ completed_at: new Date().toISOString(),+ query_to: new Date().toISOString(),+ result_source: 'recalculation',+ results: [{ metric_uuid: METRIC_UUID, status: 'completed', result: metricResultWithBaseline, error_message: null }],+}describe('runningTimeLogic', () => {let logic: ReturnType<typeof runningTimeLogic.build>let experimentLogicInstance: ReturnType<typeof experimentLogic.build>+ let metricsLogicInstance: ReturnType<typeof experimentMetricsLogic.build>let getSpy: jest.SpyInstance | undefined- beforeEach(() => {+ beforeEach(async () => {useMocks({get: {'/api/projects/:team/experiments': { count: 0, next: null, previous: null, results: [] },'/api/projects/:team/experiment_holdouts': { count: 0, next: null, previous: null, results: [] },'/api/projects/:team/experiment_saved_metrics': { count: 0, next: null, previous: null, results: [] },'/api/projects/:team/experiments/:id': experiment,+ '/api/projects/:team/experiments/:id/metrics_recalculation/latest/': latestRecalculation,},})initKeaTests()@@ -89,13 +105,16 @@ describe('runningTimeLogic', () => {experimentLogicInstance.mount()experimentLogicInstance.actions.setExperiment(experiment)experimentLogicInstance.actions.setUnmodifiedExperiment(experiment)- experimentLogicInstance.actions.setPrimaryMetricsResults(metricResultsWithBaseline)+ metricsLogicInstance = experimentMetricsLogic({ experiment })+ metricsLogicInstance.mount()+ await expectLogic(metricsLogicInstance).toDispatchActions(['setCurrentRecalculation'])})afterEach(() => {getSpy?.mockRestore()getSpy = undefinedlogic?.unmount()+ metricsLogicInstance?.unmount()experimentLogicInstance?.unmount()})@@ -228,24 +247,23 @@ describe('runningTimeLogic', () => {expect(logic.values.isCalculating).toBe(false)})- it('follows the recalculation loading state when the recalculation flag is on', async () => {- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,+ it('follows the recalculation loading state', async () => {+ calculateRunningTimeMock.mockResolvedValue({+ recommended_sample_size: 2000,+ recommended_running_time_days: 20,})- const metricsLogicInstance = experimentMetricsLogic({ experiment })- metricsLogicInstance.mount()logic = runningTimeLogic({ experiment })logic.mount()+ // The baseline fires the automatic estimate on mount; let it settle so only the recalculation state moves.+ await expectLogic(logic).toDispatchActions(['loadAutomaticCalculationSuccess']).toFinishAllListeners()+ expect(logic.values.isCalculating).toBe(false)metricsLogicInstance.actions.setRecalculationLoading(true)await expectLogic(logic).toMatchValues({ isCalculating: true })metricsLogicInstance.actions.setRecalculationLoading(false)await expectLogic(logic).toMatchValues({ isCalculating: false })-- metricsLogicInstance.unmount()})})})diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.tsindex 732637bde33d..e6ab71c5e78f 100644--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts@@ -3,9 +3,7 @@ import { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'import api from 'lib/api'-import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { objectsEqual } from 'lib/utils/objects'import { experimentsConfigLogic } from '~/scenes/settings/environment/experimentsConfigLogic'@@ -18,17 +16,12 @@ import type {RunningTimeCalculationResultApi,} from 'products/experiments/frontend/generated/api.schemas'-import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'-import type { CachedNewExperimentQueryResponse, ExperimentMetricUnion } from '../../../queries/schema/schema-general'+import type { CachedNewExperimentQueryResponse } from '../../../queries/schema/schema-general'import { experimentLogic, saveExperimentUpdate } from '../experimentLogic'import { experimentMetricsLogic } from '../experimentMetricsLogic'import { modalsLogic } from '../modalsLogic'-import {- getFlagVariants,- getOrderedMetricsWithResults,- isExperimentConflictError,- toConcurrencyPayload,-} from '../utils'+import { getFlagVariants, metricResults, isExperimentConflictError, toConcurrencyPayload } from '../utils'+import type { MetricWithResult } from '../utils'import {ManualCalculatorMetricType,baselineStatsFromResults,@@ -60,20 +53,11 @@ export interface ManualPreview {export interface runningTimeLogicValues {currentProjectId: number | null // experimentLogicexperiment: Experiment // experimentLogic- orderedPrimaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[] // experimentLogic- primaryMetricsResultsLoading: boolean // experimentLogicunmodifiedExperiment: Experiment | null // experimentLogicisRecalculating: boolean // experimentMetricsLogic- recalcPrimaryMetricsResults: CachedNewExperimentQueryResponse[] // experimentMetricsLogic- recalcPrimaryMetricsResultsErrors: (unknown | null)[] // experimentMetricsLogic+ primaryMetricsResults: CachedNewExperimentQueryResponse[] // experimentMetricsLogic+ primaryMetricsResultsErrors: (unknown | null)[] // experimentMetricsLogicdefaultMinimumDetectableEffect: number // experimentsConfigLogic- featureFlags: FeatureFlagsSet // featureFlagLogicisRunningTimeConfigModalOpen: boolean // modalsLogicautomaticCalculation: RunningTimeCalculationResultApi | nullautomaticCalculationInput: RunningTimeCalculationInputApi | null@@ -92,13 +76,7 @@ export interface runningTimeLogicValues {manualPreviewInput: RunningTimeCalculationInputApi | nullmanualPreviewLoading: booleanmde: number- metricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]+ metricsWithResults: MetricWithResult[]mode: RunningTimeConfig['mode']numberOfVariants: numberremainingDays: number | null@@ -191,41 +169,13 @@ export interface runningTimeLogicMeta {mode: (config: RunningTimeConfig) => RunningTimeConfig['mode']metricsWithResults: (experiment: Experiment,- featureFlags: FeatureFlagsSet,- orderedPrimaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[],- recalcPrimaryMetricsResults: CachedNewExperimentQueryResponse[],- recalcPrimaryMetricsResultsErrors: unknown[]- ) => {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- currentExposures: (- metricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- ) => number | null+ primaryMetricsResults: CachedNewExperimentQueryResponse[],+ primaryMetricsResultsErrors: unknown[]+ ) => MetricWithResult[]+ currentExposures: (metricsWithResults: MetricWithResult[]) => number | nullautomaticCalculationInput: (mode: 'automatic' | 'manual',- metricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[],+ metricsWithResults: MetricWithResult[],numberOfVariants: number,mde: number) => RunningTimeCalculationInputApi | null@@ -253,8 +203,6 @@ export interface runningTimeLogicMeta {isComplete: (currentExposures: number | null, targetSampleSize: number | null) => booleanisCalculating: (isManualMode: boolean,- featureFlags: FeatureFlagsSet,- primaryMetricsResultsLoading: boolean,isRecalculating: boolean,automaticCalculationLoading: boolean) => boolean@@ -282,26 +230,13 @@ export const runningTimeLogic = kea<runningTimeLogicType>([return {values: [experimentLogic({ experimentId }),- [- 'experiment',- 'unmodifiedExperiment',- 'orderedPrimaryMetricsWithResults',- 'primaryMetricsResultsLoading',- 'currentProjectId',- ],- // On the recalculation flow, metric results live in experimentMetricsLogic, not experimentLogic.+ ['experiment', 'unmodifiedExperiment', 'currentProjectId'],experimentMetricsLogic({ experiment: props.experiment }),- [- 'primaryMetricsResults as recalcPrimaryMetricsResults',- 'primaryMetricsResultsErrors as recalcPrimaryMetricsResultsErrors',- 'isRecalculating',- ],+ ['primaryMetricsResults', 'primaryMetricsResultsErrors', 'isRecalculating'],modalsLogic,['isRunningTimeConfigModalOpen'],experimentsConfigLogic,['defaultMinimumDetectableEffect'],- featureFlagLogic,- ['featureFlags'],],actions: [experimentLogic({ experimentId }),@@ -413,34 +348,14 @@ export const runningTimeLogic = kea<runningTimeLogicType>([mde: [(s) => [s.config], (config: RunningTimeConfig): number => config.mde],mode: [(s) => [s.config], (config: RunningTimeConfig): RunningTimeConfig['mode'] => config.mode],- // Legacy flow exposes metric results via experimentLogic; the recalculation flow exposes them- // via experimentMetricsLogic. Pick whichever is active so automatic mode always has a baseline.+ // Primary metrics zipped with their results, so automatic mode always has a baseline to read.metricsWithResults: [- (s) => [- s.experiment,- s.featureFlags,- s.orderedPrimaryMetricsWithResults,- s.recalcPrimaryMetricsResults,- s.recalcPrimaryMetricsResultsErrors,- ],+ (s) => [s.experiment, s.primaryMetricsResults, s.primaryMetricsResultsErrors],(experiment: Experiment,- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,- legacyMetricsWithResults: {- displayIndex: number- error: any- metric: import('../../../queries/schema').ExperimentMetricUnion- metricIndex: number- result: any- }[],- recalcResults: import('../../../queries/schema').CachedNewExperimentQueryResponse[],- recalcErrors: (unknown | null)[]- ) => {- if (experiment && featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- return getOrderedMetricsWithResults(experiment, recalcResults, recalcErrors, [], [], false)- }- return legacyMetricsWithResults- },+ results: import('../../../queries/schema').CachedNewExperimentQueryResponse[],+ errors: (unknown | null)[]+ ) => (experiment ? metricResults(experiment)(results, errors, 'primary') : []),],currentExposures: [@@ -586,29 +501,12 @@ export const runningTimeLogic = kea<runningTimeLogicType>([// instead of flashing a pending state during the gap between the two. Manual mode has no async// estimate to wait on, so it never counts as calculating.isCalculating: [- (s) => [- s.isManualMode,- s.featureFlags,- s.primaryMetricsResultsLoading,- s.isRecalculating,- s.automaticCalculationLoading,- ],- (- isManualMode: boolean,- featureFlags: FeatureFlagsSet,- primaryMetricsResultsLoading: boolean,- isRecalculating: boolean,- automaticCalculationLoading: boolean- ): boolean => {+ (s) => [s.isManualMode, s.isRecalculating, s.automaticCalculationLoading],+ (isManualMode: boolean, isRecalculating: boolean, automaticCalculationLoading: boolean): boolean => {if (isManualMode) {return false}- // The recalculation flow sources results from experimentMetricsLogic, the legacy flow from- // experimentLogic. Watch whichever is active so neither path flashes a pending state on load.- const metricsLoading = featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]- ? isRecalculating- : primaryMetricsResultsLoading- return metricsLoading || automaticCalculationLoading+ return isRecalculating || automaticCalculationLoading},],manualFormPreview: [diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 7522141e37d4..c7d3ce051445 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -3,24 +3,15 @@ import { api } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'-import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { userLogic } from 'scenes/userLogic'import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'-import experimentMetricResultsErrorJson from '~/mocks/fixtures/api/experiments/_experiment_metric_results_error.json'import experimentMetricResultsSuccessJson from '~/mocks/fixtures/api/experiments/_experiment_metric_results_success.json'import { useMocks } from '~/mocks/jest'import { tagsModel } from '~/models/tagsModel'-import {- Breakdown,- CachedNewExperimentQueryResponse,- ExperimentMetric,- ExperimentMetricType,- NodeKind,-} from '~/queries/schema/schema-general'+import { Breakdown, ExperimentMetric, ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {BreakdownAttributionType,@@ -122,255 +113,12 @@ describe('experimentLogic', () => {},})initKeaTests()- // The jest posthog-js mock never fires onFeatureFlags, so receivedFeatureFlags stays false and- // refreshExperimentResults would defer forever. Simulate the real flag arrival so refreshes run.- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([], {})logic = experimentLogic()logic.mount()await expectLogic(userLogic).toFinishAllListeners()})- describe('loadPrimaryMetricsResults', () => {- it('given a refresh, loads the metric results', async () => {- logic.actions.setExperiment(experiment)-- useMocks({- post: {- '/api/environments/:team/query/:kind': (() => {- let callCount = 0- return () => {- callCount++- return [- 200,- {- cache_key: 'cache_key',- query_status:- callCount === 1- ? experimentMetricResultsSuccessJson.query_status- : experimentMetricResultsErrorJson.query_status,- },- ]- }- })(),- },- get: {- '/api/environments/:team/query/:id': (() => {- let callCount = 0- return () => {- callCount++- return callCount === 1- ? [200, experimentMetricResultsSuccessJson]- : [400, experimentMetricResultsErrorJson]- }- })(),- },- })-- const promise = logic.asyncActions.loadPrimaryMetricsResults(true)-- await expectLogic(logic).toDispatchActions(['setPrimaryMetricsResultsLoading']).toMatchValues({- primaryMetricsResultsLoading: true,- primaryMetricsResultsErrors: [],- })-- await promise-- await expectLogic(logic)- .toDispatchActions(['setPrimaryMetricsResultsLoading'])- .toMatchValues({- primaryMetricsResultsLoading: false,- primaryMetricsResultsErrors: [- null,- {- detail: {- 'no-control-variant': true,- 'no-test-variant': true,- 'no-exposures': false,- },- hasDiagnostics: true,- statusCode: 400,- code: 'no-results',- queryId: expect.any(String),- timestamp: expect.any(Number),- },- ],- })- })- })-- describe('loadSecondaryMetricsResults', () => {- it('given a refresh, loads the secondary metric results', async () => {- logic.actions.setExperiment(experiment)-- useMocks({- post: {- '/api/environments/:team/query/:kind': (() => {- let callCount = 0- return () => {- callCount++- return [- 200,- {- cache_key: 'cache_key',- query_status:- callCount === 2- ? experimentMetricResultsSuccessJson.query_status- : experimentMetricResultsErrorJson.query_status,- },- ]- }- })(),- },- get: {- '/api/environments/:team/query/:id': (() => {- let callCount = 0- return () => {- callCount++- return callCount === 2- ? [200, experimentMetricResultsSuccessJson]- : [400, experimentMetricResultsErrorJson]- }- })(),- },- })-- const promise = logic.asyncActions.loadSecondaryMetricsResults(true)-- await expectLogic(logic).toDispatchActions(['setSecondaryMetricsResultsLoading']).toMatchValues({- secondaryMetricsResultsLoading: true,- secondaryMetricsResultsErrors: [],- })-- await promise-- await expectLogic(logic)- .toDispatchActions(['setSecondaryMetricsResultsLoading'])- .toMatchValues({- secondaryMetricsResultsLoading: false,- secondaryMetricsResultsErrors: [- {- detail: {- 'no-control-variant': true,- 'no-test-variant': true,- 'no-exposures': false,- },- hasDiagnostics: true,- statusCode: 400,- code: 'no-results',- queryId: expect.any(String),- timestamp: expect.any(Number),- },- null,- ],- })- })- })-describe('refreshExperimentResults', () => {- it('waits for metric refreshes to complete before resolving', async () => {- logic.actions.setExperiment(experiment)-- useMocks({- post: {- '/api/environments/:team/query': async () => {- await new Promise((resolve) => setTimeout(resolve, 30))- return [- 200,- {- cache_key: 'cache_key',- query_status: experimentMetricResultsSuccessJson.query_status,- },- ]- },- },- get: {- '/api/environments/:team/query/:id': async () => {- await new Promise((resolve) => setTimeout(resolve, 30))- return [200, experimentMetricResultsSuccessJson]- },- },- })-- await logic.asyncActions.refreshExperimentResults(true, 'manual')-- // Verify loading states are properly reset after refresh completes- expect(logic.values.primaryMetricsResultsLoading).toBe(false)- expect(logic.values.secondaryMetricsResultsLoading).toBe(false)- })-- it('defers the refresh until feature flags arrive, then replays it once', async () => {- // Reinitialize kea so flags start unresolved (receivedFeatureFlags false). The outer beforeEach- // marks flags received; here a refresh must not choose a branch yet, since reading the flag as- // off would run the failing legacy loaders.- logic.unmount()- initKeaTests()- logic = experimentLogic()- logic.mount()- await expectLogic(userLogic).toFinishAllListeners()-- logic.actions.setExperiment(experiment)-- // The refresh is deferred: it never starts while flags are unresolved.- await expectLogic(logic, () => {- logic.actions.refreshExperimentResults(true, 'manual')- }).toNotHaveDispatchedActions(['markRefreshStarted'])-- // Once flags arrive, the deferred refresh replays with its original arguments.- await expectLogic(logic, () => {- featureFlagLogic.actions.setFeatureFlags([], {})- }).toDispatchActions([- (action) =>- action.type === logic.actionTypes.refreshExperimentResults &&- action.payload.forceRefresh === true &&- action.payload.triggeredBy === 'manual',- 'markRefreshStarted',- ])- })-- it('re-runs the refresh when a later flag update contradicts the value it used', async () => {- // The outer beforeEach delivered an empty flag set: flags count as received, but the- // recalculation flag reads off, like the bootstrap set of a page load.- logic.actions.setExperiment(experiment)- useMocks({- post: {- '/api/environments/:team/query': () => [- 200,- { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },- ],- },- get: {- '/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],- },- })- // The expectLogic wrapper consumes this refresh's actions from the recorded history, so the- // assertions below match only the replayed refresh, not this original one.- await expectLogic(logic, async () => {- await logic.asyncActions.refreshExperimentResults(true, 'manual')- }).toDispatchActions(['refreshExperimentResults', 'markRefreshStarted', 'markRefreshFinished'])-- // The real flag response lands with the flag on. The refresh must re-run with its original- // arguments, or the page keeps whatever the wrong branch loaded.- await expectLogic(logic, () => {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,- })- }).toDispatchActions([- (action) =>- action.type === logic.actionTypes.refreshExperimentResults &&- action.payload.forceRefresh === true &&- action.payload.triggeredBy === 'manual',- 'markRefreshStarted',- ])-- // A repeated update with the same value must not re-run the refresh.- await expectLogic(logic, () => {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,- })- }).toNotHaveDispatchedActions(['refreshExperimentResults'])- })-const unevenExposures = {timeseries: [{ variant: 'control' }, { variant: 'test' }, { variant: '$multiple' }],total_exposures: { control: 600, test: 350, $multiple: 50 },@@ -490,46 +238,37 @@ describe('experimentLogic', () => {})describe('updateExperimentMetrics', () => {- it('keeps existing results when saving the metric definitions fails', async () => {- const existingResult = experimentMetricResultsSuccessJson.query_status- .results as unknown as CachedNewExperimentQueryResponse-+ it('keeps the existing results when saving the metric definitions fails', async () => {logic.actions.setExperiment(experiment)- logic.actions.setPrimaryMetricsResults([existingResult])- logic.actions.setPrimaryMetricsResultsErrors([null])jest.spyOn(api, 'update').mockRejectedValueOnce(new Error('network down'))await expectLogic(logic, () => logic.actions.updateExperimentMetrics())- .toDispatchActions(['updateExperimentFailure']).toFinishAllListeners()-- expect(logic.values.primaryMetricsResults).toEqual([existingResult])- expect(logic.values.primaryMetricsResultsErrors).toEqual([null])+ .toNotHaveDispatchedActions([+ experimentMetricsLogic({ experiment }).actionTypes.setPrimaryMetricsResults,+ 'refreshExperimentResults',+ ])+ .toDispatchActions(['updateExperimentFailure'])})- it('reloads cached results for the server metric list after a save conflict', async () => {- const staleResult = experimentMetricResultsSuccessJson.query_status- .results as unknown as CachedNewExperimentQueryResponse-+ it('clears the results and reloads cached ones for the server metric list after a save conflict', async () => {logic.actions.setUnmodifiedExperiment(experiment)logic.actions.setExperiment(experiment)- logic.actions.setPrimaryMetricsResults([staleResult])jest.spyOn(api, 'update').mockRejectedValueOnce({status: 409,data: { detail: 'The experiment was changed since you loaded it.', current_version: 5 },})- // Another editor removed every metric, so the stale result pairs with nothing on the server.+ // Another editor removed every metric, so the previous results pair with nothing on the server.jest.spyOn(api, 'get').mockResolvedValueOnce({ ...experiment, version: 5, metrics: [], saved_metrics: [] })await expectLogic(logic, () => logic.actions.updateExperimentMetrics()).toDispatchActions([+ experimentMetricsLogic({ experiment }).actionTypes.setPrimaryMetricsResults,(action) =>action.type === logic.actionTypes.refreshExperimentResults &&action.payload.forceRefresh === false,]).toFinishAllListeners()-- expect(logic.values.primaryMetricsResults).toEqual([])})})@@ -567,20 +306,8 @@ describe('experimentLogic', () => {],['the variant exclusion', (): void => logic.actions.setVariantExcluded('test', true)],[- 'the variant exclusion with recalculation on',- (): void => {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,- })- logic.actions.setVariantExcluded('test', true)- },- ],- [- 'a metric move while results load',- (): void => {- logic.actions.setPrimaryMetricsResultsLoading(true)- logic.actions.moveMetricsBetweenSections(true, [secondaryUuid], [], [secondaryUuid])- },+ 'a metric move',+ (): void => logic.actions.moveMetricsBetweenSections(true, [secondaryUuid], [], [secondaryUuid]),],])('%s skips the follow-up work', async (_name, dispatch) => {const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)@@ -593,8 +320,6 @@ describe('experimentLogic', () => {.toFinishAllListeners().toNotHaveDispatchedActions(['refreshExperimentResults',- 'loadPrimaryMetricsResults',- 'loadSecondaryMetricsResults','loadExposures',experimentMetricsLogic({ experiment }).actionTypes.triggerRecalculation,])@@ -1160,29 +885,19 @@ describe('experimentLogic', () => {name: 'Secondary metric',} as unknown as ExperimentMetric- const primaryMetricResult = {- baseline: { key: 'control' },- metric_uuid: 'primary-metric-uuid',- } as unknown as CachedNewExperimentQueryResponse- const otherPrimaryMetricResult = {- baseline: { key: 'control' },- metric_uuid: 'other-primary-uuid',- } as unknown as CachedNewExperimentQueryResponse- const thirdPrimaryMetricResult = {- baseline: { key: 'control' },- metric_uuid: 'third-primary-uuid',- } as unknown as CachedNewExperimentQueryResponse- const secondaryMetricResult = {- baseline: { key: 'control' },- metric_uuid: 'secondary-metric-uuid',- } as unknown as CachedNewExperimentQueryResponse+ // Moving a metric is metric-scoped: the recompute reuses the window so unchanged metrics stay cached. It+ // follows the save request itself, so it can land before the loader reports updateExperimentSuccess.+ const recomputesWithCurrentWindow = (action: any): boolean =>+ action.type === logic.actionTypes.refreshExperimentResults &&+ action.payload.forceRefresh === true &&+ action.payload.triggeredBy === 'metric_config_change'beforeEach(() => {jest.spyOn(api, 'update')api.update.mockClear()})- it('moves an inline metric to secondary and reuses existing results', async () => {+ it('moves an inline metric to secondary and recomputes results against the new layout', async () => {const testExperiment = {...experiment,saved_metrics: [],@@ -1192,8 +907,6 @@ describe('experimentLogic', () => {} as unknown as Experimentlogic.actions.setExperiment(testExperiment)- logic.actions.setPrimaryMetricsResults([primaryMetricResult, otherPrimaryMetricResult])- logic.actions.setSecondaryMetricsResults([secondaryMetricResult])api.update.mockResolvedValue({...testExperiment,metrics: [otherPrimaryMetric],@@ -1209,15 +922,9 @@ describe('experimentLogic', () => {['primary-metric-uuid'])})+ .toDispatchActions([recomputesWithCurrentWindow]).toFinishAllListeners()- .toNotHaveDispatchedActions([- 'refreshExperimentResults',- 'loadPrimaryMetricsResults',- 'loadSecondaryMetricsResults',- 'loadExperiment',- 'retryPrimaryMetric',- 'retrySecondaryMetric',- ])+ .toNotHaveDispatchedActions(['loadExperiment'])expect(api.update).toHaveBeenCalledWith(expect.stringContaining('/experiments/'),@@ -1231,10 +938,6 @@ describe('experimentLogic', () => {expect.stringContaining('/experiments/'),expect.not.objectContaining({ saved_metrics_ids: expect.anything() }))- expect(logic.values.primaryMetricsResults).toEqual([otherPrimaryMetricResult])- expect(logic.values.secondaryMetricsResults).toEqual([secondaryMetricResult, primaryMetricResult])- expect(logic.values.primaryMetricsResultsErrors).toEqual([null])- expect(logic.values.secondaryMetricsResultsErrors).toEqual([null, null])})it('applies a combined move and removal in a single update', async () => {@@ -1247,11 +950,6 @@ describe('experimentLogic', () => {} as unknown as Experimentlogic.actions.setExperiment(testExperiment)- logic.actions.setPrimaryMetricsResults([- primaryMetricResult,- otherPrimaryMetricResult,- thirdPrimaryMetricResult,- ])api.update.mockResolvedValue({...testExperiment,metrics: [thirdPrimaryMetric],@@ -1267,9 +965,10 @@ describe('experimentLogic', () => {['primary-metric-uuid'])})+ .toDispatchActions([recomputesWithCurrentWindow]).toFinishAllListeners()- .toNotHaveDispatchedActions(['refreshExperimentResults'])+ expect(api.update).toHaveBeenCalledTimes(1)expect(api.update).toHaveBeenCalledWith(expect.stringContaining('/experiments/'),expect.objectContaining({@@ -1278,8 +977,6 @@ describe('experimentLogic', () => {primary_metrics_ordered_uuids: ['third-primary-uuid'],}))- expect(logic.values.primaryMetricsResults).toEqual([thirdPrimaryMetricResult])- expect(logic.values.secondaryMetricsResults).toEqual([primaryMetricResult])})it('moves a shared metric by flipping its saved-metric link type', async () => {@@ -1298,10 +995,6 @@ describe('experimentLogic', () => {metadata: { type: 'primary' },created_at: '2024-01-01T00:00:00Z',} satisfies ExperimentSavedMetric- const sharedMetricResult = {- baseline: { key: 'control' },- metric_uuid: 'shared-metric-uuid',- } as unknown as CachedNewExperimentQueryResponseconst testExperiment = {...experiment,metrics: [],@@ -1311,7 +1004,6 @@ describe('experimentLogic', () => {} as unknown as Experimentlogic.actions.setExperiment(testExperiment)- logic.actions.setPrimaryMetricsResults([sharedMetricResult])api.update.mockResolvedValue({...testExperiment,saved_metrics: [{ ...sharedSavedMetric, metadata: { type: 'secondary' } }],@@ -1321,8 +1013,9 @@ describe('experimentLogic', () => {await expectLogic(logic, () => {logic.actions.moveMetricsBetweenSections(false, ['shared-metric-uuid'], [], ['shared-metric-uuid'])})+ .toDispatchActions([recomputesWithCurrentWindow]).toFinishAllListeners()- .toNotHaveDispatchedActions(['refreshExperimentResults', 'loadExperiment'])+ .toNotHaveDispatchedActions(['loadExperiment'])expect(api.update).toHaveBeenCalledWith(expect.stringContaining('/experiments/'),@@ -1330,122 +1023,9 @@ describe('experimentLogic', () => {saved_metrics_ids: [{ id: sharedMetricId, metadata: { type: 'secondary' } }],}))- expect(logic.values.primaryMetricsResults).toEqual([])- expect(logic.values.secondaryMetricsResults).toEqual([sharedMetricResult])})- it('loads only the moved metric when it has no result yet', async () => {- const fetchedResult = { baseline: { key: 'control' }, variant_results: [] }- useMocks({- post: {- '/api/environments/:team/query/:kind': () => [- 200,- {- cache_key: 'cache_key',- query_status: {- ...experimentMetricResultsSuccessJson.query_status,- results: fetchedResult,- },- },- ],- },- get: {- '/api/environments/:team/query/:id': () => [- 200,- {- query_status: {- ...experimentMetricResultsSuccessJson.query_status,- results: fetchedResult,- },- },- ],- },- })-- const testExperiment = {- ...experiment,- saved_metrics: [],- metrics: [],- metrics_secondary: [secondaryMetric],- secondary_metrics_ordered_uuids: ['secondary-metric-uuid'],- } as unknown as Experiment-- logic.actions.setExperiment(testExperiment)- api.update.mockResolvedValue({- ...testExperiment,- metrics: [secondaryMetric],- metrics_secondary: [],- secondary_metrics_ordered_uuids: [],- })-- await expectLogic(logic, () => {- logic.actions.moveMetricsBetweenSections(true, ['secondary-metric-uuid'], [], ['secondary-metric-uuid'])- })- .toDispatchActionsInAnyOrder(['updateExperimentSuccess', 'retryPrimaryMetric'])- .toFinishAllListeners()- .toNotHaveDispatchedActions(['refreshExperimentResults', 'loadPrimaryMetricsResults'])-- expect(logic.values.primaryMetricsResults).toEqual([expect.objectContaining(fetchedResult)])- })-- it.each([- ['are already loading', true],- ['start loading while the save waits in the queue', false],- ])('falls back to a full refresh when results %s', async (_name, loadingBeforeMove) => {- useMocks({- post: {- '/api/environments/:team/query/:kind': () => [- 200,- { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },- ],- },- get: {- '/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],- },- })-- const testExperiment = {- ...experiment,- saved_metrics: [],- metrics: [primaryMetric],- metrics_secondary: [],- primary_metrics_ordered_uuids: ['primary-metric-uuid'],- } as unknown as Experiment-- logic.actions.setExperiment(testExperiment)- if (loadingBeforeMove) {- logic.actions.setPrimaryMetricsResultsLoading(true)- }- let finishSave: (saved: Experiment) => void = () => {}- api.update.mockReturnValueOnce(- new Promise<Experiment>((resolve) => {- finishSave = resolve- })- )-- logic.actions.moveMetricsBetweenSections(false, ['primary-metric-uuid'], [], ['primary-metric-uuid'])- if (!loadingBeforeMove) {- logic.actions.setPrimaryMetricsResultsLoading(true)- }- finishSave({- ...testExperiment,- metrics: [],- metrics_secondary: [primaryMetric],- primary_metrics_ordered_uuids: [],- } as unknown as Experiment)-- await expectLogic(logic)- .toDispatchActions([- 'updateExperiment',- // Moving a metric is metric-scoped: reuse the window so unchanged metrics stay cached.- (action) =>- action.type === logic.actionTypes.refreshExperimentResults &&- action.payload.triggeredBy === 'metric_config_change',- ])- .toFinishAllListeners()- })-- it('realigns results to the server metric lists after a save conflict', async () => {+ it('recomputes cached results for the server metric lists after a save conflict', async () => {const testExperiment = {...experiment,saved_metrics: [],@@ -1456,13 +1036,12 @@ describe('experimentLogic', () => {logic.actions.setUnmodifiedExperiment(testExperiment)logic.actions.setExperiment(testExperiment)- logic.actions.setPrimaryMetricsResults([primaryMetricResult, otherPrimaryMetricResult])- logic.actions.setSecondaryMetricsResults([secondaryMetricResult])api.update.mockRejectedValueOnce({status: 409,data: { detail: 'The experiment was changed since you loaded it.', current_version: 5 },})- // Another editor swapped the two primary metrics, so each result now belongs at the other position.+ // Another editor swapped the two primary metrics, and this move did not save. The loader swaps+ // the server's lists in before it reports the failure, so the recompute lands first.jest.spyOn(api, 'get').mockResolvedValueOnce({...testExperiment,version: 5,@@ -1477,12 +1056,16 @@ describe('experimentLogic', () => {['primary-metric-uuid'])})- .toDispatchActions(['updateExperimentFailure'])+ .toDispatchActions([+ (action) =>+ action.type === logic.actionTypes.refreshExperimentResults &&+ action.payload.forceRefresh === false &&+ action.payload.triggeredBy === 'metric_config_change',+ 'updateExperimentFailure',+ ]).toFinishAllListeners()expect(logic.values.experiment.metrics).toEqual([otherPrimaryMetric, primaryMetric])- expect(logic.values.primaryMetricsResults).toEqual([otherPrimaryMetricResult, primaryMetricResult])- expect(logic.values.secondaryMetricsResults).toEqual([secondaryMetricResult])})})describe('tags refresh', () => {@@ -1656,55 +1239,6 @@ describe('experimentLogic', () => {expect(logic.values.experiment.saved_metrics[0].metadata.breakdowns).toEqual(expected)})- it('should include breakdowns when preparing shared metrics for loading', () => {- const testExperiment: Experiment = {- ...experiment,- saved_metrics: [- {- id: 1,- experiment: experiment.id as number,- saved_metric: 123,- name: 'Shared Metric',- query: {- uuid: 'shared-metric-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: '$pageview' },- },- metadata: {- type: 'primary',- breakdowns: [- { property: '$browser', type: 'event' } satisfies Breakdown,- { property: '$os', type: 'event' } satisfies Breakdown,- ],- },- effective_query: {- uuid: 'shared-metric-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: '$pageview' },- breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown] },- },- created_at: '2024-01-01T00:00:00Z',- } satisfies ExperimentSavedMetric,- ],- metrics: [],- primary_metrics_ordered_uuids: ['shared-metric-uuid'],- start_date: '2024-01-01',- }-- logic.actions.setExperiment(testExperiment)-- // Check that orderedPrimaryMetricsWithResults includes breakdowns- const metricsWithResults = logic.values.orderedPrimaryMetricsWithResults- expect(metricsWithResults.length).toBe(1)- const enrichedMetric = metricsWithResults[0].metric- expect(enrichedMetric.breakdownFilter?.breakdowns).toEqual([- { property: '$browser', type: 'event' },- { property: '$os', type: 'event' },- ])- })-it('should add breakdown to secondary shared metric metadata', () => {const breakdown: Breakdown = { property: '$browser', type: 'event' }const testExperiment: Experiment = {@@ -1735,56 +1269,6 @@ describe('experimentLogic', () => {expect(logic.values.experiment.saved_metrics[0].metadata.breakdowns).toEqual([breakdown])})- it('should include breakdowns when preparing secondary shared metrics for loading', () => {- const testExperiment: Experiment = {- ...experiment,- saved_metrics: [- {- id: 1,- experiment: experiment.id as number,- saved_metric: 123,- name: 'Secondary Shared Metric',- query: {- uuid: 'secondary-metric-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: '$pageview' },- },- metadata: {- type: 'secondary',- breakdowns: [- { property: '$browser', type: 'event' } satisfies Breakdown,- { property: '$os', type: 'event' } satisfies Breakdown,- ],- },- effective_query: {- uuid: 'secondary-metric-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: '$pageview' },- breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown] },- },- created_at: '2024-01-01T00:00:00Z',- } satisfies ExperimentSavedMetric,- ],- metrics: [],- metrics_secondary: [],- secondary_metrics_ordered_uuids: ['secondary-metric-uuid'],- start_date: '2024-01-01',- }-- logic.actions.setExperiment(testExperiment)-- // Check that orderedSecondaryMetricsWithResults includes breakdowns- const metricsWithResults = logic.values.orderedSecondaryMetricsWithResults- expect(metricsWithResults.length).toBe(1)- const enrichedMetric = metricsWithResults[0].metric- expect(enrichedMetric.breakdownFilter?.breakdowns).toEqual([- { property: '$browser', type: 'event' },- { property: '$os', type: 'event' },- ])- })-describe.each([{name: 'adding a breakdown',@@ -1832,7 +1316,11 @@ describe('experimentLogic', () => {noOpEdits: [],},])('$name', ({ action, change, inlineEdit, sharedEdit, event, noOpEdits }) => {- const legacyReloads = ['loadPrimaryMetricsResults', 'loadSecondaryMetricsResults']+ // The edit changes how the metric is computed, so the recompute reuses the window and recomputes it.+ const recomputesWithCurrentWindow = (dispatched: any): boolean =>+ dispatched.type === logic.actionTypes.refreshExperimentResults &&+ dispatched.payload.forceRefresh === true &&+ dispatched.payload.triggeredBy === 'metric_config_change'let captureSpy: jest.SpyInstancelet updateSpy: jest.SpyInstance@@ -1880,22 +1368,13 @@ describe('experimentLogic', () => {{ location: 'an inline secondary metric', uuid: 'inline-secondary', isPrimary: false },{ location: 'a shared primary metric', uuid: 'shared-primary', isPrimary: true },{ location: 'a shared secondary metric', uuid: 'shared-secondary', isPrimary: false },- ])('on $location saves the edit and reloads its section', async ({ uuid, isPrimary }) => {- const reload = isPrimary ? 'loadPrimaryMetricsResults' : 'loadSecondaryMetricsResults'-- // toNotHaveDispatchedActions searches only the history after the last match. The earlier tests in- // this block do not wait for their saves, so a late save can dispatch a reload into this test.- // Match the change first to skip that, and check the absent actions before matching the reload.+ ])('on $location saves the edit and recomputes its results', async ({ uuid, isPrimary }) => {await expectLogic(logic, () => {change(uuid)}).toDispatchActions([action]).toFinishAllListeners()- .toNotHaveDispatchedActions([- ...legacyReloads.filter((reloadAction) => reloadAction !== reload),- 'refreshExperimentResults',- ])- .toDispatchActions([reload])+ .toDispatchActions([recomputesWithCurrentWindow])const editInline = (metric: ExperimentMetric): ExperimentMetric =>metric.uuid === uuid ? ({ ...metric, ...inlineEdit } as ExperimentMetric) : metric@@ -1926,30 +1405,11 @@ describe('experimentLogic', () => {}).toDispatchActions([action]).toFinishAllListeners()- .toNotHaveDispatchedActions(['updateExperiment', ...legacyReloads, 'refreshExperimentResults'])+ .toNotHaveDispatchedActions(['updateExperiment', 'refreshExperimentResults'])expect(breakdownEvents()).toEqual([])})- it('refreshes results on the recalculation flow', async () => {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,- })-- await expectLogic(logic, () => {- change('inline-secondary')- })- .toDispatchActions([action])- .toFinishAllListeners()- .toNotHaveDispatchedActions(legacyReloads)- .toDispatchActions([- (dispatched) =>- dispatched.type === logic.actionTypes.refreshExperimentResults &&- dispatched.payload.forceRefresh === true &&- dispatched.payload.triggeredBy === 'metric_config_change',- ])- })-it('skips the reload when the save fails', async () => {updateSpy.mockRejectedValue(new Error('network down'))@@ -1958,7 +1418,7 @@ describe('experimentLogic', () => {}).toDispatchActions([action]).toFinishAllListeners()- .toNotHaveDispatchedActions([...legacyReloads, 'refreshExperimentResults'])+ .toNotHaveDispatchedActions(['refreshExperimentResults']).toDispatchActions(['updateExperimentFailure'])// The event reports the user action, so it fires before the save and does not wait for it.@@ -2347,19 +1807,12 @@ describe('experimentLogic', () => {keyed.mount()keyed.actions.setExperiment(runningExperiment)- // Pre-condition: experiment is running with cached metric resultsexpect(keyed.values.experiment.start_date).toBe('2026-03-17T10:00:00Z')- const stubResult = { result: 'stub' } as any- keyed.actions.setPrimaryMetricsResults([stubResult])- keyed.actions.setSecondaryMetricsResults([stubResult])- keyed.actions.setPrimaryMetricsResultsErrors([{ error: 'stub' }])- keyed.actions.setSecondaryMetricsResultsErrors([{ error: 'stub' }])- expect(keyed.values.primaryMetricsResults).toHaveLength(1)await expectLogic(keyed, () => {keyed.actions.resetRunningExperiment()})- .toDispatchActions(['resetRunningExperiment', 'setExperiment', 'clearMetricsResults'])+ .toDispatchActions(['resetRunningExperiment', 'setExperiment']).toFinishAllListeners()expect(createSpy).toHaveBeenCalledWith(expect.stringContaining(`/experiments/${experiment.id}/reset`))@@ -2369,12 +1822,6 @@ describe('experimentLogic', () => {expect(keyed.values.experiment.end_date).toBeNull()expect(keyed.values.experiment.status).toBe('draft')- // Post-condition: metric results are cleared- expect(keyed.values.primaryMetricsResults).toEqual([])- expect(keyed.values.secondaryMetricsResults).toEqual([])- expect(keyed.values.primaryMetricsResultsErrors).toEqual([])- expect(keyed.values.secondaryMetricsResultsErrors).toEqual([])-createSpy.mockRestore()keyed.unmount()})diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 996df8c16a20..f1faaba4b708 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -21,7 +21,6 @@ import api from 'lib/api'import { isApprovalRequiredError } from 'lib/api-error'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'@@ -31,7 +30,6 @@ import { objectsEqual } from 'lib/utils/objects'import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'import { billingLogic } from 'scenes/billing/billingLogic'-import { runWithLimit } from 'scenes/dashboard/dashboardUtils'import {hasMultipleVariantsActive,hasZeroRollout,@@ -52,8 +50,6 @@ import { performQuery } from '~/queries/query'import {AnyEntityNode,Breakdown,- CachedExperimentQueryResponse,- CachedNewExperimentQueryResponse,ExperimentExposureCriteria,ExperimentExposureQueryResponse,ExperimentFunnelsQuery,@@ -82,7 +78,6 @@ import {import {EXPERIMENT_MIN_EXPOSURES_FOR_RESULTS,NEW_EXPERIMENT,- NEW_EXPERIMENT_FORCE_REFRESH_AFTER_MINUTES,MetricInsightId,} from 'products/experiments/frontend/constants'import { hasEnded, isLaunched } from 'products/experiments/frontend/experimentStatus'@@ -146,14 +141,11 @@ import {type ExperimentSavedMetric,type ExperimentUpdatePayload,type ExperimentUpdateRequest,- getDisplayOrderedIndices,getExperimentVariants,- getOrderedMetricsWithResults,conflictPreservedFields,isExperimentConflictError,isLegacyExperiment,sharedMetricEffectiveQuery,- sharedMetricsToExperimentMetrics,toConcurrencyPayload,toFlagVariantsInput,withoutProjectedFlagConfig,@@ -256,47 +248,6 @@ function generateRefreshId(): string {})}-interface MetricLoadingConfig {- metrics: any[]- experimentId: Experiment['id']- refresh?: boolean- teamId?: number | null- refreshId: string- isPrimary: boolean- isRetry: boolean- metricIndexOffset: number- orderedUuids?: string[] | null- featureFlags: FeatureFlagsSet- onSetResults: (results: CachedNewExperimentQueryResponse[]) => void- onSetErrors: (errors: any[]) => void-}--interface MetricLoadingSummary {- successfulCount: number- erroredCount: number- cachedCount: number-}--function parseMetricErrorDetail(error: any): { detail: any; hasDiagnostics: boolean } {- const errorDetailText = typeof error.detail === 'string' ? error.detail : null- const errorDetailMatch = errorDetailText?.match(/\{.*\}/)-- if (!errorDetailMatch) {- return { detail: error.detail || error.message, hasDiagnostics: false }- }-- try {- return { detail: JSON.parse(errorDetailMatch[0]), hasDiagnostics: true }- } catch {- return { detail: error.detail || error.message, hasDiagnostics: false }- }-}--/**- * Positional uuid list for one section's results arrays: inline metrics first,- * then shared metrics of that type — mirroring how loadPrimaryMetricsResults /- * loadSecondaryMetricsResults build their query lists.- */export function getSectionMetricUuids(experiment: Experiment, isSecondary: boolean): (string | undefined)[] {const inlineMetrics = (isSecondary ? experiment.metrics_secondary : experiment.metrics) || []const sharedMetrics = ((experiment.saved_metrics || []) as ExperimentSavedMetric[]).filter(@@ -395,152 +346,12 @@ async function inflightUpdateOutcome(cache: Record<string, any>): Promise<'saved}}-// Max concurrent metric queries to avoid overwhelming the celery queue's-// per-team concurrency limit (10). Using runWithLimit instead of Promise.all-// prevents mass rejections and retry churn when experiments have many metrics.-const METRIC_QUERY_CONCURRENCY_LIMIT = 10--const loadMetrics = async ({- metrics,- experimentId,- refresh,- teamId,- refreshId,- isPrimary,- isRetry,- metricIndexOffset,- orderedUuids,- featureFlags,- onSetResults,- onSetErrors,-}: MetricLoadingConfig): Promise<MetricLoadingSummary> => {- const results: CachedNewExperimentQueryResponse[] = []- const currentErrors = Array.from({ length: metrics.length }).fill(null)-- let successfulCount = 0- let erroredCount = 0- let cachedCount = 0-- // Build tasks in display order so higher-priority metrics get dispatched first,- // but each task writes to its original index so the UI stays consistent.- const displayOrder = getDisplayOrderedIndices(metrics, orderedUuids)-- const tasks = displayOrder.map((originalIndex) => {- const metric = metrics[originalIndex]- return async (): Promise<void> => {- let response: any = null- const startTime = performance.now()- const metricIndex = metricIndexOffset + originalIndex- const metricKind = metric.kind || 'unknown'-- try {- const queryWithExperimentId = {- kind: NodeKind.ExperimentQuery,- metric: metric,- experiment_id: experimentId,- }- response = await performQuery(- setLatestVersionsOnQuery(queryWithExperimentId),- undefined,- getExperimentRefreshMode(featureFlags, !!refresh)- )-- const durationMs = Math.round(performance.now() - startTime)- const isCached = !!response?.is_cached-- if (isNewExperimentResponse(response as CachedExperimentQueryResponse)) {- results[originalIndex] = response as CachedNewExperimentQueryResponse- }- onSetResults([...results])-- successfulCount++- if (isCached) {- cachedCount++- }-- eventUsageLogic.actions.reportExperimentMetricFinished(- experimentId,- metric,- teamId,- response?.query_status?.id || null,- {- duration_ms: durationMs,- is_cached: isCached,- metric_index: metricIndex,- is_primary: isPrimary,- is_retry: isRetry,- refresh_id: refreshId,- metric_kind: metricKind,- execution_mode: getExperimentExecutionMode(featureFlags),- }- )- } catch (error: any) {- const errorCode = typeof error.code === 'string' ? error.code : null- const statusCode = typeof error.status === 'number' ? error.status : null- const { detail: errorDetail, hasDiagnostics } = parseMetricErrorDetail(error)- const queryId = response?.query_status?.id || error.queryId || null-- currentErrors[originalIndex] = {- detail: errorDetail,- statusCode,- hasDiagnostics,- code: errorCode,- queryId,- timestamp: Date.now(),- }- onSetErrors(currentErrors)-- erroredCount++-- // No telemetry here: the terminal `experiment metric error` event is emitted by the- // backend (see products/experiments/backend/hogql_queries/error_handling.py), which- // classifies from typed exceptions instead of HTTP status codes.-- onSetResults([...results])- }- }- })-- await runWithLimit(tasks, METRIC_QUERY_CONCURRENCY_LIMIT)-- return { successfulCount, erroredCount, cachedCount }-}--export function isNewExperimentResponse(- response: CachedExperimentQueryResponse-): response is CachedNewExperimentQueryResponse {- return 'baseline' in response && response.baseline !== null-}--/**- * Whether a launched experiment's freshest cached result is older than `staleAfterMinutes`.- * Returns true when there are no cached results yet, so we refresh to populate them. The results- * array can be sparse — metrics that returned no baseline leave holes — so entries without a- * `last_refresh` are skipped.- */-export function experimentResultsAreStale(- results: (CachedNewExperimentQueryResponse | undefined)[],- staleAfterMinutes: number-): boolean {- const refreshTimes = results- .filter((result): result is CachedNewExperimentQueryResponse => !!result?.last_refresh)- .map((result) => dayjs(result.last_refresh))-- if (refreshTimes.length === 0) {- return true- }-- const freshest = refreshTimes.reduce((latest, current) => (current.isAfter(latest) ? current : latest))- return dayjs().diff(freshest, 'minute', true) >= staleAfterMinutes-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentLogicValues {billing: BillingType | null // billingLogicdefaultMinimumDetectableEffect: number // experimentsConfigLogicexperimentsConfig: ExperimentsConfig | null // experimentsConfigLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic- receivedFeatureFlags: boolean // featureFlagLogicconversionMetrics: FunnelTimeConversionMetrics // funnelDataLogicfunnelResults: FunnelResultType // funnelDataLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel@@ -582,13 +393,7 @@ export interface experimentLogicValues {getInsightType: (metric: ExperimentFunnelsQuery | ExperimentMetricUnion | ExperimentTrendsQuery | undefined) => InsightType- getOrderedMetricsWithResults: (isSecondary: boolean) => {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]+ hasMetrics: booleanhasMinimumExposureForResults: booleanhealthFindings: HealthPanelFinding[] | nullhogfettiTrigger: (() => void) | null@@ -601,36 +406,14 @@ export interface experimentLogicValues {isSingleVariantShipped: booleanlaunchExperimentLoading: booleanminimumDetectableEffect: number- notifyWhenResultsReady: booleanopenDatePicker: 'end' | 'start' | null- orderedPrimaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- orderedSecondaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]primaryMetricsLengthWithSharedMetrics: number- primaryMetricsResults: CachedNewExperimentQueryResponse[]- primaryMetricsResultsErrors: any[]- primaryMetricsResultsLoading: booleanprops: anyrecommendedRunningTime: numberrecommendedSampleSize: numberresolvedExposureEvent: string- secondaryMetricsResults: CachedNewExperimentQueryResponse[]- secondaryMetricsResultsErrors: any[]- secondaryMetricsResultsLoading: booleanshippedVariantKey: string | nullshowDebugPanel: boolean- showNotificationOffer: booleanstatsMethod: ExperimentStatsMethodunfreezeExposureLoading: booleanunmodifiedExperiment: Experiment | null@@ -725,13 +508,6 @@ export interface experimentLogicActions {healthProperties: ExperimentViewedHealthProperties} // eventUsageLogicupdateExperiments: (experiment: Experiment) => Experiment // experimentsLogic- setFeatureFlags: (- flags: string[],- variants: Record<string, boolean | string>- ) => {- flags: string[]- variants: Record<string, boolean | string>- } // featureFlagLogicupdateFlagFromPartial: (flag: Partial<FeatureFlagType> & {id: number@@ -801,9 +577,6 @@ export interface experimentLogicActions {changeExperimentStartDate: (startDate: string) => {startDate: string}- clearMetricsResults: () => {- value: true- }createExperimentDashboard: () => {value: true}@@ -822,9 +595,6 @@ export interface experimentLogicActions {exposureCohort: CohortType | nullpayload?: any}- dismissNotificationOffer: () => {- value: true- }duplicateMetric: ({ uuid, isSecondary, newUuid }: { isSecondary: boolean; newUuid: string; uuid: string }) => {isSecondary: booleannewUuid: string@@ -922,20 +692,6 @@ export interface experimentLogicActions {exposures: anypayload?: boolean}- loadPrimaryMetricsResults: (- refresh?: boolean,- refreshId?: string- ) => {- refresh: boolean | undefined- refreshId: string | undefined- }- loadSecondaryMetricsResults: (- refresh?: boolean,- refreshId?: string- ) => {- refresh: boolean | undefined- refreshId: string | undefined- }markRefreshFinished: (refreshId: string,finalState: FinishedRefreshState@@ -1055,12 +811,6 @@ export interface experimentLogicActions {resumeExperiment: () => {value: true}- retryPrimaryMetric: (index: number) => {- index: number- }- retrySecondaryMetric: (index: number) => {- index: number- }setEditExperiment: (editing: boolean) => {editing: boolean}@@ -1141,33 +891,9 @@ export interface experimentLogicActions {name: string | undefineduuid: string}- setNotifyWhenResultsReady: (notify: boolean) => {- notify: boolean- }setOpenDatePicker: (boundary: 'end' | 'start' | null) => {boundary: 'end' | 'start' | null}- setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => {- results: CachedNewExperimentQueryResponse[]- }- setPrimaryMetricsResultsErrors: (errors: any[]) => {- errors: any[]- }- setPrimaryMetricsResultsLoading: (loading: boolean) => {- loading: boolean- }- setSecondaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => {- results: CachedNewExperimentQueryResponse[]- }- setSecondaryMetricsResultsErrors: (errors: any[]) => {- errors: any[]- }- setSecondaryMetricsResultsLoading: (loading: boolean) => {- loading: boolean- }- setShowNotificationOffer: (show: boolean) => {- show: boolean- }setTrendsExposureMetric: ({uuid,name,@@ -1219,9 +945,6 @@ export interface experimentLogicActions {excluded: booleanvariantKey: string}- subscribeToResultsNotification: () => {- value: true- }toggleDebugPanel: () => {value: true}@@ -1373,66 +1096,8 @@ export interface experimentLogicMeta {usesNewQueryRunner: (experiment: Experiment) => booleanhasMinimumExposureForResults: (exposures: any, usesNewQueryRunner: boolean) => booleanexposureCriteria: (experiment: Experiment) => ExperimentExposureCriteria | undefined- getOrderedMetricsWithResults: (- experiment: Experiment,- primaryMetricsResults: CachedNewExperimentQueryResponse[],- primaryMetricsResultsErrors: any[],- secondaryMetricsResults: CachedNewExperimentQueryResponse[],- secondaryMetricsResultsErrors: any[]- ) => (isSecondary: boolean) => {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- orderedPrimaryMetricsWithResults: (- getOrderedMetricsWithResults: (isSecondary: boolean) => {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- ) => {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- orderedSecondaryMetricsWithResults: (- getOrderedMetricsWithResults: (isSecondary: boolean) => {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- ) => {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- browserNoMetricsWarning: (- orderedPrimaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[],- orderedSecondaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[],- isExperimentLaunched: boolean- ) => boolean+ hasMetrics: (experiment: Experiment) => boolean+ browserNoMetricsWarning: (hasMetrics: boolean, isExperimentLaunched: boolean) => booleanstatsMethod: (experiment: Experiment) => ExperimentStatsMethod}}@@ -1457,7 +1122,7 @@ export const experimentLogic = kea<experimentLogicType>([groupsModel,['aggregationLabel', 'groupTypes', 'showGroupsOptions'],featureFlagLogic,- ['featureFlags', 'receivedFeatureFlags'],+ ['featureFlags'],holdoutsLogic,['holdouts'],billingLogic,@@ -1500,8 +1165,6 @@ export const experimentLogic = kea<experimentLogicType>([],teamLogic,['addProductIntent'],- featureFlagLogic,- ['setFeatureFlags'],featureFlagsLogic,['updateFlagFromPartial'],modalsLogic,@@ -1755,26 +1418,10 @@ export const experimentLogic = kea<experimentLogicType>([attributionValue,}),updateMetricBreakdownLimit: (uuid: string, breakdownLimit: number) => ({ uuid, breakdownLimit }),- // METRICS RESULTS- clearMetricsResults: true,- setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),- setPrimaryMetricsResultsLoading: (loading: boolean) => ({ loading }),- loadPrimaryMetricsResults: (refresh?: boolean, refreshId?: string) => ({ refresh, refreshId }),- setPrimaryMetricsResultsErrors: (errors: any[]) => ({ errors }),- retryPrimaryMetric: (index: number) => ({ index }),- setSecondaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),- loadSecondaryMetricsResults: (refresh?: boolean, refreshId?: string) => ({ refresh, refreshId }),- setSecondaryMetricsResultsErrors: (errors: any[]) => ({ errors }),- retrySecondaryMetric: (index: number) => ({ index }),- setSecondaryMetricsResultsLoading: (loading: boolean) => ({ loading }),updateDistribution: (variants: MultivariateFlagVariant[], rolloutPercentage?: number) => ({variants,rolloutPercentage,}),- subscribeToResultsNotification: true,- dismissNotificationOffer: true,- setShowNotificationOffer: (show: boolean) => ({ show }),- setNotifyWhenResultsReady: (notify: boolean) => ({ notify }),toggleDebugPanel: true,setVariantExcluded: (variantKey: string, excluded: boolean) => ({ variantKey, excluded }),}),@@ -2091,56 +1738,6 @@ export const experimentLogic = kea<experimentLogicType>([: experiment,},],- // PRIMARY METRICS- primaryMetricsResults: [- [] as CachedNewExperimentQueryResponse[],- {- setPrimaryMetricsResults: (_, { results }) => results,- loadPrimaryMetricsResults: () => [],- loadExperiment: () => [],- clearMetricsResults: () => [],- },- ],- primaryMetricsResultsLoading: [- false,- {- setPrimaryMetricsResultsLoading: (_, { loading }) => loading,- },- ],- primaryMetricsResultsErrors: [- [] as any[],- {- setPrimaryMetricsResultsErrors: (_, { errors }) => errors,- loadPrimaryMetricsResults: () => [],- loadExperiment: () => [],- clearMetricsResults: () => [],- },- ],- // SECONDARY METRICS- secondaryMetricsResults: [- [] as CachedNewExperimentQueryResponse[],- {- setSecondaryMetricsResults: (_, { results }) => results,- loadSecondaryMetricsResults: () => [],- loadExperiment: () => [],- clearMetricsResults: () => [],- },- ],- secondaryMetricsResultsLoading: [- false,- {- setSecondaryMetricsResultsLoading: (_, { loading }) => loading,- },- ],- secondaryMetricsResultsErrors: [- [] as any[],- {- setSecondaryMetricsResultsErrors: (_, { errors }) => errors,- loadSecondaryMetricsResults: () => [],- loadExperiment: () => [],- clearMetricsResults: () => [],- },- ],editingPrimaryMetricUuid: [null as string | null,{@@ -2209,20 +1806,6 @@ export const experimentLogic = kea<experimentLogicType>([setHogfettiTrigger: (_, { trigger }) => trigger,},],- showNotificationOffer: [- false,- {- setShowNotificationOffer: (_, { show }) => show,- dismissNotificationOffer: () => false,- },- ],- notifyWhenResultsReady: [- false,- {- setNotifyWhenResultsReady: (_, { notify }) => notify,- dismissNotificationOffer: () => false,- },- ],}),sharedListeners(({ values, actions, selectors, cache }) => ({/**@@ -2263,16 +1846,7 @@ export const experimentLogic = kea<experimentLogicType>([return}- // A breakdown config change alters how the metric is computed, so re-run results. The recalculation- // flow reuses the current window (metric_config_change), so this metric recomputes on its changed- // fingerprint while unchanged metrics load from cache. Legacy reloads the section that holds the metric.- if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- actions.refreshExperimentResults(true, 'metric_config_change')- } else if (location?.isPrimary) {- actions.loadPrimaryMetricsResults(true)- } else {- actions.loadSecondaryMetricsResults(true)- }+ actions.refreshExperimentResults(true, 'metric_config_change')},})),listeners(({ values, actions, selectors, asyncActions, cache, props, sharedListeners }) => ({@@ -2309,28 +1883,6 @@ export const experimentLogic = kea<experimentLogicType>([reportHealthFindingActedOn: ({ finding, actionKind }) => {captureExperimentHealthFindingActedOn(values.experiment, finding, actionKind)},- beforeUnmount: () => {- clearTimeout(cache.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.'- )- }- },loadExperimentSuccess: async ({ experiment, payload }) => {const duration = experiment?.start_date ? dayjs().diff(experiment.start_date, 'second') : null// eslint-disable-next-line no-unused-expressions@@ -2345,8 +1897,7 @@ export const experimentLogic = kea<experimentLogicType>([))- // Load metrics for launched experiments (will set up auto-refresh after load completes).- // refreshExperimentResults branches on the recalculation feature flag internally.+ // Load results for launched experiments (will set up auto-refresh after load completes).if (experiment && isLaunched(experiment)) {actions.refreshExperimentResults(false, payload?.triggeredBy ?? 'manual', true)}@@ -2549,72 +2100,24 @@ export const experimentLogic = kea<experimentLogicType>([}},refreshExperimentResults: async ({ forceRefresh, triggeredBy, refreshIfStale }) => {- // The refresh branches on the recalculation flag. Choosing a branch before the flag has- // resolved reads it as off and runs the legacy loaders, which fail for a recalculation- // experiment. Defer the refresh until flags arrive; setFeatureFlags replays it once.- if (!values.receivedFeatureFlags) {- cache.deferredRefresh = { forceRefresh, triggeredBy, refreshIfStale }- return- }-- // The setFeatureFlags listener re-runs this refresh if a later flag update contradicts this value.- cache.branchFlagValue = !!values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]- cache.lastRefreshArgs = { forceRefresh, triggeredBy, refreshIfStale }-const refreshId = generateRefreshId()const refreshStart = performance.now()- const summaries: MetricLoadingSummary[] = []- cache.refreshSummariesById = cache.refreshSummariesById ?? {}- cache.refreshSummariesById[refreshId] = summariesactions.markRefreshStarted(refreshId, triggeredBy)- // Start 10s timer to offer browser notifications- clearTimeout(cache.notificationOfferTimer)- cache.notificationOfferTimer = setTimeout(() => {- actions.setShowNotificationOffer(true)- }, 10_000)-let caughtError = falsetry {- const recalculationFlow = values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]- if (recalculationFlow) {- /**- * Config changes and auto-refresh both re-run metrics, tagged with their cause; page loads- * and manual reloads are handled elsewhere. Concurrent triggers coalesce onto one active run.- */- if (isRecalculationTrigger(triggeredBy) && values.experiment) {- experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(- triggeredBy- )- }- // 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),- ])+ if (isRecalculationTrigger(triggeredBy) && values.experiment) {+ experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(triggeredBy)}++ await asyncActions.loadExposures(forceRefresh)} catch (error) {caughtError = truethrow error} finally {const totalDurationMs = Math.round(performance.now() - refreshStart)- const refreshSummaries: MetricLoadingSummary[] = cache.refreshSummariesById?.[refreshId] ?? []- if (cache.refreshSummariesById) {- delete cache.refreshSummariesById[refreshId]- }-- // Clear notification offer timer (even when unmounted below, so it can't fire later)- clearTimeout(cache.notificationOfferTimer)- // The metric loads above can outlive the page: navigating to another experiment- // unmounts this logic and detaches its reducers, so any `values` read below would- // throw "[KEA] Can not find path ... in the store". The remaining bookkeeping only- // concerns a page that's still showing, so skip it when unmounted.if (experimentLogic.findMounted(props)) {const primaryCount =(values.experiment?.metrics?.length || 0) +@@ -2626,9 +2129,6 @@ export const experimentLogic = kea<experimentLogicType>([(values.experiment?.saved_metrics?.filter((m: { metadata: { type: string } }) => m.metadata.type === 'secondary').length || 0)- const successfulCount = refreshSummaries.reduce((sum, s) => sum + s.successfulCount, 0)- const erroredCount = refreshSummaries.reduce((sum, s) => sum + s.erroredCount, 0)- const cachedCount = refreshSummaries.reduce((sum, s) => sum + s.cachedCount, 0)posthog.capture('experiment results refresh completed', {experiment_id: values.experimentId,@@ -2636,9 +2136,6 @@ export const experimentLogic = kea<experimentLogicType>([total_duration_ms: totalDurationMs,primary_metrics_count: primaryCount,secondary_metrics_count: secondaryCount,- successful_count: successfulCount,- errored_count: erroredCount,- cached_count: cachedCount,triggered_by: triggeredBy ?? 'manual',force_refresh: !!forceRefresh,refresh_id: refreshId,@@ -2657,73 +2154,15 @@ export const experimentLogic = kea<experimentLogicType>([),})- const finalState: FinishedRefreshState = caughtError- ? 'errored'- : erroredCount > 0- ? 'partial'- : 'completed'+ const finalState: FinishedRefreshState = caughtError ? 'errored' : 'completed'actions.markRefreshFinished(refreshId, finalState)- // Fire browser notification if user subscribed- if (- values.notifyWhenResultsReady &&- 'Notification' in window &&- Notification.permission === 'granted'- ) {- const notification = new Notification('Experiment results ready', {- body: `Results for "${values.experiment.name}" are now available.`,- icon: '/static/posthog-icon.svg',- tag: `experiment-results-${values.experimentId}`,- })- notification.onclick = () => {- window.focus()- notification.close()- }- }-- // Reset notification state- actions.setShowNotificationOffer(false)- actions.setNotifyWhenResultsReady(false)-- // A warming-up experiment can show a stale "no results yet" snapshot on load, so fetch- // fresh once. When it has results we leave it to the in-tab auto-refresh, since recomputes- // might be expensive. Gated on `!forceRefresh` so the refresh we trigger here can't loop.- if (- refreshIfStale &&- !forceRefresh &&- !caughtError &&- !values.hasMinimumExposureForResults &&- experimentResultsAreStale(- [...values.primaryMetricsResults, ...values.secondaryMetricsResults],- NEW_EXPERIMENT_FORCE_REFRESH_AFTER_MINUTES- )- ) {+ if (refreshIfStale && !forceRefresh && !caughtError && !values.hasMinimumExposureForResults) {actions.refreshExperimentResults(true, 'page_load')}}}},- setFeatureFlags: () => {- // Flags have now resolved. Replay a refresh that arrived before them so the branch decision- // uses the real flag value. One-shot: clear the deferred request before re-firing.- const deferred = cache.deferredRefresh- if (deferred) {- cache.deferredRefresh = undefined- actions.refreshExperimentResults(deferred.forceRefresh, deferred.triggeredBy, deferred.refreshIfStale)- return- }- /**- * A refresh that branched on a wrong early flag value ran the wrong loaders, and nothing- * re-runs it when the real flag response lands (see the setFeatureFlags listener in- * experimentMetricsLogic for why the first flag set of a page load can be wrong). Re-run the- * last refresh when the current value contradicts the recorded one; equal values no-op.- */- const flagValue = !!values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]- const lastArgs = cache.lastRefreshArgs- if (lastArgs && cache.branchFlagValue !== undefined && flagValue !== cache.branchFlagValue) {- actions.refreshExperimentResults(lastArgs.forceRefresh, lastArgs.triggeredBy, lastArgs.refreshIfStale)- }- },updateExperimentMetrics: async () => {actions.updateExperiment({metrics: values.experiment.metrics,@@ -2731,26 +2170,16 @@ export const experimentLogic = kea<experimentLogicType>([update_feature_flag_params: false,})const outcome = await inflightUpdateOutcome(cache)- // After most failures the previous experiment and its results remain valid and visible. After a- // conflict the loader has swapped in the server's metric lists, so the previous results no longer- // pair with them.if (outcome === 'failed') {return}- // Metric results are positional. Once the metric list has changed, keeping the previous arrays- // around can briefly pair a result with the wrong metric (and gives no feedback while the- // updated results are computed). Clear both result stores so every metric in the updated list- // renders its existing per-variant loading skeleton.- actions.clearMetricsResults()const metricsLogic = experimentMetricsLogic({ experiment: values.experiment })metricsLogic.actions.setPrimaryMetricsResults([])metricsLogic.actions.setPrimaryMetricsResultsErrors([])metricsLogic.actions.setSecondaryMetricsResults([])metricsLogic.actions.setSecondaryMetricsResultsErrors([])- // Reload results for added/edited metrics. After a conflict this edit did not save, so nothing- // needs a recompute and cached results are enough.actions.refreshExperimentResults(outcome === 'saved', 'metric_config_change')},updateExposureCriteria: async () => {@@ -2762,9 +2191,6 @@ export const experimentLogic = kea<experimentLogicType>([})const outcome = await inflightUpdateOutcome(cache)if (outcome !== 'saved') {- // The modal closes before the save settles. After a conflict the loader keeps the edit for- // review. After any other failure, put back the saved criteria, so the page does not show- // criteria that the server does not have.if (outcome === 'failed' && values.unmodifiedExperiment) {actions.setExperiment({ exposure_criteria: values.unmodifiedExperiment.exposure_criteria })}@@ -2773,23 +2199,22 @@ export const experimentLogic = kea<experimentLogicType>([actions.refreshExperimentResults(true, 'experiment_config_change')},updateExperimentSettings: async ({ update, fromModal }) => {- // Settings like stats config, CUPED, and conversion-window handling change- // how metrics and exposures are computed, so persist then re-query.- // A save sends the whole stats_config object, also the keys that this user did not edit. After a conflict,- // a kept copy would send those stale keys over the other edit, so the controls show the server's copy.actions.updateExperiment({ ...update, update_feature_flag_params: false, discardOnConflict: true })+if (!(await inflightUpdateSaved(cache))) {return}+if (fromModal === 'cuped') {actions.closeCupedModal()} else if (fromModal === 'statsMethod') {actions.closeStatsEngineModal()}- // Unlaunched experiments have no results to recalculate, so don't promise a recalculation.+lemonToast.success(values.isExperimentLaunched ? 'Settings saved. Recalculating results…' : 'Settings saved')+actions.refreshExperimentResults(true, 'experiment_config_change')},resetRunningExperiment: async () => {@@ -2800,8 +2225,6 @@ export const experimentLogic = kea<experimentLogicType>([)actions.setExperiment(response)refreshTreeItem('experiment', String(values.experimentId))- // Metric results live in separate reducers not covered by setExperiment- actions.clearMetricsResults()} catch (error: any) {lemonToast.error(error.detail || 'Failed to reset experiment')}@@ -3158,168 +2581,6 @@ export const experimentLogic = kea<experimentLogicType>([actions.setExperiment(structuredClone(values.unmodifiedExperiment))}},- loadPrimaryMetricsResults: async ({ refresh, refreshId }: { refresh?: boolean; refreshId?: string }) => {- actions.setPrimaryMetricsResultsLoading(true)- actions.setPrimaryMetricsResults([])-- const sharedMetrics: ExperimentMetric[] = sharedMetricsToExperimentMetrics(- values.experiment?.saved_metrics as ExperimentSavedMetric[],- 'primary'- )-- const metrics = [...(values.experiment?.metrics || []), ...sharedMetrics]-- const resolvedRefreshId = refreshId || generateRefreshId()- const summary = await loadMetrics({- metrics,- experimentId: values.experimentId,- refresh,- teamId: values.currentTeamId,- refreshId: resolvedRefreshId,- isPrimary: true,- isRetry: false,- metricIndexOffset: 0,- orderedUuids: values.experiment?.primary_metrics_ordered_uuids,- featureFlags: values.featureFlags,- onSetResults: actions.setPrimaryMetricsResults,- onSetErrors: actions.setPrimaryMetricsResultsErrors,- })-- const refreshSummaries = cache.refreshSummariesById?.[resolvedRefreshId]- if (refreshSummaries) {- refreshSummaries.push(summary)- }-- actions.setPrimaryMetricsResultsLoading(false)-- // Mark the review results task as complete when results are loaded for a launched experiment.- // Mounted check first: the load can outlive the page, and `values` reads throw once unmounted.- if (experimentLogic.findMounted(props) && values.experiment && isLaunched(values.experiment)) {- globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.ReviewExperimentResults)- }- },- loadSecondaryMetricsResults: async ({ refresh, refreshId }: { refresh?: boolean; refreshId?: string }) => {- actions.setSecondaryMetricsResultsLoading(true)- actions.setSecondaryMetricsResults([])-- const sharedMetrics: ExperimentMetric[] = sharedMetricsToExperimentMetrics(- values.experiment?.saved_metrics as ExperimentSavedMetric[],- 'secondary'- )- const secondaryMetrics = [...(values.experiment?.metrics_secondary || []), ...sharedMetrics]-- const resolvedRefreshId = refreshId || generateRefreshId()- const summary = await loadMetrics({- metrics: secondaryMetrics,- experimentId: values.experimentId,- refresh,- teamId: values.currentTeamId,- refreshId: resolvedRefreshId,- isPrimary: false,- isRetry: false,- metricIndexOffset: 0,- orderedUuids: values.experiment?.secondary_metrics_ordered_uuids,- featureFlags: values.featureFlags,- onSetResults: actions.setSecondaryMetricsResults,- onSetErrors: actions.setSecondaryMetricsResultsErrors,- })-- const refreshSummaries = cache.refreshSummariesById?.[resolvedRefreshId]- if (refreshSummaries) {- refreshSummaries.push(summary)- }-- actions.setSecondaryMetricsResultsLoading(false)- },- retryPrimaryMetric: async ({ index }: { index: number }) => {- // Clear the error for this metric- const currentErrors = [...values.primaryMetricsResultsErrors]- currentErrors[index] = null- actions.setPrimaryMetricsResultsErrors(currentErrors)-- // Get the metric to retry-- const sharedMetrics: ExperimentMetric[] = sharedMetricsToExperimentMetrics(- values.experiment?.saved_metrics as ExperimentSavedMetric[],- 'primary'- )-- const metrics = [...(values.experiment?.metrics || []), ...sharedMetrics]-- const metricToRetry = metrics[index]- if (!metricToRetry) {- return- }-- // Create single-item arrays for this metric- const singleMetricArray = [metricToRetry]- const currentResults = [...values.primaryMetricsResults]-- // Load just this one metric- await loadMetrics({- metrics: singleMetricArray,- experimentId: values.experimentId,- refresh: true,- teamId: values.currentTeamId,- refreshId: generateRefreshId(),- isPrimary: true,- isRetry: true,- metricIndexOffset: index,- featureFlags: values.featureFlags,- onSetResults: (results) => {- currentResults[index] = results[0]- actions.setPrimaryMetricsResults(currentResults)- },- onSetErrors: (errors) => {- currentErrors[index] = errors[0]- actions.setPrimaryMetricsResultsErrors(currentErrors)- },- })- },- retrySecondaryMetric: async ({ index }: { index: number }) => {- // Clear the error for this metric- const currentErrors = [...values.secondaryMetricsResultsErrors]- currentErrors[index] = null- actions.setSecondaryMetricsResultsErrors(currentErrors)-- // Get the metric to retry- const sharedMetrics: ExperimentMetric[] = sharedMetricsToExperimentMetrics(- values.experiment?.saved_metrics as ExperimentSavedMetric[],- 'secondary'- )-- const secondaryMetrics = [...(values.experiment?.metrics_secondary || []), ...sharedMetrics]-- const metricToRetry = secondaryMetrics[index]- if (!metricToRetry) {- return- }-- // Create single-item arrays for this metric- const singleMetricArray = [metricToRetry]- const currentResults = [...values.secondaryMetricsResults]-- // Load just this one metric- await loadMetrics({- metrics: singleMetricArray,- experimentId: values.experimentId,- refresh: true,- teamId: values.currentTeamId,- refreshId: generateRefreshId(),- isPrimary: false,- isRetry: true,- metricIndexOffset: index,- featureFlags: values.featureFlags,- onSetResults: (results) => {- currentResults[index] = results[0]- actions.setSecondaryMetricsResults(currentResults)- },- onSetErrors: (errors) => {- currentErrors[index] = errors[0]- actions.setSecondaryMetricsResultsErrors(currentErrors)- },- })- },openReleaseConditionsModal: () => {const numericFlagId = values.experiment.feature_flag?.idif (numericFlagId) {@@ -3387,27 +2648,6 @@ export const experimentLogic = kea<experimentLogicType>([const moved = new Set(movedUuids)const orderingField = isSecondary ? 'secondary_metrics_ordered_uuids' : 'primary_metrics_ordered_uuids'- // Moves and removals don't change any metric's definition, so existing- // results stay valid — they only need realigning to the new positional- // layout. That's unsafe while a load is writing positional results- // concurrently.- const canReuseResults = !values.primaryMetricsResultsLoading && !values.secondaryMetricsResultsLoading-- // Snapshot results/errors by uuid before the update changes the layout.- const resultsByUuid = new Map<string, CachedNewExperimentQueryResponse | undefined>()- const errorsByUuid = new Map<string, any>()- for (const section of [false, true]) {- const uuids = getSectionMetricUuids(values.experiment, section)- const results = section ? values.secondaryMetricsResults : values.primaryMetricsResults- const errors = section ? values.secondaryMetricsResultsErrors : values.primaryMetricsResultsErrors- uuids.forEach((uuid, index) => {- if (uuid) {- resultsByUuid.set(uuid, results[index])- errorsByUuid.set(uuid, errors[index])- }- })- }-const sourceField = isSecondary ? 'metrics_secondary' : 'metrics'const targetField = isSecondary ? 'metrics' : 'metrics_secondary'const sourceInlineMetrics = values.experiment[sourceField] || []@@ -3416,10 +2656,6 @@ export const experimentLogic = kea<experimentLogicType>([(m) => !(m.uuid && (moved.has(m.uuid) || removed.has(m.uuid))))- // The ordering arrays are a display hint: a removed metric's stale entry matches nothing,- // and a moved metric needs no entry in the target section, where it renders last. The- // source array is pruned on a move so readers that rank across both sections do not keep- // placing the metric among its old neighbours.const update: Partial<Experiment> & { update_feature_flag_params?: boolean } = {[sourceField]: remainingInlineMetrics,update_feature_flag_params: false,@@ -3449,59 +2685,12 @@ export const experimentLogic = kea<experimentLogicType>([}actions.updateExperiment(update)- // After a conflict the loader has swapped in the server's metric lists, so the results must- // follow that layout too.- if ((await inflightUpdateOutcome(cache)) === 'failed') {- return- }-- // The save can wait behind other updates in the queue, and a results load can start meanwhile.- // A realign would then overwrite the arrays that this load fills.- if (!canReuseResults || values.primaryMetricsResultsLoading || values.secondaryMetricsResultsLoading) {- actions.refreshExperimentResults(true, 'metric_config_change')+ const outcome = await inflightUpdateOutcome(cache)+ if (outcome === 'failed') {return}- const newPrimaryUuids = getSectionMetricUuids(values.experiment, false)- const newSecondaryUuids = getSectionMetricUuids(values.experiment, true)- actions.setPrimaryMetricsResults(- newPrimaryUuids.map((uuid) =>- uuid ? resultsByUuid.get(uuid) : undefined- ) as CachedNewExperimentQueryResponse[]- )- actions.setPrimaryMetricsResultsErrors(- newPrimaryUuids.map((uuid) => (uuid ? (errorsByUuid.get(uuid) ?? null) : null))- )- actions.setSecondaryMetricsResults(- newSecondaryUuids.map((uuid) =>- uuid ? resultsByUuid.get(uuid) : undefined- ) as CachedNewExperimentQueryResponse[]- )- actions.setSecondaryMetricsResultsErrors(- newSecondaryUuids.map((uuid) => (uuid ? (errorsByUuid.get(uuid) ?? null) : null))- )-- // A moved metric without a result or error would be stuck rendering as- // loading in its new section — fetch just those. Sequentially, because- // the retry actions write back the whole positional array and would- // stomp each other's results if run concurrently.- if (isLaunched(values.experiment)) {- const targetUuids = isSecondary ? newPrimaryUuids : newSecondaryUuids- for (const uuid of movedUuids) {- if (resultsByUuid.get(uuid) || errorsByUuid.get(uuid)) {- continue- }- const newIndex = targetUuids.indexOf(uuid)- if (newIndex === -1) {- continue- }- if (isSecondary) {- await asyncActions.retryPrimaryMetric(newIndex)- } else {- await asyncActions.retrySecondaryMetric(newIndex)- }- }- }+ actions.refreshExperimentResults(outcome === 'saved', 'metric_config_change')},updateMetricBreakdown: [({ uuid, breakdown }, _breakpoint, _action, previousState): void => {@@ -3555,18 +2744,11 @@ export const experimentLogic = kea<experimentLogicType>([},})- // Re-fetch results since the variant set changed. On the recalculation flow this advances the- // window (experiment_config_change), so every metric recomputes; legacy uses the per-metric- // loaders. Exposures refresh either way.- if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {- // eslint-disable-next-line no-unused-expressions- values.experiment &&- experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(- 'experiment_config_change'- )- } else {- actions.loadPrimaryMetricsResults(true)- actions.loadSecondaryMetricsResults(true)++ if (values.experiment) {+ experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(+ 'experiment_config_change'+ )}actions.loadExposures(true)},@@ -4052,66 +3234,16 @@ export const experimentLogic = kea<experimentLogicType>([return experiment.exposure_criteria},],- getOrderedMetricsWithResults: [- (s) => [- s.experiment,- s.primaryMetricsResults,- s.primaryMetricsResultsErrors,- s.secondaryMetricsResults,- s.secondaryMetricsResultsErrors,- ],- (- experiment: Experiment,- primaryMetricsResults: CachedNewExperimentQueryResponse[],- primaryMetricsResultsErrors: any[],- secondaryMetricsResults: CachedNewExperimentQueryResponse[],- secondaryMetricsResultsErrors: any[]- ) =>- (isSecondary: boolean) =>- getOrderedMetricsWithResults(- experiment,- primaryMetricsResults,- primaryMetricsResultsErrors,- secondaryMetricsResults,- secondaryMetricsResultsErrors,- isSecondary- ),- ],- orderedPrimaryMetricsWithResults: [- (s) => [s.getOrderedMetricsWithResults],- (- getOrderedMetricsWithResults: (isSecondary: boolean) => {- displayIndex: number- error: any- metric: import('~/queries/schema/schema-general').ExperimentMetricUnion- metricIndex: number- result: any- }[]- ) => getOrderedMetricsWithResults(false),- ],- orderedSecondaryMetricsWithResults: [- (s) => [s.getOrderedMetricsWithResults],- (- getOrderedMetricsWithResults: (isSecondary: boolean) => {- displayIndex: number- error: any- metric: import('~/queries/schema/schema-general').ExperimentMetricUnion- metricIndex: number- result: any- }[]- ) => getOrderedMetricsWithResults(true),- ],// The page's own rule for "No metrics defined", for people without health findings.+ hasMetrics: [+ (s) => [s.experiment],+ (experiment: Experiment): boolean =>+ getSectionMetricUuids(experiment, false).length > 0 ||+ getSectionMetricUuids(experiment, true).length > 0,+ ],browserNoMetricsWarning: [- (s) => [s.orderedPrimaryMetricsWithResults, s.orderedSecondaryMetricsWithResults, s.isExperimentLaunched],- (- orderedPrimaryMetricsWithResults: unknown[],- orderedSecondaryMetricsWithResults: unknown[],- isExperimentLaunched: boolean- ): boolean =>- isExperimentLaunched &&- orderedPrimaryMetricsWithResults.length === 0 &&- orderedSecondaryMetricsWithResults.length === 0,+ (s) => [s.hasMetrics, s.isExperimentLaunched],+ (hasMetrics: boolean, isExperimentLaunched: boolean): boolean => isExperimentLaunched && !hasMetrics,],statsMethod: [(s) => [s.experiment],diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex 8f5191507760..eec344bc2d17 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -2,8 +2,7 @@ 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 { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { preflightLogic } from 'lib/logic/preflightLogic'import { projectLogic } from 'scenes/projectLogic'@@ -144,10 +143,6 @@ describe('experimentMetricsLogic', () => {},})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) })})@@ -213,6 +208,10 @@ describe('experimentMetricsLogic', () => {],},})+ const markTaskAsCompleted = jest.fn()+ const setupSpy = jest+ .spyOn(globalSetupLogic, 'findMounted')+ .mockReturnValue({ actions: { markTaskAsCompleted } } as any)mountLogic()// afterMount fires loadLatestRecalculation on its own — no manual dispatch needed.@@ -230,6 +229,9 @@ describe('experimentMetricsLogic', () => {expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)expect(logic.values.secondaryMetricsResults[0]).toEqual(secondaryResult)expect(logic.values.recalculationLoading).toBe(false)+ // Results on screen for a launched experiment complete the review results setup task.+ expect(markTaskAsCompleted).toHaveBeenCalledWith(SetupTaskId.ReviewExperimentResults)+ setupSpy.mockRestore()})it('surfaces a discovery-step failure (metric_errors entry, no result row) loaded on mount', async () => {@@ -1508,119 +1510,6 @@ describe('experimentMetricsLogic', () => {})})- 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()- })- })-- describe('feature flag races on mount', () => {- it('defers the latest fetch until flags arrive, then replays it', async () => {- // Reinitialize kea so flags start unresolved (receivedFeatureFlags false). Reading the flag as- // off here would clear loading and skip the fetch, hiding the recalculation results.- initKeaTests()- await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })- const latestMock = jest.fn(() => [200, completedRecalculation])- useMocks({- get: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': latestMock },- })- mountLogic()-- // afterMount fires loadLatestRecalculation, but it defers: no fetch while flags are unresolved.- await expectLogic(logic)- .toDispatchActions(['loadLatestRecalculation'])- .toNotHaveDispatchedActions(['setCurrentRecalculation'])- expect(latestMock).not.toHaveBeenCalled()-- // While deferred, loading must clear: the loadLatestRecalculation action set it true, and if flags- // never arrive it would otherwise freeze the reload control and wrongly queue config-change reruns.- expect(logic.values.recalculationLoading).toBe(false)- expect(logic.values.isRecalculating).toBe(false)-- // Once flags arrive with the recalculation flag on, the deferred fetch replays.- await expectLogic(logic, () => {- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,- })- }).toDispatchActions(['setFeatureFlags', 'loadLatestRecalculation', 'setCurrentRecalculation'])- expect(latestMock).toHaveBeenCalledTimes(1)- })-- it('re-runs the load when a later flag update contradicts the value the mount decision used', async () => {- // The first flag set of a page load can come from the server bootstrap, which omits- // org-targeted flags: flags count as received, but this flag reads off, so the mount load bails.- featureFlagLogic.actions.setFeatureFlags([], {})- const latestMock = jest.fn(() => [200, completedRecalculation])- useMocks({- get: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': latestMock },- })- mountLogic()-- await expectLogic(logic)- .toDispatchActions(['loadLatestRecalculation'])- .toNotHaveDispatchedActions(['setCurrentRecalculation'])- expect(latestMock).not.toHaveBeenCalled()-- // The real flag response lands with the flag on. The load must re-run, or the recalculation- // UI waits forever for results that nothing fetches.- await expectLogic(logic, () => {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,- })- }).toDispatchActions(['setFeatureFlags', 'loadLatestRecalculation', 'setCurrentRecalculation'])- expect(latestMock).toHaveBeenCalledTimes(1)-- // A repeated update with the same value must not re-run the load.- await expectLogic(logic, () => {- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION], {- [FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]: true,- })- }).toNotHaveDispatchedActions(['loadLatestRecalculation'])- expect(latestMock).toHaveBeenCalledTimes(1)- })- })-describe('queuedRerun reducer', () => {beforeEach(() => {mountLogic()diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex 69db793e0314..7514332591de 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -3,13 +3,11 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'-import { FEATURE_FLAGS } from 'lib/constants'+import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { dayjs } from 'lib/dayjs'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'lib/logic/preflightLogic'import { projectLogic } from 'scenes/projectLogic'-import type { FeatureFlagsSet } from '~/lib/logic/featureFlagLogic'import type { CachedNewExperimentQueryResponse, ExperimentMetric } from '~/queries/schema/schema-general'import { Experiment } from '~/types'import type { ExperimentIdType } from '~/types'@@ -219,8 +217,6 @@ const resolveErrorByUuid = (recalculation: RecalculationPayload): ResolveByUuid<// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentMetricsLogicValues {- featureFlags: FeatureFlagsSet // featureFlagLogic- receivedFeatureFlags: boolean // featureFlagLogicisDev: boolean | undefined // preflightLogiccurrentProjectId: number | null // projectLogicbackendEnforcesRefreshWindow: boolean@@ -255,13 +251,6 @@ export interface experimentMetricsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentMetricsLogicActions {- setFeatureFlags: (- flags: string[],- variants: Record<string, boolean | string>- ) => {- flags: string[]- variants: Record<string, boolean | string>- } // featureFlagLogicloadLatestRecalculation: () => {value: true}@@ -342,15 +331,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([key((props) => props.experiment.id),path((key) => ['scenes', 'experiment', 'experimentMetricsLogic', String(key)]),connect(() => ({- values: [- projectLogic,- ['currentProjectId'],- featureFlagLogic,- ['featureFlags', 'receivedFeatureFlags'],- preflightLogic,- ['isDev'],- ],- actions: [featureFlagLogic, ['setFeatureFlags']],+ values: [projectLogic, ['currentProjectId'], preflightLogic, ['isDev']],})),actions({setCurrentRecalculation: (recalculation: RecalculationPayload | null) => ({ recalculation }),@@ -546,23 +527,17 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([],}),listeners(({ actions, values, props, cache }) => {- const flagEnabled = (): boolean => !!values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]-- /**- * Recalculations only make sense once an experiment has launched: a draft has no results to fetch.- * A stopped experiment still has final results to compute and display, so it is included here — this- * mirrors the backend, which only rejects recalculation for drafts (`is_launched`). Gates both the- * latest-fetch and triggering a new run.- */const experimentIsLaunched = (): boolean => isLaunched(props.experiment)- /**- * some local helpers for the listeners closure- */+ const markResultsReviewed = (recalculation: RecalculationPayload): void => {+ const terminal =+ recalculation.status === RECALCULATION_STATUSES.completed ||+ recalculation.status === RECALCULATION_STATUSES.failed+ if (terminal && experimentMetricsLogic.findMounted(props) && experimentIsLaunched()) {+ globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.ReviewExperimentResults)+ }+ }- /**- * extracts project id and experiment id from values and props.- */const ids = (): { projectId: number; experimentId: number } | null => {const projectId = values.currentProjectIdconst experimentId = props.experiment.id@@ -572,10 +547,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([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: RecalculationPayload): void => {const startMs = cache.recalcStartMs ?? Date.now()reportExperimentMetricRecalculation(@@ -592,10 +563,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([)}- /**- * apply per-metric results and errors by setting primary and secondary metric results and errors.- * Partial failures will load the metrics that succeeded, and failed metrics get a nice error view.- */const applyResults = (recalculation: RecalculationPayload): void => {const resultFor = resolveResultByUuid(recalculation.results)const errorFor = resolveErrorByUuid(recalculation)@@ -603,14 +570,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([const alignPrimary = alignByMetricPosition(props.experiment, 'primary')const alignSecondary = alignByMetricPosition(props.experiment, 'secondary')- /**- * Merge, don't overwrite: keep whatever is already shown for a metric until its real result or- * error lands. A run that is still pending (or a cold_run mid-flight) carries an empty `results`- * list, so a plain overwrite would blank cells we already populated (e.g. timeseries cold-start- * placeholders), flipping them back to a loading spinner. A slot is updated only when this payload- * has a result OR an error for that metric; a new error clears the old result and vice versa, so a- * cell never shows a stale result alongside a fresh error.- */const nextResults = alignPrimary(resultFor)const nextSecondaryResults = alignSecondary(resultFor)const nextErrors = alignPrimary(errorFor)@@ -631,6 +590,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([}return current[i]})+const mergeErrors = (current: (unknown | null)[],nextError: MetricErrorState[],@@ -672,28 +632,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([return {loadLatestRecalculation: async () => {- /**- * Flags may not have resolved yet on mount. Reading the flag as off here would clear the- * loading state and skip the fetch, so the recalculation results never appear. Defer until- * flags arrive; setFeatureFlags replays this fetch. Clear the loading state while deferred:- * the loadLatestRecalculation action set it true, and if flags never arrive (the app renders- * after appLogic's timeout with receivedFeatureFlags still false) it would otherwise strand- * `isRecalculating` true, freezing the reload control and wrongly queueing config-change reruns.- */- if (!values.receivedFeatureFlags) {- cache.deferredLoadLatest = true- actions.setRecalculationLoading(false)- return- }- // The setFeatureFlags listener re-runs this load if a later flag update contradicts this value.- cache.branchFlagValue = flagEnabled()- /**- * bail if feature not enabled. Clear recalculation loading state- */- if (!flagEnabled()) {- actions.setRecalculationLoading(false)- return- }// Don't fetch for draft experiments — there's nothing to recalculate yet.if (!experimentIsLaunched()) {actions.setRecalculationLoading(false)@@ -721,6 +659,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([)actions.setCurrentRecalculation(recalculation)applyResults(recalculation)+ markResultsReviewed(recalculation)/*** if there's an active recalculation running, schedule polling of@@ -767,26 +706,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([actions.setRecalculationLoading(false)}},- setFeatureFlags: () => {- // Flags have resolved. Replay a latest-recalculation fetch that arrived before them so the- // branch decision uses the real flag value. One-shot: clear the deferred flag first.- if (cache.deferredLoadLatest) {- cache.deferredLoadLatest = false- actions.loadLatestRecalculation()- return- }- /**- * The deferred replay only covers loads that ran before any flags arrived. The first- * setFeatureFlags of a page load can carry the server bootstrap set, which omits every flag- * it could not evaluate locally (org-targeted flags among them), so this flag reads off. A- * load that branched on that value bailed, and nothing else re-runs it when the real flag- * response lands, which leaves the recalculation UI waiting forever. Re-run it when the- * current value contradicts the recorded one; equal values no-op.- */- if (cache.branchFlagValue !== undefined && flagEnabled() !== cache.branchFlagValue) {- actions.loadLatestRecalculation()- }- },setCurrentRecalculation: () => {// Re-enable the reload button the moment the window closes, not on the next data load.cache.disposables.dispose('manualRefreshEligibility')@@ -803,12 +722,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([}, 'manualRefreshEligibility')},triggerRecalculation: async ({ trigger }) => {- /**- * bail if feature not enabled- */- if (!flagEnabled()) {- return- }/*** Don't recalculate draft experiments; a config-change edit on a draft shouldn't kick off a* run. Stopped experiments are allowed — they still need their final results computed.@@ -837,13 +750,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([actions.setQueuedRerun(trigger)return}- /**- * Mark the metrics that already show something (a value or an error) as recalculating, so- * they keep their value and show a loading tag until the new result streams in. Cold runs- * have nothing prior, so nothing to mark.- */- // Marks that already belong to a run being polled (set by loadLatestRecalculation when it- // found an active run) must survive a rejected create, so keep them for the catch block.+const previousRecalculatingMetricUuids = new Set(values.recalculatingMetricUuids)if (trigger !== 'cold_run') {actions.setRecalculatingMetricUuids(@@ -970,9 +877,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([* results without dispatching pollRecalculation, so cache.activeRecalculationId covers that case.*/pollRecalculation: async ({ recalculationId }, breakpoint) => {- if (!flagEnabled()) {- return- }const resolvedIds = ids()if (!resolvedIds) {return@@ -1070,6 +974,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([// Successful metrics load, failed metrics surface their error in-row.applyResults(recalculation)+ markResultsReviewed(recalculation)emitTerminalEvent(recalculation)if (recalculation.failed_metrics > 0) {lemonToast.error(diff --git a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.tsindex 796cb1ff7ef9..44dcf37c1d9f 100644--- a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts@@ -1,7 +1,5 @@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'@@ -44,10 +42,6 @@ describe('experimentResultsNotificationLogic', () => {},})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 })diff --git a/frontend/src/scenes/experiments/experimentResultsStaleness.test.ts b/frontend/src/scenes/experiments/experimentResultsStaleness.test.tsdeleted file mode 100644index f9bd43fd4890..000000000000--- a/frontend/src/scenes/experiments/experimentResultsStaleness.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import { dayjs } from 'lib/dayjs'--import { CachedNewExperimentQueryResponse } from '~/queries/schema/schema-general'--import { NEW_EXPERIMENT_FORCE_REFRESH_AFTER_MINUTES } from 'products/experiments/frontend/constants'--import { experimentResultsAreStale } from './experimentLogic'--const THRESHOLD = NEW_EXPERIMENT_FORCE_REFRESH_AFTER_MINUTES--const resultRefreshedMinutesAgo = (minutes: number): CachedNewExperimentQueryResponse =>- ({- last_refresh: dayjs().subtract(minutes, 'minute').toISOString(),- }) as CachedNewExperimentQueryResponse--describe('experimentResultsAreStale', () => {- it('treats an empty result set as stale (no results yet — cheap to refresh)', () => {- expect(experimentResultsAreStale([], THRESHOLD)).toBe(true)- })-- it('treats results with no last_refresh as stale', () => {- expect(experimentResultsAreStale([{} as CachedNewExperimentQueryResponse], THRESHOLD)).toBe(true)- })-- it('is not stale when the freshest result is within the threshold', () => {- const results = [resultRefreshedMinutesAgo(THRESHOLD * 5), resultRefreshedMinutesAgo(THRESHOLD / 2)]- expect(experimentResultsAreStale(results, THRESHOLD)).toBe(false)- })-- it('is stale when every result is older than the threshold', () => {- const results = [resultRefreshedMinutesAgo(THRESHOLD * 2), resultRefreshedMinutesAgo(THRESHOLD * 5)]- expect(experimentResultsAreStale(results, THRESHOLD)).toBe(true)- })-- it('uses the freshest result across primary and secondary metrics', () => {- // One metric is stale, but another was refreshed recently — overall not stale.- const results = [resultRefreshedMinutesAgo(THRESHOLD * 10), resultRefreshedMinutesAgo(THRESHOLD / 2)]- expect(experimentResultsAreStale(results, THRESHOLD)).toBe(false)- })-- it('ignores sparse holes left by metrics that returned no baseline', () => {- const results = new Array(3) as (CachedNewExperimentQueryResponse | undefined)[]- results[1] = resultRefreshedMinutesAgo(THRESHOLD / 2)- expect(experimentResultsAreStale(results, THRESHOLD)).toBe(false)- })-})diff --git a/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsxindex 1f4360603562..25ea4257a2f0 100644--- a/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx@@ -10,6 +10,15 @@ import EXPERIMENT_WITH_ASYMMETRIC_INTERVALS from '~/mocks/fixtures/api/experimenimport EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_query_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_ASYMMETRIC_INTERVALS,+ resultsByMetricType(EXPERIMENT_WITH_ASYMMETRIC_INTERVALS, {+ mean: EXPERIMENT_METRIC_RESULT_WITH_ASYMMETRIC_INTERVALS,+ })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -22,6 +31,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_ASYMMETRIC_INTERVALS.id}/`]:EXPERIMENT_WITH_ASYMMETRIC_INTERVALS,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -32,14 +42,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, EXPERIMENT_METRIC_RESULT_WITH_ASYMMETRIC_INTERVALS]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentExposuresExpanded.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentExposuresExpanded.stories.tsxindex 6aa5e16fec93..396ae653633a 100644--- a/frontend/src/scenes/experiments/stories/ExperimentExposuresExpanded.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentExposuresExpanded.stories.tsx@@ -12,6 +12,13 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_MEAN_METRIC,+ resultsByMetricType(EXPERIMENT_WITH_MEAN_METRIC, { mean: MEAN_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -24,6 +31,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/`]: EXPERIMENT_WITH_MEAN_METRIC,[`/api/projects/:team_id/experiment_holdouts`]: [],[`/api/projects/:team_id/experiment_saved_metrics/`]: [],@@ -32,14 +40,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, MEAN_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsxindex 6e027262b5a1..ae2809d781b0 100644--- a/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx@@ -7,15 +7,20 @@ import EXPERIMENT_FREQUENTIST_FIVE_VARIANTS from '~/mocks/fixtures/api/experimenimport FUNNEL_METRIC_RESULT from '~/mocks/fixtures/api/experiments/experiment_frequentist_five_variants_funnel_metric_result.json'import MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/experiment_frequentist_five_variants_mean_metric_result.json'import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_query_result.json'-import {- ExperimentMetric,- NodeKind,- isExperimentFunnelMetric,- isExperimentMeanMetric,-} from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'import { App } from '~/scenes/App'import { urls } from '~/scenes/urls'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_FREQUENTIST_FIVE_VARIANTS,+ resultsByMetricType(EXPERIMENT_FREQUENTIST_FIVE_VARIANTS, {+ mean: MEAN_METRIC_RESULT,+ funnel: FUNNEL_METRIC_RESULT,+ })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -28,6 +33,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_FREQUENTIST_FIVE_VARIANTS.id}/`]:EXPERIMENT_FREQUENTIST_FIVE_VARIANTS,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -38,18 +44,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- if (isExperimentFunnelMetric(body.query.metric as ExperimentMetric)) {- return [200, FUNNEL_METRIC_RESULT]- } else if (isExperimentMeanMetric(body.query.metric as ExperimentMetric)) {- return [200, MEAN_METRIC_RESULT]- }+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsxindex 2c6771a457a1..1159687798a5 100644--- a/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx@@ -9,7 +9,14 @@ import EXPERIMENT_FREQUENTIST_TWO_VARIANTS from '~/mocks/fixtures/api/experimentimport FUNNEL_METRIC_RESULT from '~/mocks/fixtures/api/experiments/experiment_frequentist_two_variants_funnel_metric_result.json'import MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/experiment_frequentist_two_variants_mean_metric_result.json'import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_query_result.json'-import { NodeKind, isExperimentFunnelMetric, isExperimentMeanMetric } from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'++import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_FREQUENTIST_TWO_VARIANTS,+ resultsByMetricType(EXPERIMENT_FREQUENTIST_TWO_VARIANTS, { mean: MEAN_METRIC_RESULT, funnel: FUNNEL_METRIC_RESULT })+)const meta: Meta = {component: App,@@ -23,6 +30,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_FREQUENTIST_TWO_VARIANTS.id}/`]:EXPERIMENT_FREQUENTIST_TWO_VARIANTS,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -33,18 +41,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- if (isExperimentFunnelMetric(body.query.metric)) {- return [200, FUNNEL_METRIC_RESULT]- } else if (isExperimentMeanMetric(body.query.metric)) {- return [200, MEAN_METRIC_RESULT]- }+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentResultsRowRecordingLinks.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentResultsRowRecordingLinks.stories.tsxindex 3140dc217492..981bf48ed862 100644--- a/frontend/src/scenes/experiments/stories/ExperimentResultsRowRecordingLinks.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentResultsRowRecordingLinks.stories.tsx@@ -13,10 +13,21 @@ import FUNNELS_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metriimport MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'+// The split button each variant row offers. The menu is the feature: it names the populations the// Recordings tab can open for this metric, and a funnel names different ones from a mean metric.const MAIN_BUTTON = '[data-attr="experiment-metrics-view-recordings"]'+const FUNNEL_RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_FUNNEL_METRIC,+ resultsByMetricType(EXPERIMENT_WITH_FUNNEL_METRIC, { funnel: FUNNELS_METRIC_RESULT })+)+const MEAN_RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_MEAN_METRIC,+ resultsByMetricType(EXPERIMENT_WITH_MEAN_METRIC, { mean: MEAN_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -30,6 +41,8 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...FUNNEL_RECALCULATION.get,+ ...MEAN_RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_FUNNEL_METRIC.id}/`]:EXPERIMENT_WITH_FUNNEL_METRIC,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/`]: EXPERIMENT_WITH_MEAN_METRIC,@@ -46,16 +59,14 @@ const meta: Meta = {'/api/projects/:team_id/property_definitions/seen_together': {},},post: {+ ...FUNNEL_RECALCULATION.post,+ ...MEAN_RECALCULATION.post,// Answered so the scene does not raise a failure toast over the table.'/api/projects/:team_id/experiments/calculate_running_time/': {},+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, FUNNELS_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),@@ -67,14 +78,10 @@ type Story = StoryObj<{}>const meanMetricDecorator = mswDecorator({post: {+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, MEAN_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},})diff --git a/frontend/src/scenes/experiments/stories/ExperimentStoppedWithConclusion.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentStoppedWithConclusion.stories.tsxindex 289aa783ce05..8ccde4cf87c9 100644--- a/frontend/src/scenes/experiments/stories/ExperimentStoppedWithConclusion.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentStoppedWithConclusion.stories.tsx@@ -9,6 +9,8 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport FUNNELS_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'+const EXPERIMENT_STOPPED_WITH_CONCLUSION = {...EXPERIMENT_WITH_FUNNEL_METRIC,end_date: '2025-01-20T14:39:00Z',@@ -16,6 +18,11 @@ const EXPERIMENT_STOPPED_WITH_CONCLUSION = {conclusion_comment: 'The test variant improved conversion by 12%, so we shipped it to everyone.',}+const RECALCULATION = recalculationMocks(+ EXPERIMENT_STOPPED_WITH_CONCLUSION,+ resultsByMetricType(EXPERIMENT_STOPPED_WITH_CONCLUSION, { funnel: FUNNELS_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -34,6 +41,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_STOPPED_WITH_CONCLUSION.id}/`]:EXPERIMENT_STOPPED_WITH_CONCLUSION,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -44,14 +52,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, FUNNELS_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentStoppedWithLongConclusion.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentStoppedWithLongConclusion.stories.tsxindex d82027fae7d0..8630e1021649 100644--- a/frontend/src/scenes/experiments/stories/ExperimentStoppedWithLongConclusion.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentStoppedWithLongConclusion.stories.tsx@@ -9,6 +9,8 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport FUNNELS_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'+const LONG_CONCLUSION_COMMENT = ['We shipped the test variant on qualitative feedback rather than on a measured lift.','The primary metric moved by a small amount that never reached significance, and the secondary metrics disagreed with each other about the direction of the effect.',@@ -32,6 +34,11 @@ const EXPERIMENT_STOPPED_WITH_LONG_CONCLUSION = {conclusion_comment: LONG_CONCLUSION_COMMENT,}+const RECALCULATION = recalculationMocks(+ EXPERIMENT_STOPPED_WITH_LONG_CONCLUSION,+ resultsByMetricType(EXPERIMENT_STOPPED_WITH_LONG_CONCLUSION, { funnel: FUNNELS_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -50,6 +57,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_STOPPED_WITH_LONG_CONCLUSION.id}/`]:EXPERIMENT_STOPPED_WITH_LONG_CONCLUSION,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -61,14 +69,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, FUNNELS_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsxindex 05f33fd844dc..cde06917c308 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx@@ -9,6 +9,13 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport FUNNELS_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_FUNNEL_METRIC,+ resultsByMetricType(EXPERIMENT_WITH_FUNNEL_METRIC, { funnel: FUNNELS_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -27,6 +34,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_FUNNEL_METRIC.id}/`]:EXPERIMENT_WITH_FUNNEL_METRIC,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -36,14 +44,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, FUNNELS_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsxindex cff594b56bbf..8e077b68ecee 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsx@@ -12,6 +12,8 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'+const EXPERIMENT_WITH_HEALTH_FINDINGS = {...EXPERIMENT_WITH_MEAN_METRIC,health: {@@ -58,6 +60,11 @@ const EXPOSURES_WITH_BIAS_RISK = {],}+const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_HEALTH_FINDINGS,+ resultsByMetricType(EXPERIMENT_WITH_HEALTH_FINDINGS, { mean: MEAN_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -70,6 +77,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/`]:EXPERIMENT_WITH_HEALTH_FINDINGS,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -79,14 +87,13 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURES_WITH_BIAS_RISK]- }-- return [200, MEAN_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery+ ? [200, EXPOSURES_WITH_BIAS_RISK]+ : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithLongFlagKey.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithLongFlagKey.stories.tsxindex 2b0a09634844..bd88206228ac 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithLongFlagKey.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithLongFlagKey.stories.tsx@@ -9,6 +9,8 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport FUNNELS_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'+const EXPERIMENT_WITH_LONG_FLAG_KEY = {...EXPERIMENT_WITH_FUNNEL_METRIC,feature_flag: {@@ -17,6 +19,11 @@ const EXPERIMENT_WITH_LONG_FLAG_KEY = {},}+const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_LONG_FLAG_KEY,+ resultsByMetricType(EXPERIMENT_WITH_LONG_FLAG_KEY, { funnel: FUNNELS_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -35,6 +42,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_LONG_FLAG_KEY.id}/`]:EXPERIMENT_WITH_LONG_FLAG_KEY,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -44,14 +52,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, FUNNELS_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsxindex 31efb8d56a9e..e5fc33976302 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx@@ -10,6 +10,13 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_MEAN_METRIC,+ resultsByMetricType(EXPERIMENT_WITH_MEAN_METRIC, { mean: MEAN_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -22,6 +29,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/`]: EXPERIMENT_WITH_MEAN_METRIC,[`/api/projects/:team_id/experiment_holdouts`]: [],[`/api/projects/:team_id/experiment_saved_metrics/`]: [],@@ -30,14 +38,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, MEAN_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMultiStepFunnelMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMultiStepFunnelMetric.stories.tsxindex 32fc262523c9..4b3ff27bbf7f 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithMultiStepFunnelMetric.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMultiStepFunnelMetric.stories.tsx@@ -9,6 +9,13 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport FUNNELS_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result_multi_step.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_MULTI_STEP_FUNNEL_METRIC,+ resultsByMetricType(EXPERIMENT_WITH_MULTI_STEP_FUNNEL_METRIC, { funnel: FUNNELS_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -27,6 +34,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MULTI_STEP_FUNNEL_METRIC.id}/`]:EXPERIMENT_WITH_MULTI_STEP_FUNNEL_METRIC,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -38,14 +46,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, FUNNELS_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsxindex 3b63b6289cc1..4efffca124e9 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx@@ -10,12 +10,18 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport FUNNEL_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result.json'import MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'import RATIO_METRIC_RESULT from '~/mocks/fixtures/api/experiments/ratio_metric_result.json'-import {- NodeKind,- isExperimentFunnelMetric,- isExperimentMeanMetric,- isExperimentRatioMetric,-} from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'++import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_MULTIPLE_METRICS,+ resultsByMetricType(EXPERIMENT_WITH_MULTIPLE_METRICS, {+ mean: MEAN_METRIC_RESULT,+ funnel: FUNNEL_METRIC_RESULT,+ ratio: RATIO_METRIC_RESULT,+ })+)const meta: Meta = {component: App,@@ -29,6 +35,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MULTIPLE_METRICS.id}/`]:EXPERIMENT_WITH_MULTIPLE_METRICS,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -39,20 +46,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- if (isExperimentFunnelMetric(body.query.metric)) {- return [200, FUNNEL_METRIC_RESULT]- } else if (isExperimentMeanMetric(body.query.metric)) {- return [200, MEAN_METRIC_RESULT]- } else if (isExperimentRatioMetric(body.query.metric)) {- return [200, RATIO_METRIC_RESULT]- }+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsxindex 210064807889..453dd9a2d928 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx@@ -10,12 +10,18 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport FUNNEL_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result.json'import MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'import RATIO_METRIC_RESULT from '~/mocks/fixtures/api/experiments/ratio_metric_result.json'-import {- NodeKind,- isExperimentFunnelMetric,- isExperimentMeanMetric,- isExperimentRatioMetric,-} from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'++import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_MULTIPLE_METRICS_REORDERED,+ resultsByMetricType(EXPERIMENT_WITH_MULTIPLE_METRICS_REORDERED, {+ mean: MEAN_METRIC_RESULT,+ funnel: FUNNEL_METRIC_RESULT,+ ratio: RATIO_METRIC_RESULT,+ })+)const meta: Meta = {component: App,@@ -29,6 +35,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MULTIPLE_METRICS_REORDERED.id}/`]:EXPERIMENT_WITH_MULTIPLE_METRICS_REORDERED,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -40,20 +47,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- if (isExperimentFunnelMetric(body.query.metric)) {- return [200, FUNNEL_METRIC_RESULT]- } else if (isExperimentMeanMetric(body.query.metric)) {- return [200, MEAN_METRIC_RESULT]- } else if (isExperimentRatioMetric(body.query.metric)) {- return [200, RATIO_METRIC_RESULT]- }+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsxindex e493119d419e..585bc99491df 100644--- a/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx@@ -10,6 +10,13 @@ import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_queimport RATIO_METRIC_RESULT from '~/mocks/fixtures/api/experiments/ratio_metric_result.json'import { NodeKind } from '~/queries/schema/schema-general'+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'++const RECALCULATION = recalculationMocks(+ EXPERIMENT_WITH_RATIO_METRIC,+ resultsByMetricType(EXPERIMENT_WITH_RATIO_METRIC, { ratio: RATIO_METRIC_RESULT })+)+const meta: Meta = {component: App,title: 'Scenes-App/Experiments',@@ -22,6 +29,7 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ ...RECALCULATION.get,[`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_RATIO_METRIC.id}/`]:EXPERIMENT_WITH_RATIO_METRIC,[`/api/projects/:team_id/experiment_holdouts`]: [],@@ -31,14 +39,11 @@ const meta: Meta = {[`/api/environments/:team_id/default_release_conditions/`]: [],},post: {+ ...RECALCULATION.post,+ // Exposures still load through experimentLogic; metric results come from the recalculation run.'/api/environments/:team_id/query/:kind': async ({ request }) => {const body = (await request.json()) as Record<string, any>-- if (body.query.kind === NodeKind.ExperimentExposureQuery) {- return [200, EXPOSURE_QUERY_RESULT]- }-- return [200, RATIO_METRIC_RESULT]+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]},},}),diff --git a/frontend/src/scenes/experiments/stories/recalculationMocks.ts b/frontend/src/scenes/experiments/stories/recalculationMocks.tsnew file mode 100644index 000000000000..b52407d862ba--- /dev/null+++ b/frontend/src/scenes/experiments/stories/recalculationMocks.ts@@ -0,0 +1,101 @@+import type { Mocks } from '~/mocks/utils'++import type {+ ExperimentMetricsRecalculationJobApi,+ ExperimentMetricsRecalculationLatestApi,+ ExperimentMetricsRecalculationRunApi,+ MetricRecalculationResultApi,+} from 'products/experiments/frontend/generated/api.schemas'++/** The parts of an experiment fixture the run reads: every metric uuid, inline and shared, in both sections. */+type ExperimentFixture = {+ id: number | string+ metrics?: { uuid?: string }[]+ metrics_secondary?: { uuid?: string }[]+ saved_metrics?: { query?: { uuid?: string } }[]+}++/** A result fixture is a cached experiment query response; `last_refresh` stamps the run's window. */+type ResultFixture = { last_refresh?: string | null } & Record<string, unknown>++const RUN_ID = 'storybook-recalculation'++type MetricType = 'mean' | 'funnel' | 'ratio'+type ExperimentWithMetricTypes = ExperimentFixture & {+ metrics?: { uuid?: string; metric_type?: string }[]+ metrics_secondary?: { uuid?: string; metric_type?: string }[]+}++/** Resolves each metric of the experiment to the result fixture for its metric type. */+export function resultsByMetricType(+ experiment: ExperimentWithMetricTypes,+ fixtures: Partial<Record<MetricType, ResultFixture>>+): (metricUuid: string) => ResultFixture | null {+ const metrics = [...(experiment.metrics ?? []), ...(experiment.metrics_secondary ?? [])]+ return (metricUuid) => {+ const metricType = metrics.find((metric) => metric.uuid === metricUuid)?.metric_type as MetricType | undefined+ return (metricType && fixtures[metricType]) || null+ }+}++export function recalculationMocks(+ experiment: ExperimentFixture,+ resultFor: (metricUuid: string) => ResultFixture | null+): Mocks {+ const metricUuids = [+ ...(experiment.metrics ?? []).map((metric) => metric.uuid),+ ...(experiment.metrics_secondary ?? []).map((metric) => metric.uuid),+ ...(experiment.saved_metrics ?? []).map((savedMetric) => savedMetric.query?.uuid),+ ].filter((uuid): uuid is string => !!uuid)++ const results: MetricRecalculationResultApi[] = metricUuids.map((metricUuid) => {+ const result = resultFor(metricUuid)+ return result+ ? { metric_uuid: metricUuid, status: 'completed', result, error_message: null }+ : { metric_uuid: metricUuid, status: 'failed', result: null, error_message: 'Metric failed to compute' }+ })+ const failedUuids = results.filter(({ status }) => status === 'failed').map(({ metric_uuid }) => metric_uuid)++ const queryTo =+ results+ .map(({ result }) => (result as ResultFixture | null)?.last_refresh ?? null)+ .filter((stamp): stamp is string => !!stamp)+ .sort()+ .at(-1) ?? null++ const run: ExperimentMetricsRecalculationRunApi = {+ id: RUN_ID,+ experiment_id: Number(experiment.id),+ status: failedUuids.length === metricUuids.length && metricUuids.length > 0 ? 'failed' : 'completed',+ total_metrics: metricUuids.length,+ completed_metrics: metricUuids.length - failedUuids.length,+ failed_metrics: failedUuids.length,+ metric_errors: Object.fromEntries(+ failedUuids.map((uuid) => [+ uuid,+ { step: 'calculate', message: 'Metric failed to compute', retriable: false },+ ])+ ),+ created_at: queryTo ?? new Date(0).toISOString(),+ started_at: queryTo,+ completed_at: queryTo,+ query_to: queryTo,+ metric_retries: {},+ results,+ rows_read: null,+ estimated_rows_total: null,+ }+ const latest: ExperimentMetricsRecalculationLatestApi = { ...run, active_run: null, result_source: 'recalculation' }+ const job: ExperimentMetricsRecalculationJobApi = { ...run, is_existing: true }+ const base = `/api/projects/:team_id/experiments/${experiment.id}/metrics_recalculation`++ return {+ get: {+ [`${base}/latest/`]: latest,+ [`${base}/:recalculationId/`]: run,+ },+ post: {+ [`${base}/`]: [201, job],+ },+ }+}diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex 8d2dce920a8e..ff64b549d5d6 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -33,7 +33,6 @@ import {getDisplayOrderedIndices,getEventCountQuery,getFunnelDropoffReason,- getOrderedMetricsWithResults,getSessionLinkabilityEventNames,isEvenlyDistributed,isLegacyExperiment,@@ -736,7 +735,7 @@ describe('hasLegacyMetrics', () => {})})-describe('getOrderedMetricsWithResults', () => {+describe('metricResults over inline and shared metrics', () => {const baseExperiment = {...experimentJson,metrics: [],@@ -767,7 +766,7 @@ describe('getOrderedMetricsWithResults', () => {const results = [mockResult({ result: 'data1' })]const errors = [null]- const ordered = getOrderedMetricsWithResults(experiment, results, errors, [], [], false)+ const ordered = metricResults(experiment)(results, errors, 'primary')expect(ordered).toHaveLength(1)expect(ordered[0].metric.uuid).toBe('metric-1')@@ -798,7 +797,7 @@ describe('getOrderedMetricsWithResults', () => {const results = [mockResult({ result: 'data1' }), mockResult({ result: 'data2' })]const errors = [null, null]- const ordered = getOrderedMetricsWithResults(experiment, results, errors, [], [], false)+ const ordered = metricResults(experiment)(results, errors, 'primary')expect(ordered).toHaveLength(2)expect(ordered[0].metric.uuid).toBe('metric-2')@@ -831,7 +830,7 @@ describe('getOrderedMetricsWithResults', () => {const results = [mockResult({ result: 'shared-data' })]const errors = [null]- const ordered = getOrderedMetricsWithResults(experiment, results, errors, [], [], false)+ const ordered = metricResults(experiment)(results, errors, 'primary')expect(ordered).toHaveLength(1)expect(ordered[0].metric.uuid).toBe('shared-uuid')@@ -874,22 +873,8 @@ describe('getOrderedMetricsWithResults', () => {const primaryResults = [mockResult({ result: 'primary-data' })]const secondaryResults = [mockResult({ result: 'secondary-data' })]- const primaryOrdered = getOrderedMetricsWithResults(- experiment,- primaryResults,- [null],- secondaryResults,- [null],- false- )- const secondaryOrdered = getOrderedMetricsWithResults(- experiment,- primaryResults,- [null],- secondaryResults,- [null],- true- )+ const primaryOrdered = metricResults(experiment)(primaryResults, [null], 'primary')+ const secondaryOrdered = metricResults(experiment)(secondaryResults, [null], 'secondary')expect(primaryOrdered).toHaveLength(1)expect(primaryOrdered[0].metric.uuid).toBe('primary-uuid')@@ -930,7 +915,7 @@ describe('getOrderedMetricsWithResults', () => {const results = [mockResult({ result: 'inline-data' }), mockResult({ result: 'shared-data' })]const errors = [null, null]- const ordered = getOrderedMetricsWithResults(experiment, results, errors, [], [], false)+ const ordered = metricResults(experiment)(results, errors, 'primary')expect(ordered).toHaveLength(2)expect(ordered[0].metric.uuid).toBe('shared-1')@@ -947,7 +932,7 @@ describe('getOrderedMetricsWithResults', () => {primary_metrics_ordered_uuids: [],}- const ordered = getOrderedMetricsWithResults(experiment, [], [], [], [], false)+ const ordered = metricResults(experiment)([], [], 'primary')expect(ordered).toEqual([])})@@ -966,7 +951,7 @@ describe('getOrderedMetricsWithResults', () => {primary_metrics_ordered_uuids: ['metric-1'],}- const ordered = getOrderedMetricsWithResults(experiment, [mockResult({})], [null], [], [], false)+ const ordered = metricResults(experiment)([mockResult({})], [null], 'primary')expect(ordered[0].metricIndex).toBe(0)})diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 13abe6e3b9af..1fbb83b6057b 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -1260,26 +1260,3 @@ export const metricResults =metricIndex: index,}))}--/**- * {@link metricResults} over both sections' arrays, picking one. Kept for the legacy per-metric- * results path and its selectors.- */-export function getOrderedMetricsWithResults(- experiment: Experiment,- primaryMetricsResults: CachedNewExperimentQueryResponse[],- primaryMetricsResultsErrors: any[],- secondaryMetricsResults: CachedNewExperimentQueryResponse[],- secondaryMetricsResultsErrors: any[],- isSecondary: boolean-): Array<{- metric: ExperimentMetric- result: any- error: any- displayIndex: number- metricIndex: number-}> {- return isSecondary- ? metricResults(experiment)(secondaryMetricsResults, secondaryMetricsResultsErrors, 'secondary')- : metricResults(experiment)(primaryMetricsResults, primaryMetricsResultsErrors, 'primary')-}diff --git a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsxindex 8c3014fc9205..71fa284d3d2d 100644--- a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx+++ b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx@@ -3,11 +3,9 @@ import { useActions, useAsyncActions, useValues } from 'kea'import { IconRefresh } from '@posthog/icons'import { LemonButton, lemonToast } from '@posthog/lemon-ui'-import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { Spinner } from 'lib/lemon-ui/Spinner'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { experimentLogic, previousRefreshAnalytics } from 'scenes/experiments/experimentLogic'import { experimentMetricsLogic } from 'scenes/experiments/experimentMetricsLogic'@@ -57,7 +55,7 @@ function RefreshButton({)}-function RecalculationRefreshButton({ experiment }: { experiment: Experiment }): JSX.Element {+export function ExperimentRefreshButton({ experiment }: { experiment: Experiment }): JSX.Element {const metricsLogic = experimentMetricsLogic({ experiment })const {isRecalculating,@@ -100,44 +98,3 @@ function RecalculationRefreshButton({ experiment }: { experiment: Experiment }):/>)}--function LegacyRefreshButton({ experiment }: { experiment: Experiment }): JSX.Element {- const {- primaryMetricsResults,- secondaryMetricsResults,- primaryMetricsResultsLoading,- secondaryMetricsResultsLoading,- exposuresLoading,- currentRefresh,- } = useValues(experimentLogic)- const { reportExperimentMetricsRefreshed } = useActions(experimentLogic)- const { refreshExperimentResults } = useAsyncActions(experimentLogic)-- const lastRefresh = primaryMetricsResults?.[0]?.last_refresh || secondaryMetricsResults?.[0]?.last_refresh || null-- return (- <RefreshButton- isRefreshing={primaryMetricsResultsLoading || secondaryMetricsResultsLoading || exposuresLoading}- lastRefresh={lastRefresh}- onRefresh={() => {- reportExperimentMetricsRefreshed(experiment, true, {- triggered_by: 'manual',- ...previousRefreshAnalytics(currentRefresh),- })- void refreshExperimentResults(true, 'manual').catch(() => {- lemonToast.error('Could not refresh results. Try again.')- })- }}- />- )-}--export function ExperimentRefreshButton({ experiment }: { experiment: Experiment }): JSX.Element {- const { featureFlags } = useValues(featureFlagLogic)-- return featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION] ? (- <RecalculationRefreshButton experiment={experiment} />- ) : (- <LegacyRefreshButton experiment={experiment} />- )-}diff --git a/products/experiments/frontend/components/SummarizeExperimentButton.tsx b/products/experiments/frontend/components/SummarizeExperimentButton.tsxindex 9e9e137adf04..f3b5470937e8 100644--- a/products/experiments/frontend/components/SummarizeExperimentButton.tsx+++ b/products/experiments/frontend/components/SummarizeExperimentButton.tsx@@ -6,7 +6,7 @@ import { IconSparkles } from '@posthog/icons'import { Tooltip } from '@posthog/lemon-ui'import { addProductIntent } from 'lib/utils/product-intents'-import { experimentLogic } from 'scenes/experiments/experimentLogic'+import { experimentLogic, getSectionMetricUuids } from 'scenes/experiments/experimentLogic'import { useMaxTool } from 'scenes/max/useMaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'@@ -26,7 +26,7 @@ interface MinimalExperimentSummaryContext {}function useExperimentSummaryMaxTool(): ReturnType<typeof useMaxTool> {- const { experiment, orderedPrimaryMetricsWithResults } = useValues(experimentLogic)+ const { experiment } = useValues(experimentLogic)// Simplified context - backend will fetch full data using experiment_idconst maxToolContext = useMemo(@@ -38,10 +38,10 @@ function useExperimentSummaryMaxTool(): ReturnType<typeof useMaxTool> {)const shouldShowMaxSummaryTool = useMemo(() => {- const hasResults = orderedPrimaryMetricsWithResults.length > 0+ const hasPrimaryMetrics = getSectionMetricUuids(experiment, false).length > 0const hasStarted = isLaunched(experiment)- return hasResults && hasStarted- }, [orderedPrimaryMetricsWithResults, experiment.status, experiment.start_date, experiment.end_date, experiment]) //eslint-disable-line react-hooks/exhaustive-deps+ return hasPrimaryMetrics && hasStarted+ }, [experiment])const maxToolResult = useMaxTool({identifier: 'experiment_results_summary',diff --git a/products/experiments/frontend/constants.ts b/products/experiments/frontend/constants.tsindex 58015733d09f..beb01190e351 100644--- a/products/experiments/frontend/constants.ts+++ b/products/experiments/frontend/constants.ts@@ -48,12 +48,6 @@ export const MAX_LOOKBACK_DAYS = 30export const DEFAULT_MDE = 30-// Autorefresh constants-// While a launched experiment is still gathering its first exposures, force refresh results on page-// load (queries are fast with little data and this is better UX to not let users wait until they see-// the experiment is working).-export const NEW_EXPERIMENT_FORCE_REFRESH_AFTER_MINUTES = 1-// Mirrors EXPERIMENT_RECALCULATION_MAX_AGE_DAYS in posthog/temporal/experiments/activities.pyexport const EXPERIMENT_RECALCULATION_MAX_AGE_DAYS = 60diff --git a/products/experiments/frontend/health/experimentHealthDebugLogic.ts b/products/experiments/frontend/health/experimentHealthDebugLogic.tsindex 073d9930c3c5..0e07ea36eb48 100644--- a/products/experiments/frontend/health/experimentHealthDebugLogic.ts+++ b/products/experiments/frontend/health/experimentHealthDebugLogic.ts@@ -1,9 +1,14 @@import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'-import { type ExperimentLogicProps, type ExperimentWarning, experimentLogic } from 'scenes/experiments/experimentLogic'+import {+ type ExperimentLogicProps,+ type ExperimentWarning,+ experimentLogic,+ getSectionMetricUuids,+} from 'scenes/experiments/experimentLogic'import { resolveMultipleVariantHandling } from 'scenes/experiments/utils'-import type { ExperimentExposureCriteria, ExperimentMetricUnion } from '~/queries/schema/schema-general'+import type { ExperimentExposureCriteria } from '~/queries/schema/schema-general'import type { Experiment, ExperimentIdType } from '~/types'import {@@ -28,20 +33,6 @@ export interface experimentHealthDebugLogicValues {exposuresLoading: boolean // experimentLogichealthFindings: HealthPanelFinding[] | null // experimentLogicisExperimentDraft: boolean // experimentLogic- orderedPrimaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[] // experimentLogic- orderedSecondaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[] // experimentLogichealthDebugChecks: HealthDebugCheck[]healthDebugFacts: HealthDebugFact[]pageMetricCounts: HealthDebugInput['pageMetricCounts']@@ -51,22 +42,7 @@ export interface experimentHealthDebugLogicValues {export interface experimentHealthDebugLogicMeta {key: ExperimentIdType__keaTypeGenInternalSelectorTypes: {- pageMetricCounts: (- orderedPrimaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[],- orderedSecondaryMetricsWithResults: {- displayIndex: number- error: any- metric: ExperimentMetricUnion- metricIndex: number- result: any- }[]- ) => HealthDebugInput['pageMetricCounts']+ pageMetricCounts: (experiment: Experiment) => HealthDebugInput['pageMetricCounts']healthDebugChecks: (experiment: Experiment,healthFindings: HealthPanelFinding[] | null,@@ -117,18 +93,16 @@ export const experimentHealthDebugLogic = kea<experimentHealthDebugLogicType>(['exposuresLoading','exposureCriteria','isExperimentDraft',- 'orderedPrimaryMetricsWithResults',- 'orderedSecondaryMetricsWithResults','experimentLoadCount',],],})),selectors({pageMetricCounts: [- (s) => [s.orderedPrimaryMetricsWithResults, s.orderedSecondaryMetricsWithResults],- (primary: unknown[], secondary: unknown[]): HealthDebugInput['pageMetricCounts'] => ({- primary: primary.length,- secondary: secondary.length,+ (s) => [s.experiment],+ (experiment: Experiment): HealthDebugInput['pageMetricCounts'] => ({+ primary: getSectionMetricUuids(experiment, false).length,+ secondary: getSectionMetricUuids(experiment, true).length,}),],healthDebugChecks: [