Skip to content

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

feat(experiments): block manual metric reloads for five minutes after the latest run (#112207)

Rodrigo Iloro5805c3030ca3
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
index f7fd5b4fe70a..35fa12a36cff 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
@@ -4,8 +4,10 @@ import { lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { preflightLogic } from 'lib/logic/preflightLogic'
import { projectLogic } from 'scenes/projectLogic'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -133,6 +135,8 @@ describe('experimentMetricsLogic', () => {
// Default handlers so every afterMount-driven load/trigger has a mock; tests override per-case.
useMocks({
get: {
+ // The fixture is a dev preflight, which never blocks a reload; the window tests need production.
+ '/_preflight': [200, { ...preflightJson, is_debug: false }],
'/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [404, {}],
},
post: {
@@ -715,23 +719,19 @@ describe('experimentMetricsLogic', () => {
it('clears the recalculating marks when the create request is rejected', async () => {
// The marks are set before the POST so the shown values read as refreshing; a rejected POST
- // (a 429 from the refresh window, or any error) never reaches the poll that would clear them.
+ // never reaches the poll that would clear them. A 429 takes the window path, tested below. The
+ // latest run finished outside the window, so the manual trigger is not blocked locally.
useMocks({
get: {
'/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
200,
- completedRecalculation,
- ],
- },
- post: {
- '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
- 429,
{
- code: 'recalculation_rate_limited',
- detail: 'Metrics were recalculated less than 5 minutes ago.',
+ ...completedRecalculation,
+ completed_at: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
},
],
},
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [500, {}] },
})
mountLogic()
await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
@@ -745,7 +745,7 @@ describe('experimentMetricsLogic', () => {
expect(logic.values.recalculatingMetricUuids).toEqual([])
expect(logic.values.isRecalculating).toBe(false)
- expect(lemonToast.error).toHaveBeenCalledWith('Metrics were recalculated less than 5 minutes ago.')
+ expect(lemonToast.error).toHaveBeenCalledWith('Failed to trigger metrics recalculation')
})
it('keeps the marks of a run already being polled when a retry request is rejected', async () => {
@@ -762,15 +762,7 @@ describe('experimentMetricsLogic', () => {
{ ...pendingRecalculation, id: 'recalc-2', status: 'in_progress' },
],
},
- post: {
- '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
- 429,
- {
- code: 'recalculation_rate_limited',
- detail: 'Metrics were recalculated less than 5 minutes ago.',
- },
- ],
- },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [500, {}] },
})
// Real timers: the poll's first tick is two seconds out, and the by-id mock stays in progress with
// no results, so a tick that lands keeps the marks either way.
@@ -791,7 +783,7 @@ describe('experimentMetricsLogic', () => {
])
expect(logic.values.recalculatingMetricUuids).toContain(PRIMARY_METRIC_UUID)
- expect(lemonToast.error).toHaveBeenCalledWith('Metrics were recalculated less than 5 minutes ago.')
+ expect(lemonToast.error).toHaveBeenCalledWith('Failed to trigger metrics recalculation')
})
it('does not restore marks a completed poll already cleared while the retry request was pending', async () => {
@@ -832,6 +824,160 @@ describe('experimentMetricsLogic', () => {
expect(logic.values.recalculatingMetricUuids).toEqual([])
})
+ describe('manual refresh window', () => {
+ // query_to stays old, as on a stopped experiment, so the window can only come from completed_at.
+ const finishedMinutesAgo = <T extends object>(
+ latest: T,
+ minutesAgo: number
+ ): T & { completed_at: string } => ({
+ ...latest,
+ completed_at: new Date(Date.now() - minutesAgo * 60 * 1000).toISOString(),
+ })
+
+ it.each([
+ {
+ name: 'blocks a manual reload inside the window',
+ latest: completedRecalculation,
+ trigger: 'manual',
+ minutesAgo: 2,
+ blocked: true,
+ },
+ {
+ name: 'allows a manual reload after the window',
+ latest: completedRecalculation,
+ trigger: 'manual',
+ minutesAgo: 6,
+ blocked: false,
+ },
+ {
+ name: 'lets a heal through inside the window',
+ latest: completedRecalculation,
+ trigger: 'heal_latest_run',
+ minutesAgo: 2,
+ blocked: true,
+ },
+ {
+ // The fallback is not a run: a fresh timeseries point must not block the first recalculation.
+ name: 'never blocks on a timeseries fallback',
+ latest: completeTimeseriesFallbackRecalculation,
+ trigger: 'manual',
+ minutesAgo: 2,
+ blocked: false,
+ },
+ {
+ name: 'never blocks after a failed run',
+ latest: partialFailureRecalculation,
+ trigger: 'manual',
+ minutesAgo: 2,
+ blocked: false,
+ },
+ ] as const)('$name', async ({ latest, trigger, minutesAgo, blocked }) => {
+ const posts = !(blocked && trigger === 'manual')
+ const createMock = jest.fn(() => [201, pendingRecalculation])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ finishedMinutesAgo(latest, minutesAgo),
+ ],
+ },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ mountLogic()
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+ expect(logic.values.isManualRefreshBlocked).toBe(blocked)
+
+ await expectLogic(logic, () => {
+ logic.actions.triggerRecalculation(trigger)
+ }).toFinishAllListeners()
+ expect(createMock.mock.calls.length > 0).toBe(posts)
+ })
+
+ it('never blocks a reload in local development', async () => {
+ const createMock = jest.fn(() => [201, pendingRecalculation])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ finishedMinutesAgo(completedRecalculation, 2),
+ ],
+ },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ // The mount-time preflight load must land first, or it overwrites the dev preflight.
+ await expectLogic(preflightLogic).toDispatchActions(['loadPreflightSuccess'])
+ preflightLogic.actions.loadPreflightSuccess({ ...preflightJson, is_debug: true } as any)
+ mountLogic()
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+ expect(logic.values.isManualRefreshBlocked).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.triggerRecalculation('manual')
+ }).toFinishAllListeners()
+ expect(createMock).toHaveBeenCalled()
+ })
+
+ it('syncs the window and informs the user when the backend answers 429', async () => {
+ // The local window was open (an old run), but another tab or an agent used the window first.
+ const latestCalls: number[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => {
+ latestCalls.push(1)
+ return [200, finishedMinutesAgo(completedRecalculation, 10)]
+ },
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': () => [
+ 429,
+ {
+ code: 'recalculation_rate_limited',
+ detail: 'Metrics were recalculated less than 5 minutes ago.',
+ },
+ ],
+ },
+ })
+ mountLogic()
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+ expect(logic.values.isManualRefreshBlocked).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.triggerRecalculation('manual')
+ })
+ .toDispatchActions(['triggerRecalculation', 'loadLatestRecalculation'])
+ .toFinishAllListeners()
+
+ expect(latestCalls).toHaveLength(2)
+ expect(lemonToast.info).toHaveBeenCalledWith('Metrics were recalculated less than 5 minutes ago.')
+ expect(lemonToast.error).not.toHaveBeenCalled()
+ expect(logic.values.isRecalculating).toBe(false)
+ })
+
+ it('unblocks the reload button when the window closes, without a new load', async () => {
+ jest.useFakeTimers()
+ try {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ finishedMinutesAgo(completedRecalculation, 4),
+ ],
+ },
+ })
+ mountLogic()
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
+ expect(logic.values.isManualRefreshBlocked).toBe(true)
+
+ await expectLogic(logic, () => {
+ jest.advanceTimersByTime(60 * 1000 + 200)
+ }).toDispatchActions(['recheckRefreshEligibility'])
+ expect(logic.values.isManualRefreshBlocked).toBe(false)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+ })
+
describe('queuing', () => {
it('queues instead of posting when a run is active', async () => {
const createMock = jest.fn(() => [201, pendingRecalculation])
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index fd849967a4ea..ad478f8dba0e 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -4,7 +4,9 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
+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'
@@ -20,6 +22,7 @@ import {
} from 'products/experiments/frontend/generated/api'
import type {
ExperimentMetricsRecalculationJobApi,
+ ExperimentMetricsRecalculationLatestApi,
ExperimentMetricsRecalculationRequestTriggerEnumApi,
ExperimentMetricsRecalculationRunApi,
ResultSourceEnumApi,
@@ -51,7 +54,8 @@ function reportExperimentMetricRecalculation(
export type RecalculationPayload = Omit<ExperimentMetricsRecalculationJobApi, 'is_existing'> &
Partial<
Pick<ExperimentMetricsRecalculationRunApi, 'metric_retries' | 'results' | 'rows_read' | 'estimated_rows_total'>
- >
+ > &
+ Partial<Pick<ExperimentMetricsRecalculationLatestApi, 'result_source'>>
/**
* This logic can only handle state when an experiment is present.
@@ -60,6 +64,9 @@ export interface ExperimentMetricsLogicProps {
experiment: Experiment
}
+// A manual reload inside this window after the latest completed run finished is blocked, the same five
+// minutes a dashboard waits between bulk refreshes. The backend applies the same window and returns that run.
+const MIN_MANUAL_REFRESH_INTERVAL_MINUTES = 5
const RECALCULATION_POLL_INTERVAL_MS = 2000
const MAX_POLL_RETRIES = 5
/**
@@ -214,8 +221,10 @@ const resolveErrorByUuid = (recalculation: RecalculationPayload): ResolveByUuid<
export interface experimentMetricsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
receivedFeatureFlags: boolean // featureFlagLogic
+ isDev: boolean | undefined // preflightLogic
currentProjectId: number | null // projectLogic
currentRecalculation: RecalculationPayload | null
+ isManualRefreshBlocked: boolean
isMetricRecalculating: (metricUuid: string | undefined) => boolean
isRecalculating: boolean
lastRefresh: string | null
@@ -225,6 +234,7 @@ export interface experimentMetricsLogicValues {
rowsRead: number
} | null
metricRetries: Record<string, MetricRetryInfo>
+ nextAllowedManualRefresh: string | null
nextRetryAt: string | null
primaryMetricsResults: CachedNewExperimentQueryResponse[]
primaryMetricsResultsErrors: (unknown | null)[]
@@ -236,6 +246,7 @@ export interface experimentMetricsLogicValues {
completed: number
total: number
}
+ refreshEligibilityTick: number
secondaryMetricsResults: CachedNewExperimentQueryResponse[]
secondaryMetricsResultsErrors: (unknown | null)[]
totalMetricsCount: number
@@ -256,6 +267,9 @@ export interface experimentMetricsLogicActions {
pollRecalculation: (recalculationId: string) => {
recalculationId: string
}
+ recheckRefreshEligibility: () => {
+ value: true
+ }
setCurrentRecalculation: (recalculation: RecalculationPayload | null) => {
recalculation: RecalculationPayload | null
}
@@ -296,6 +310,12 @@ export interface experimentMetricsLogicMeta {
}
totalMetricsCount: (arg: any) => number
lastRefresh: (currentRecalculation: RecalculationPayload | null) => string | null
+ nextAllowedManualRefresh: (currentRecalculation: RecalculationPayload | null) => string | null
+ isManualRefreshBlocked: (
+ nextAllowedManualRefresh: string | null,
+ refreshEligibilityTick: number,
+ isDev: boolean | undefined
+ ) => boolean
metricRetries: (currentRecalculation: RecalculationPayload | null) => Record<string, MetricRetryInfo>
nextRetryAt: (metricRetries: Record<string, MetricRetryInfo>) => string | null
recalculationDisplayState: (
@@ -318,7 +338,14 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
key((props) => props.experiment.id),
path((key) => ['scenes', 'experiment', 'experimentMetricsLogic', String(key)]),
connect(() => ({
- values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags', 'receivedFeatureFlags']],
+ values: [
+ projectLogic,
+ ['currentProjectId'],
+ featureFlagLogic,
+ ['featureFlags', 'receivedFeatureFlags'],
+ preflightLogic,
+ ['isDev'],
+ ],
actions: [featureFlagLogic, ['setFeatureFlags']],
})),
actions({
@@ -328,6 +355,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
trigger,
}),
pollRecalculation: (recalculationId: string) => ({ recalculationId }),
+ recheckRefreshEligibility: true,
setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),
setSecondaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),
setPrimaryMetricsResultsErrors: (errors: (unknown | null)[]) => ({ errors }),
@@ -352,6 +380,8 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
setCurrentRecalculation: () => false,
},
],
+ // Bumped when the manual refresh window closes, so isManualRefreshBlocked recomputes without new data.
+ refreshEligibilityTick: [0, { recheckRefreshEligibility: (state: number) => state + 1 }],
queuedRerun: [
null as ExperimentMetricsRecalculationRequestTriggerEnumApi | null,
{
@@ -441,6 +471,23 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
(s) => [s.currentRecalculation],
(recalc: RecalculationPayload | null): string | null => recalc?.query_to ?? null,
],
+ nextAllowedManualRefresh: [
+ (s) => [s.currentRecalculation],
+ // Only a completed run anchors the window: the timeseries fallback is not a run, and a failed
+ // run must stay reloadable. The window measures from completed_at, as the backend does.
+ (recalc: RecalculationPayload | null): string | null =>
+ recalc?.status === RECALCULATION_STATUSES.completed &&
+ recalc.result_source !== 'timeseries_fallback' &&
+ recalc.completed_at
+ ? dayjs(recalc.completed_at).add(MIN_MANUAL_REFRESH_INTERVAL_MINUTES, 'minutes').toISOString()
+ : null,
+ ],
+ isManualRefreshBlocked: [
+ (s) => [s.nextAllowedManualRefresh, s.refreshEligibilityTick, s.isDev],
+ // Local development skips the window, as the backend does, so a developer can reload at will.
+ (nextAllowedManualRefresh: string | null, _tick: number, isDev: boolean | undefined): boolean =>
+ !isDev && !!nextAllowedManualRefresh && dayjs(nextAllowedManualRefresh).isAfter(dayjs()),
+ ],
metricRetries: [
(s) => [s.currentRecalculation],
(recalc: RecalculationPayload | null): Record<string, MetricRetryInfo> => {
@@ -732,6 +779,21 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
actions.loadLatestRecalculation()
}
},
+ setCurrentRecalculation: () => {
+ // Re-enable the reload button the moment the window closes, not on the next data load.
+ cache.disposables.dispose('manualRefreshEligibility')
+ const nextAllowed = values.nextAllowedManualRefresh
+ if (!nextAllowed || !dayjs(nextAllowed).isAfter(dayjs())) {
+ return
+ }
+ cache.disposables.add(() => {
+ const timerId = setTimeout(
+ actions.recheckRefreshEligibility,
+ Math.max(0, dayjs(nextAllowed).diff(dayjs())) + 100
+ )
+ return () => clearTimeout(timerId)
+ }, 'manualRefreshEligibility')
+ },
triggerRecalculation: async ({ trigger }) => {
/**
* bail if feature not enabled
@@ -739,6 +801,9 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
if (!flagEnabled()) {
return
}
+ if (trigger === 'manual' && values.isManualRefreshBlocked) {
+ 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.
@@ -878,6 +943,13 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
actions.setRecalculatingMetricUuids(
values.recalculatingMetricUuids.filter((uuid) => previousRecalculatingMetricUuids.has(uuid))
)
+ if (error?.status === 429) {
+ // Another tab or an agent used the refresh window first. Reload the latest run so the
+ // button picks up its completed_at and shows when the next refresh is possible.
+ lemonToast.info(error?.detail || 'Metrics were recalculated less than 5 minutes ago.')
+ actions.loadLatestRecalculation()
+ return
+ }
lemonToast.error(error?.detail || 'Failed to trigger metrics recalculation')
} finally {
cache.createInFlight = false
diff --git a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx
index 906861acf0cf..3083b91f5230 100644
--- a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx
+++ b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx
@@ -4,6 +4,7 @@ import { IconRefresh } from '@posthog/icons'
import { LemonButton, lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { experimentLogic, previousRefreshAnalytics } from 'scenes/experiments/experimentLogic'
@@ -18,6 +19,7 @@ interface RefreshButtonProps {
lastRefresh: string | null
progress?: { completed: number; total: number }
queuedHint?: string
+ blockedReason?: string
onRefresh: () => void
}
@@ -26,6 +28,7 @@ function RefreshButton({
lastRefresh,
progress,
queuedHint,
+ blockedReason,
onRefresh,
}: RefreshButtonProps): JSX.Element {
const loadingText =
@@ -37,7 +40,7 @@ function RefreshButton({
size="xsmall"
icon={isRefreshing ? <Spinner textColored /> : <IconRefresh />}
onClick={onRefresh}
- disabledReason={isRefreshing ? (queuedHint ?? loadingText) : undefined}
+ disabledReason={isRefreshing ? (queuedHint ?? loadingText) : blockedReason}
aria-label={isRefreshing ? undefined : 'Refresh results'}
data-attr="refresh-experiment"
>
@@ -55,7 +58,14 @@ function RefreshButton({
function RecalculationRefreshButton({ experiment }: { experiment: Experiment }): JSX.Element {
const metricsLogic = experimentMetricsLogic({ experiment })
- const { isRecalculating, recalculationProgress, lastRefresh, queuedRerun } = useValues(metricsLogic)
+ const {
+ isRecalculating,
+ recalculationProgress,
+ lastRefresh,
+ queuedRerun,
+ isManualRefreshBlocked,
+ nextAllowedManualRefresh,
+ } = useValues(metricsLogic)
const { triggerRecalculation } = useActions(metricsLogic)
const { currentRefresh } = useValues(experimentLogic)
const { reportExperimentMetricsRefreshed } = useActions(experimentLogic)
@@ -67,6 +77,11 @@ function RecalculationRefreshButton({ experiment }: { experiment: Experiment }):
lastRefresh={lastRefresh}
progress={recalculationProgress}
queuedHint={queuedRerun ? 'Changes apply after the current recalculation finishes' : undefined}
+ blockedReason={
+ isManualRefreshBlocked && nextAllowedManualRefresh
+ ? `Next refresh possible ${dayjs(nextAllowedManualRefresh).fromNow()}`
+ : undefined
+ }
onRefresh={() => {
reportExperimentMetricsRefreshed(experiment, true, {
triggered_by: 'manual',