Skip to content

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

fix(experiments): re-run metric loads when recalc flag resolves late (#96525)

Juraj Majerike421e65fd52a
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 35a3fb1a1e98..5e4a8c441a03 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -2,6 +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 { userLogic } from 'scenes/userLogic'
@@ -311,6 +312,49 @@ describe('experimentLogic', () => {
'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'])
+ })
})
describe('updateExperimentMetrics', () => {
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 25ffb38044c6..9ed149b52602 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -2790,6 +2790,10 @@ export const experimentLogic = kea<experimentLogicType>([
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[] = []
@@ -2941,6 +2945,18 @@ export const experimentLogic = kea<experimentLogicType>([
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 () => {
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
index 3578cc896f52..93ab2d007afb 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
@@ -1233,7 +1233,7 @@ describe('experimentMetricsLogic', () => {
})
})
- describe('feature flags unresolved on mount', () => {
+ 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.
@@ -1265,6 +1265,39 @@ describe('experimentMetricsLogic', () => {
}).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', () => {
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index 2cd6c9a18d55..9acb05cd6cd3 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -641,6 +641,8 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
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
*/
@@ -751,6 +753,18 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
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()
}
},
triggerRecalculation: async ({ trigger }) => {