: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
fix(experiments): stop duration pending flashing while estimate loads (#110540)
Juraj Majerik48bf2bfaeea6
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.tsindex b495af6c099b..805357686f26 100644--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts@@ -2,13 +2,16 @@ 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'import { Experiment } from '~/types'import { experimentLogic } from '../experimentLogic'+import { experimentMetricsLogic } from '../experimentMetricsLogic'import { runningTimeLogic } from './runningTimeLogic'jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({@@ -168,4 +171,58 @@ describe('runningTimeLogic', () => {expect(experimentLogicInstance.values.unmodifiedExperiment?.version).toEqual(9)})})++ describe('isCalculating', () => {+ it('stays true while the automatic estimate is in flight, then settles on success', async () => {+ let resolveCalc: (value: unknown) => void = () => {}+ calculateRunningTimeMock.mockReturnValue(+ new Promise((resolve) => {+ resolveCalc = resolve+ })+ )+ api.update.mockResolvedValue({ ...experiment, version: 4 })++ logic = runningTimeLogic({ experiment })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadAutomaticCalculation'])+ expect(logic.values.isCalculating).toBe(true)++ resolveCalc({ recommended_sample_size: 2000, recommended_running_time_days: 20 })+ await expectLogic(logic).toDispatchActions(['loadAutomaticCalculationSuccess']).toFinishAllListeners()+ expect(logic.values.isCalculating).toBe(false)+ })++ it('clears calculating when the automatic estimate request fails', async () => {+ // A failed request leaves the result null for good, so calculating must still settle —+ // otherwise the meta bar hangs on "Calculating…" instead of showing a resting state.+ calculateRunningTimeMock.mockRejectedValue(new Error('backend unavailable'))++ logic = runningTimeLogic({ experiment })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadAutomaticCalculationFailure']).toFinishAllListeners()+ 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,+ })+ const metricsLogicInstance = experimentMetricsLogic({ experiment })+ metricsLogicInstance.mount()++ logic = runningTimeLogic({ experiment })+ logic.mount()++ 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 da5ad7d0db53..1a3370f5ba5e 100644--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts@@ -69,6 +69,7 @@ export interface runningTimeLogicValues {}[] // experimentLogicprimaryMetricsResultsLoading: boolean // experimentLogicunmodifiedExperiment: Experiment | null // experimentLogic+ isRecalculating: boolean // experimentMetricsLogicrecalcPrimaryMetricsResults: CachedNewExperimentQueryResponse[] // experimentMetricsLogicrecalcPrimaryMetricsResultsErrors: (unknown | null)[] // experimentMetricsLogicdefaultMinimumDetectableEffect: number // experimentsConfigLogic@@ -82,6 +83,7 @@ export interface runningTimeLogicValues {currentExposures: number | nulldailyExposureRate: number | nullinitialConfig: RunningTimeConfig+ isCalculating: booleanisComplete: booleanisManualMode: booleanisSaving: boolean@@ -249,6 +251,13 @@ export interface runningTimeLogicMeta {experiment: Experiment) => number | nullisComplete: (currentExposures: number | null, targetSampleSize: number | null) => boolean+ isCalculating: (+ isManualMode: boolean,+ featureFlags: FeatureFlagsSet,+ primaryMetricsResultsLoading: boolean,+ isRecalculating: boolean,+ automaticCalculationLoading: boolean+ ) => booleanmanualFormPreview: (manualPreviewInput: RunningTimeCalculationInputApi | null,manualPreview: ManualPreview@@ -285,6 +294,7 @@ export const runningTimeLogic = kea<runningTimeLogicType>([['primaryMetricsResults as recalcPrimaryMetricsResults','primaryMetricsResultsErrors as recalcPrimaryMetricsResultsErrors',+ 'isRecalculating',],modalsLogic,['isRunningTimeConfigModalOpen'],@@ -571,6 +581,36 @@ export const runningTimeLogic = kea<runningTimeLogicType>([(current: number | null, target: number | null): boolean =>current !== null && target !== null && current >= target,],+ // True while the estimate is still resolving: metric results loading or the automatic calculation+ // request in flight. Lets the UI distinguish "still loading" from "settled but can't estimate"+ // 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 => {+ 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+ },+ ],manualFormPreview: [(s) => [s.manualPreviewInput, s.manualPreview],(input: RunningTimeCalculationInputApi | null, preview: ManualPreview): ManualPreview =>diff --git a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRemainingTime.tsx b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRemainingTime.tsxindex fa0145b8bdf2..4ccb0fdde6b9 100644--- a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRemainingTime.tsx+++ b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRemainingTime.tsx@@ -17,22 +17,16 @@ export function ExperimentRemainingTime({experiment: ExperimentonConfigure: () => void}): JSX.Element {- const {- remainingDays,- currentExposures,- targetSampleSize,- isComplete,- isManualMode,- primaryMetricsResultsLoading,- } = useValues(runningTimeLogic({ experiment }))+ const { remainingDays, currentExposures, targetSampleSize, isComplete, isCalculating } = useValues(+ runningTimeLogic({ experiment })+ )const launched = isLaunched(experiment)- const isLoading = primaryMetricsResultsLoading && !isManualModeconst showProgress = currentExposures !== null && targetSampleSize !== nullconst days = remainingDays === null ? null : Math.ceil(remainingDays)let content: JSX.Element- if (isLoading) {+ if (isCalculating) {content = <span className="text-secondary">Calculating…</span>} else if (days === null) {content = <span className="text-secondary">{launched ? 'Duration pending' : 'Duration not estimated'}</span>