: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
feat(experiments): add second daily recalculation time picker (#108325)
Juraj Majerik16f3a5f9859b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9d82bd9d263a..c44431177e96 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11682,6 +11682,14 @@ snapshots:hash: v1.k794b7964.5389531656b98551428d0348f86123184edee37f4c3a32fdb4a1cc0869adc3ff.W_v_OXNRYXMUup9iAKFHeMPkwy3iwVpJ6BlmnA6QO_cscenes-app-settings-environment--settings-environment-error-tracking-configuration--light:hash: v1.k794b7964.05cd4d11178a6ab2b511d9bf210abe0d975216c98945669170f00138e560fd16.sqlVQyLt-1PLj-fF9YbPdwnFo_RxtHzrHyZe2OQiSDc+ scenes-app-settings-environment--settings-environment-experiments--dark:+ hash: v1.k794b7964.34ea9c4a5eec940e7e9a2a9435da52e1ebe91d2f7a7f540c76b6323bfdcf830e.HzYgBbQwQQww7_CWcnVIOZ5AwNvp-HlX1gxrQsDwoa4+ scenes-app-settings-environment--settings-environment-experiments--light:+ hash: v1.k794b7964.50405eeca5576a2c771427b596d742f2925f63e17bc96558f7969c65469fac79.yoc74JSxnEwjvd8Qneqn2pDzNMKiG5sx1D6LGwoe1Wk+ scenes-app-settings-environment--settings-environment-experiments-multiple-recalculation-times--dark:+ hash: v1.k794b7964.5b034a5effb472ad3ef818ec75b6b9506e70d95810aac035050535713157e1d6.8do5WxsjD00LvHsn752lDv_sH9FdxOYyPZM7AUzdDqk+ scenes-app-settings-environment--settings-environment-experiments-multiple-recalculation-times--light:+ hash: v1.k794b7964.fb1bcb78d3098e7ab06fdbf1c2f1902049de9030d3769520e78851d3c96b7b24.VhR7GZo9z3_d4yiKMeBu2-54QRDyq_8jIOqlZFwDG_sscenes-app-settings-environment--settings-environment-feature-flags--dark:hash: v1.k794b7964.f542dc208f8caacdc2978c3e17d6c077d299f4896b6acf1b0cbe51eb1e7e2f34.KnYG2YFjexeGzYr2iZlQmND2MXxJXDH3G9_vOeCMy84scenes-app-settings-environment--settings-environment-feature-flags--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 57ca705951ab..26a906006e63 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -324,6 +324,7 @@ export const FEATURE_FLAGS = {ERROR_TRACKING_WEEKLY_DIGEST: 'error-tracking-weekly-digest', // owner: #team-error-trackingEXPERIMENT_BEHAVIOR_COMPARISON: 'experiment-behavior-comparison', // owner: @mp-hog #team-experimentsEXPERIMENT_METRIC_EVENT_BREAKDOWNS: 'experiment-metric-event-breakdowns', // owner: @rodrigoi #team-experiments+ EXPERIMENT_MULTIPLE_RECALCULATION_TIMES: 'experiment-multiple-recalculation-times', // owner: @jurajmajerik #team-experiments, gates the second daily recalculation time picker in environment settingsEXPERIMENT_SETUP_CONTEXT: 'experiment-setup-context', // owner: @mp-hog #team-experiments, gates the experiment-setup-context MCP tool, its endpoint and the staff setup context drawer on the experiments listEXPERIMENTS_DW_AA_TEST: 'experiments-dw-aa-test', // owner: @rodrigoi #team-experimentsEXPERIMENTS_EXCLUDED_VARIANTS: 'experiments-excluded-variants', // owner: @rodrigoi #team-experimentsdiff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 959e638936ab..723e825d0264 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -734,6 +734,16 @@ export const SETTINGS_MAP: SettingSection[] = ["Select the time of day when experiment metrics should be recalculated. This time is in your project's timezone.",component: <ExperimentRecalculationTime />,keywords: ['schedule', 'refresh', 'update', 'time'],+ flag: '!EXPERIMENT_MULTIPLE_RECALCULATION_TIMES',+ },+ {+ id: 'environment-experiment-recalculation-time',+ title: 'Daily recalculation times',+ description:+ "Select up to two times of day when experiment metrics should be recalculated, at least 6 hours apart. Times are in your project's timezone.",+ component: <ExperimentRecalculationTime />,+ keywords: ['schedule', 'refresh', 'update', 'time'],+ flag: 'EXPERIMENT_MULTIPLE_RECALCULATION_TIMES',},{id: 'environment-experiment-matured-users',diff --git a/frontend/src/scenes/settings/environment/ExperimentRecalculationTime.tsx b/frontend/src/scenes/settings/environment/ExperimentRecalculationTime.tsxindex 442f06a72228..be67f666d625 100644--- a/frontend/src/scenes/settings/environment/ExperimentRecalculationTime.tsx+++ b/frontend/src/scenes/settings/environment/ExperimentRecalculationTime.tsx@@ -1,67 +1,131 @@import { useActions, useValues } from 'kea'+import { IconPlus, IconX } from '@posthog/icons'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'-import { TeamMembershipLevel } from 'lib/constants'+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'import { dayjs } from 'lib/dayjs'-import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonSelect, LemonSelectOption } from 'lib/lemon-ui/LemonSelect'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from '~/scenes/teamLogic'import { experimentsConfigLogic } from './experimentsConfigLogic'-const DEFAULT_RECALCULATION_UTC_HOUR = 2 // 02:00 UTC default--const formatHourString = (hour: number): string => {- return dayjs().hour(hour).format('HH:00')-}+const DEFAULT_RECALCULATION_UTC_TIME = '02:00:00'+// Must match MIN_RECALCULATION_GAP_HOURS in products/experiments/backend/models/team_experiments_config.py+const MIN_RECALCULATION_GAP_HOURS = 6-const hourOptions = Array.from({ length: 24 }, (_, hour) => ({- value: hour.toString(),- label: formatHourString(hour),-}))+const utcHourFromTimeString = (utcTimeString: string): number => parseInt(utcTimeString.split(':')[0], 10)-const utcToLocalHour = (utcTimeString: string | null | undefined, projectTimezone: string): number => {- if (!utcTimeString) {- const defaultTime = dayjs.utc().hour(DEFAULT_RECALCULATION_UTC_HOUR)- return defaultTime.tz(projectTimezone).hour()- }+const utcTimeStringFromUtcHour = (utcHour: number): string => `${String(utcHour).padStart(2, '0')}:00:00`- const [hour] = utcTimeString.split(':').map(Number)- const utcTime = dayjs.utc().hour(hour)- return utcTime.tz(projectTimezone).hour()+const circularHourGap = (hourA: number, hourB: number): number => {+ const diff = Math.abs(hourA - hourB)+ return Math.min(diff, 24 - diff)}-const localHourToUtcString = (localHour: number, projectTimezone: string): string => {- const localTime = dayjs().tz(projectTimezone).hour(localHour).minute(0).second(0).millisecond(0)- return localTime.utc().format('HH:mm:ss')-}+const localLabelFromUtcHour = (utcHour: number, projectTimezone: string): string =>+ dayjs.utc().hour(utcHour).minute(0).tz(projectTimezone).format('HH:mm')export function ExperimentRecalculationTime(): JSX.Element {const { timezone: projectTimezone } = useValues(teamLogic)- const { experimentsConfig, experimentsConfigLoading } = useValues(experimentsConfigLogic)+ const { experimentsConfig, experimentsConfigLoading, experimentsConfigUpdating } = useValues(experimentsConfigLogic)const { updateExperimentsConfig } = useActions(experimentsConfigLogic)+ const { featureFlags } = useValues(featureFlagLogic)const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,})- const handleChange = (value: string): void => {- const localHour = parseInt(value, 10)- const utcTimeString = localHourToUtcString(localHour, projectTimezone)- updateExperimentsConfig({ experiment_recalculation_time: utcTimeString })+ const allowSecondTime = !!featureFlags[FEATURE_FLAGS.EXPERIMENT_MULTIPLE_RECALCULATION_TIMES]++ const savedTimes = experimentsConfig?.experiment_recalculation_times?.length+ ? experimentsConfig.experiment_recalculation_times+ : [DEFAULT_RECALCULATION_UTC_TIME]+ const times = allowSecondTime ? savedTimes : [savedTimes[0]]++ const commonDisabledReason =+ restrictedReason ||+ (experimentsConfigUpdating ? 'Saving...' : experimentsConfigLoading ? 'Loading...' : undefined)++ const handleTimeChange = (index: number, value: string): void => {+ // Base on savedTimes: with the flag off, a second saved time is hidden but must survive the edit+ const newTimes = [...savedTimes]+ newTimes[index] = utcTimeStringFromUtcHour(parseInt(value, 10))+ updateExperimentsConfig({ experiment_recalculation_times: newTimes })+ }++ const addSecondTime = (): void => {+ const oppositeUtcHour = (utcHourFromTimeString(times[0]) + 12) % 24+ updateExperimentsConfig({+ experiment_recalculation_times: [times[0], utcTimeStringFromUtcHour(oppositeUtcHour)],+ })}- const currentLocalHour = utcToLocalHour(experimentsConfig?.experiment_recalculation_time, projectTimezone)+ const removeSecondTime = (): void => {+ updateExperimentsConfig({ experiment_recalculation_times: [times[0]] })+ }++ const optionsForIndex = (index: number): LemonSelectOption<string>[] => {+ const otherTime = savedTimes.length > 1 ? savedTimes[1 - index] : null+ const otherUtcHour = otherTime !== null ? utcHourFromTimeString(otherTime) : null+ return Array.from({ length: 24 }, (_, utcHour) => {+ const tooClose =+ otherUtcHour !== null && circularHourGap(utcHour, otherUtcHour) < MIN_RECALCULATION_GAP_HOURS+ return {+ value: utcHour.toString(),+ label: localLabelFromUtcHour(utcHour, projectTimezone),+ disabledReason: tooClose+ ? `Must be at least ${MIN_RECALCULATION_GAP_HOURS} hours from the other recalculation time`+ : undefined,+ }+ }).sort((a, b) => a.label.localeCompare(b.label))+ }return (- <LemonSelect- value={currentLocalHour.toString()}- onChange={handleChange}- options={hourOptions}- disabledReason={restrictedReason || (experimentsConfigLoading ? 'Loading...' : undefined)}- data-attr="team-experiment-recalculation-time"- placeholder="Select recalculation time"- />+ <div className="flex items-center gap-2">+ <LemonSelect+ value={utcHourFromTimeString(times[0]).toString()}+ onChange={(value) => handleTimeChange(0, value)}+ options={optionsForIndex(0)}+ disabledReason={commonDisabledReason}+ data-attr="team-experiment-recalculation-time"+ placeholder="Select recalculation time"+ />+ {allowSecondTime &&+ (times.length > 1 ? (+ <>+ <LemonSelect+ value={utcHourFromTimeString(times[1]).toString()}+ onChange={(value) => handleTimeChange(1, value)}+ options={optionsForIndex(1)}+ disabledReason={commonDisabledReason}+ data-attr="team-experiment-second-recalculation-time"+ />+ <LemonButton+ icon={<IconX />}+ size="small"+ onClick={removeSecondTime}+ disabledReason={commonDisabledReason}+ tooltip="Remove second time"+ data-attr="team-experiment-remove-second-recalculation-time"+ />+ </>+ ) : (+ <LemonButton+ type="tertiary"+ icon={<IconPlus />}+ size="small"+ onClick={addSecondTime}+ disabledReason={commonDisabledReason}+ data-attr="team-experiment-add-second-recalculation-time"+ >+ Add second time+ </LemonButton>+ ))}+ </div>)}diff --git a/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts b/frontend/src/scenes/settings/environment/experimentsConfigLogic.tsindex 67abfae79ec0..dcf472c67df5 100644--- a/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts+++ b/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts@@ -10,6 +10,7 @@ import { DEFAULT_MDE } from 'products/experiments/frontend/constants'export interface ExperimentsConfig {experiment_recalculation_time: string | null+ experiment_recalculation_times: string[] | nulldefault_experiment_confidence_level: number | nulldefault_experiment_stats_method: string | nulldefault_only_count_matured_users: booleandiff --git a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsxindex abd086adc55f..db4e994804ae 100644--- a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx+++ b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx@@ -5,7 +5,7 @@ import { useActions } from 'kea'import { router } from 'kea-router'import { useEffect, useState } from 'react'-import { STORYBOOK_FEATURE_FLAGS } from 'lib/constants'+import { FEATURE_FLAGS, STORYBOOK_FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -138,6 +138,49 @@ export const SettingsEnvironmentMarketingAnalytics: Story = {export const SettingsEnvironmentWebAnalytics: Story = { args: { sectionId: 'environment-web-analytics' } }+const EXPERIMENTS_CONFIG_MOCK = {+ experiment_recalculation_time: '02:00:00',+ experiment_recalculation_times: ['02:00:00'],+ default_experiment_confidence_level: null,+ default_experiment_stats_method: null,+ default_only_count_matured_users: false,+ default_cuped_enabled: false,+ default_cuped_lookback_days: null,+ default_minimum_detectable_effect: 5,+ default_sequential_testing_enabled: false,+ default_sequential_tuning_parameter: null,+ flag_cleanup_repository: null,+}++export const SettingsEnvironmentExperiments: Story = {+ args: { sectionId: 'environment-experiments' },+ parameters: {+ // STORYBOOK_FEATURE_FLAGS enables every flag, so the flag-off picker needs the exclusion+ featureFlags: STORYBOOK_FEATURE_FLAGS.filter(+ (f) => f !== FEATURE_FLAGS.EXPERIMENT_MULTIPLE_RECALCULATION_TIMES+ ),+ },+ decorators: [+ mswDecorator({+ get: { '/api/projects/:id/experiments_config/': EXPERIMENTS_CONFIG_MOCK },+ }),+ ],+}++export const SettingsEnvironmentExperimentsMultipleRecalculationTimes: Story = {+ args: { sectionId: 'environment-experiments' },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:id/experiments_config/': {+ ...EXPERIMENTS_CONFIG_MOCK,+ experiment_recalculation_times: ['02:00:00', '14:00:00'],+ },+ },+ }),+ ],+}+export const SettingsEnvironmentReplay: Story = { args: { sectionId: 'environment-replay' } }export const SettingsEnvironmentSurveys: Story = { args: { sectionId: 'environment-surveys' } }