: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): defend against race condition when evaluating feature flags on the experiment logic (#95270)
Rodrigo Ilorod8bc95e1ab41
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 0e2eb266964e..9bc78a898fc0 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -3,6 +3,7 @@ import { api } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'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'@@ -105,6 +106,10 @@ 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()@@ -277,6 +282,35 @@ describe('experimentLogic', () => {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',+ ])+ })})describe('updateExperimentMetrics', () => {diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 9d365de7ab20..25ffb38044c6 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -524,6 +524,7 @@ export interface experimentLogicValues {defaultMinimumDetectableEffect: number // experimentsConfigLogicexperimentsConfig: ExperimentsConfig | null // experimentsConfigLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic+ receivedFeatureFlags: boolean // featureFlagLogicconversionMetrics: FunnelTimeConversionMetrics // funnelDataLogicfunnelResults: FunnelResultType // funnelDataLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel@@ -783,6 +784,13 @@ export interface experimentLogicActions {} // eventUsageLogicaddToExperiments: (experiment: Experiment) => Experiment // experimentsLogicupdateExperiments: (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@@ -1344,7 +1352,11 @@ export interface experimentLogicActions {uuid: string,attributionType: BreakdownAttributionType,attributionValue?: number- ) => { attributionType: BreakdownAttributionType; attributionValue: number | undefined; uuid: string }+ ) => {+ attributionType: BreakdownAttributionType+ attributionValue: number | undefined+ uuid: string+ }updateMetricBreakdownLimit: (uuid: string,breakdownLimit: number@@ -1481,7 +1493,7 @@ export const experimentLogic = kea<experimentLogicType>([groupsModel,['aggregationLabel', 'groupTypes', 'showGroupsOptions'],featureFlagLogic,- ['featureFlags'],+ ['featureFlags', 'receivedFeatureFlags'],holdoutsLogic,['holdouts'],billingLogic,@@ -1526,6 +1538,8 @@ export const experimentLogic = kea<experimentLogicType>([],teamLogic,['addProductIntent'],+ featureFlagLogic,+ ['setFeatureFlags'],featureFlagsLogic,['updateFlagFromPartial'],modalsLogic,@@ -2768,6 +2782,14 @@ 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+ }+const refreshId = generateRefreshId()const refreshStart = performance.now()const summaries: MetricLoadingSummary[] = []@@ -2912,6 +2934,15 @@ export const experimentLogic = kea<experimentLogicType>([}}},+ 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)+ }+ },updateExperimentMetrics: async () => {actions.updateExperiment({metrics: values.experiment.metrics,diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex c10b79097c43..f25eda069bb4 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -1108,6 +1108,40 @@ describe('experimentMetricsLogic', () => {})})+ describe('feature flags unresolved 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)+ })+ })+describe('queuedRerun reducer', () => {beforeEach(() => {mountLogic()diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex 5fb416ec24fb..0dbe421b216e 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -155,6 +155,7 @@ const resolveErrorByUuid = (recalculation: ExperimentMetricsRecalculationApi): R// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentMetricsLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic+ receivedFeatureFlags: boolean // featureFlagLogiccurrentProjectId: number | null // projectLogiccurrentRecalculation: ExperimentMetricsRecalculationApi | nullisMetricRecalculating: (metricUuid: string | undefined) => boolean@@ -234,6 +235,13 @@ export interface experimentMetricsLogicActions {}status: 'completed' | 'failed' | 'triggered'} // eventUsageLogic+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogicloadLatestRecalculation: () => {value: true}@@ -307,8 +315,8 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([key((props) => props.experiment.id),path((key) => ['scenes', 'experiment', 'experimentMetricsLogic', String(key)]),connect(() => ({- values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],- actions: [eventUsageLogic, ['reportExperimentMetricRecalculation']],+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags', 'receivedFeatureFlags']],+ actions: [eventUsageLogic, ['reportExperimentMetricRecalculation'], featureFlagLogic, ['setFeatureFlags']],})),actions({setCurrentRecalculation: (recalculation: ExperimentMetricsRecalculationApi | null) => ({ recalculation }),@@ -604,6 +612,19 @@ 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+ }/*** bail if feature not enabled. Clear recalculation loading state*/@@ -699,6 +720,14 @@ 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()+ }+ },triggerRecalculation: async ({ trigger }) => {/*** bail if feature not enabled