1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// FieldTrial is a class for handling details of statistical experiments
6// performed by actual users in the field (i.e., in a shipped or beta product).
7// All code is called exclusively on the UI thread currently.
8//
9// The simplest example is an experiment to see whether one of two options
10// produces "better" results across our user population.  In that scenario, UMA
11// data is uploaded to aggregate the test results, and this FieldTrial class
12// manages the state of each such experiment (state == which option was
13// pseudo-randomly selected).
14//
15// States are typically generated randomly, either based on a one time
16// randomization (which will yield the same results, in terms of selecting
17// the client for a field trial or not, for every run of the program on a
18// given machine), or by a session randomization (generated each time the
19// application starts up, but held constant during the duration of the
20// process).
21
22//------------------------------------------------------------------------------
23// Example:  Suppose we have an experiment involving memory, such as determining
24// the impact of some pruning algorithm.
25// We assume that we already have a histogram of memory usage, such as:
26
27//   UMA_HISTOGRAM_COUNTS("Memory.RendererTotal", count);
28
29// Somewhere in main thread initialization code, we'd probably define an
30// instance of a FieldTrial, with code such as:
31
32// // FieldTrials are reference counted, and persist automagically until
33// // process teardown, courtesy of their automatic registration in
34// // FieldTrialList.
35// // Note: This field trial will run in Chrome instances compiled through
36// //       8 July, 2015, and after that all instances will be in "StandardMem".
37// scoped_refptr<base::FieldTrial> trial(
38//     base::FieldTrialList::FactoryGetFieldTrial(
39//         "MemoryExperiment", 1000, "StandardMem", 2015, 7, 8,
40//         base::FieldTrial::ONE_TIME_RANDOMIZED, NULL));
41//
42// const int high_mem_group =
43//     trial->AppendGroup("HighMem", 20);  // 2% in HighMem group.
44// const int low_mem_group =
45//     trial->AppendGroup("LowMem", 20);   // 2% in LowMem group.
46// // Take action depending of which group we randomly land in.
47// if (trial->group() == high_mem_group)
48//   SetPruningAlgorithm(kType1);  // Sample setting of browser state.
49// else if (trial->group() == low_mem_group)
50//   SetPruningAlgorithm(kType2);  // Sample alternate setting.
51
52//------------------------------------------------------------------------------
53
54#ifndef BASE_METRICS_FIELD_TRIAL_H_
55#define BASE_METRICS_FIELD_TRIAL_H_
56
57#include <map>
58#include <set>
59#include <string>
60#include <vector>
61
62#include "base/base_export.h"
63#include "base/gtest_prod_util.h"
64#include "base/memory/ref_counted.h"
65#include "base/observer_list_threadsafe.h"
66#include "base/synchronization/lock.h"
67#include "base/time/time.h"
68
69namespace base {
70
71class FieldTrialList;
72
73class BASE_EXPORT FieldTrial : public RefCounted<FieldTrial> {
74 public:
75  typedef int Probability;  // Probability type for being selected in a trial.
76
77  // Specifies the persistence of the field trial group choice.
78  enum RandomizationType {
79    // One time randomized trials will persist the group choice between
80    // restarts, which is recommended for most trials, especially those that
81    // change user visible behavior.
82    ONE_TIME_RANDOMIZED,
83    // Session randomized trials will roll the dice to select a group on every
84    // process restart.
85    SESSION_RANDOMIZED,
86  };
87
88  // EntropyProvider is an interface for providing entropy for one-time
89  // randomized (persistent) field trials.
90  class BASE_EXPORT EntropyProvider {
91   public:
92    virtual ~EntropyProvider();
93
94    // Returns a double in the range of [0, 1) to be used for the dice roll for
95    // the specified field trial. If |randomization_seed| is not 0, it will be
96    // used in preference to |trial_name| for generating the entropy by entropy
97    // providers that support it. A given instance should always return the same
98    // value given the same input |trial_name| and |randomization_seed| values.
99    virtual double GetEntropyForTrial(const std::string& trial_name,
100                                      uint32 randomization_seed) const = 0;
101  };
102
103  // A pair representing a Field Trial and its selected group.
104  struct ActiveGroup {
105    std::string trial_name;
106    std::string group_name;
107  };
108
109  typedef std::vector<ActiveGroup> ActiveGroups;
110
111  // A return value to indicate that a given instance has not yet had a group
112  // assignment (and hence is not yet participating in the trial).
113  static const int kNotFinalized;
114
115  // Disables this trial, meaning it always determines the default group
116  // has been selected. May be called immediately after construction, or
117  // at any time after initialization (should not be interleaved with
118  // AppendGroup calls). Once disabled, there is no way to re-enable a
119  // trial.
120  // TODO(mad): http://code.google.com/p/chromium/issues/detail?id=121446
121  // This doesn't properly reset to Default when a group was forced.
122  void Disable();
123
124  // Establish the name and probability of the next group in this trial.
125  // Sometimes, based on construction randomization, this call may cause the
126  // provided group to be *THE* group selected for use in this instance.
127  // The return value is the group number of the new group.
128  int AppendGroup(const std::string& name, Probability group_probability);
129
130  // Return the name of the FieldTrial (excluding the group name).
131  const std::string& trial_name() const { return trial_name_; }
132
133  // Return the randomly selected group number that was assigned, and notify
134  // any/all observers that this finalized group number has presumably been used
135  // (queried), and will never change. Note that this will force an instance to
136  // participate, and make it illegal to attempt to probabilistically add any
137  // other groups to the trial.
138  int group();
139
140  // If the group's name is empty, a string version containing the group number
141  // is used as the group name. This causes a winner to be chosen if none was.
142  const std::string& group_name();
143
144  // Set the field trial as forced, meaning that it was setup earlier than
145  // the hard coded registration of the field trial to override it.
146  // This allows the code that was hard coded to register the field trial to
147  // still succeed even though the field trial has already been registered.
148  // This must be called after appending all the groups, since we will make
149  // the group choice here. Note that this is a NOOP for already forced trials.
150  // And, as the rest of the FieldTrial code, this is not thread safe and must
151  // be done from the UI thread.
152  void SetForced();
153
154  // Enable benchmarking sets field trials to a common setting.
155  static void EnableBenchmarking();
156
157  // Creates a FieldTrial object with the specified parameters, to be used for
158  // simulation of group assignment without actually affecting global field
159  // trial state in the running process. Group assignment will be done based on
160  // |entropy_value|, which must have a range of [0, 1).
161  //
162  // Note: Using this function will not register the field trial globally in the
163  // running process - for that, use FieldTrialList::FactoryGetFieldTrial().
164  //
165  // The ownership of the returned FieldTrial is transfered to the caller which
166  // is responsible for deref'ing it (e.g. by using scoped_refptr<FieldTrial>).
167  static FieldTrial* CreateSimulatedFieldTrial(
168      const std::string& trial_name,
169      Probability total_probability,
170      const std::string& default_group_name,
171      double entropy_value);
172
173 private:
174  // Allow tests to access our innards for testing purposes.
175  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, Registration);
176  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, AbsoluteProbabilities);
177  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, RemainingProbability);
178  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, FiftyFiftyProbability);
179  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, MiddleProbabilities);
180  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, OneWinner);
181  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DisableProbability);
182  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, ActiveGroups);
183  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, ActiveGroupsNotFinalized);
184  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, Save);
185  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DuplicateRestore);
186  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedTurnFeatureOff);
187  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedTurnFeatureOn);
188  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedChangeDefault_Default);
189  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedChangeDefault_NonDefault);
190  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, FloatBoundariesGiveEqualGroupSizes);
191  FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DoesNotSurpassTotalProbability);
192
193  friend class base::FieldTrialList;
194
195  friend class RefCounted<FieldTrial>;
196
197  // This is the group number of the 'default' group when a choice wasn't forced
198  // by a call to FieldTrialList::CreateFieldTrial. It is kept private so that
199  // consumers don't use it by mistake in cases where the group was forced.
200  static const int kDefaultGroupNumber;
201
202  // Creates a field trial with the specified parameters. Group assignment will
203  // be done based on |entropy_value|, which must have a range of [0, 1).
204  FieldTrial(const std::string& trial_name,
205             Probability total_probability,
206             const std::string& default_group_name,
207             double entropy_value);
208  virtual ~FieldTrial();
209
210  // Return the default group name of the FieldTrial.
211  std::string default_group_name() const { return default_group_name_; }
212
213  // Marks this trial as having been registered with the FieldTrialList. Must be
214  // called no more than once and before any |group()| calls have occurred.
215  void SetTrialRegistered();
216
217  // Sets the chosen group name and number.
218  void SetGroupChoice(const std::string& group_name, int number);
219
220  // Ensures that a group is chosen, if it hasn't yet been. The field trial
221  // might yet be disabled, so this call will *not* notify observers of the
222  // status.
223  void FinalizeGroupChoice();
224
225  // Returns the trial name and selected group name for this field trial via
226  // the output parameter |active_group|, but only if the group has already
227  // been chosen and has been externally observed via |group()| and the trial
228  // has not been disabled. In that case, true is returned and |active_group|
229  // is filled in; otherwise, the result is false and |active_group| is left
230  // untouched.
231  bool GetActiveGroup(ActiveGroup* active_group) const;
232
233  // Returns the group_name. A winner need not have been chosen.
234  std::string group_name_internal() const { return group_name_; }
235
236  // The name of the field trial, as can be found via the FieldTrialList.
237  const std::string trial_name_;
238
239  // The maximum sum of all probabilities supplied, which corresponds to 100%.
240  // This is the scaling factor used to adjust supplied probabilities.
241  const Probability divisor_;
242
243  // The name of the default group.
244  const std::string default_group_name_;
245
246  // The randomly selected probability that is used to select a group (or have
247  // the instance not participate).  It is the product of divisor_ and a random
248  // number between [0, 1).
249  Probability random_;
250
251  // Sum of the probabilities of all appended groups.
252  Probability accumulated_group_probability_;
253
254  // The number that will be returned by the next AppendGroup() call.
255  int next_group_number_;
256
257  // The pseudo-randomly assigned group number.
258  // This is kNotFinalized if no group has been assigned.
259  int group_;
260
261  // A textual name for the randomly selected group. Valid after |group()|
262  // has been called.
263  std::string group_name_;
264
265  // When enable_field_trial_ is false, field trial reverts to the 'default'
266  // group.
267  bool enable_field_trial_;
268
269  // When forced_ is true, we return the chosen group from AppendGroup when
270  // appropriate.
271  bool forced_;
272
273  // Specifies whether the group choice has been reported to observers.
274  bool group_reported_;
275
276  // Whether this trial is registered with the global FieldTrialList and thus
277  // should notify it when its group is queried.
278  bool trial_registered_;
279
280  // When benchmarking is enabled, field trials all revert to the 'default'
281  // group.
282  static bool enable_benchmarking_;
283
284  DISALLOW_COPY_AND_ASSIGN(FieldTrial);
285};
286
287//------------------------------------------------------------------------------
288// Class with a list of all active field trials.  A trial is active if it has
289// been registered, which includes evaluating its state based on its probaility.
290// Only one instance of this class exists.
291class BASE_EXPORT FieldTrialList {
292 public:
293  // Specifies whether field trials should be activated (marked as "used"), when
294  // created using |CreateTrialsFromString()|.
295  enum FieldTrialActivationMode {
296    DONT_ACTIVATE_TRIALS,
297    ACTIVATE_TRIALS,
298  };
299
300  // Define a separator character to use when creating a persistent form of an
301  // instance.  This is intended for use as a command line argument, passed to a
302  // second process to mimic our state (i.e., provide the same group name).
303  static const char kPersistentStringSeparator;  // Currently a slash.
304
305  // Year that is guaranteed to not be expired when instantiating a field trial
306  // via |FactoryGetFieldTrial()|.  Set to two years from the build date.
307  static int kNoExpirationYear;
308
309  // Observer is notified when a FieldTrial's group is selected.
310  class BASE_EXPORT Observer {
311   public:
312    // Notify observers when FieldTrials's group is selected.
313    virtual void OnFieldTrialGroupFinalized(const std::string& trial_name,
314                                            const std::string& group_name) = 0;
315
316   protected:
317    virtual ~Observer();
318  };
319
320  // This singleton holds the global list of registered FieldTrials.
321  //
322  // To support one-time randomized field trials, specify a non-NULL
323  // |entropy_provider| which should be a source of uniformly distributed
324  // entropy values. Takes ownership of |entropy_provider|. If one time
325  // randomization is not desired, pass in NULL for |entropy_provider|.
326  explicit FieldTrialList(const FieldTrial::EntropyProvider* entropy_provider);
327
328  // Destructor Release()'s references to all registered FieldTrial instances.
329  ~FieldTrialList();
330
331  // Get a FieldTrial instance from the factory.
332  //
333  // |name| is used to register the instance with the FieldTrialList class,
334  // and can be used to find the trial (only one trial can be present for each
335  // name). |default_group_name| is the name of the default group which will
336  // be chosen if none of the subsequent appended groups get to be chosen.
337  // |default_group_number| can receive the group number of the default group as
338  // AppendGroup returns the number of the subsequence groups. |trial_name| and
339  // |default_group_name| may not be empty but |default_group_number| can be
340  // NULL if the value is not needed.
341  //
342  // Group probabilities that are later supplied must sum to less than or equal
343  // to the |total_probability|. Arguments |year|, |month| and |day_of_month|
344  // specify the expiration time. If the build time is after the expiration time
345  // then the field trial reverts to the 'default' group.
346  //
347  // Use this static method to get a startup-randomized FieldTrial or a
348  // previously created forced FieldTrial.
349  static FieldTrial* FactoryGetFieldTrial(
350      const std::string& trial_name,
351      FieldTrial::Probability total_probability,
352      const std::string& default_group_name,
353      const int year,
354      const int month,
355      const int day_of_month,
356      FieldTrial::RandomizationType randomization_type,
357      int* default_group_number);
358
359  // Same as FactoryGetFieldTrial(), but allows specifying a custom seed to be
360  // used on one-time randomized field trials (instead of a hash of the trial
361  // name, which is used otherwise or if |randomization_seed| has value 0). The
362  // |randomization_seed| value (other than 0) should never be the same for two
363  // trials, else this would result in correlated group assignments.
364  // Note: Using a custom randomization seed is only supported by the
365  // PermutedEntropyProvider (which is used when UMA is not enabled).
366  static FieldTrial* FactoryGetFieldTrialWithRandomizationSeed(
367      const std::string& trial_name,
368      FieldTrial::Probability total_probability,
369      const std::string& default_group_name,
370      const int year,
371      const int month,
372      const int day_of_month,
373      FieldTrial::RandomizationType randomization_type,
374      uint32 randomization_seed,
375      int* default_group_number);
376
377  // The Find() method can be used to test to see if a named Trial was already
378  // registered, or to retrieve a pointer to it from the global map.
379  static FieldTrial* Find(const std::string& name);
380
381  // Returns the group number chosen for the named trial, or
382  // FieldTrial::kNotFinalized if the trial does not exist.
383  static int FindValue(const std::string& name);
384
385  // Returns the group name chosen for the named trial, or the
386  // empty string if the trial does not exist.
387  static std::string FindFullName(const std::string& name);
388
389  // Returns true if the named trial has been registered.
390  static bool TrialExists(const std::string& name);
391
392  // Creates a persistent representation of active FieldTrial instances for
393  // resurrection in another process. This allows randomization to be done in
394  // one process, and secondary processes can be synchronized on the result.
395  // The resulting string contains the name and group name pairs of all
396  // registered FieldTrials for which the group has been chosen and externally
397  // observed (via |group()|) and which have not been disabled, with "/" used
398  // to separate all names and to terminate the string. This string is parsed
399  // by |CreateTrialsFromString()|.
400  static void StatesToString(std::string* output);
401
402  // Fills in the supplied vector |active_groups| (which must be empty when
403  // called) with a snapshot of all registered FieldTrials for which the group
404  // has been chosen and externally observed (via |group()|) and which have
405  // not been disabled.
406  static void GetActiveFieldTrialGroups(
407      FieldTrial::ActiveGroups* active_groups);
408
409  // Use a state string (re: StatesToString()) to augment the current list of
410  // field trials to include the supplied trials, and using a 100% probability
411  // for each trial, force them to have the same group string. This is commonly
412  // used in a non-browser process, to carry randomly selected state in a
413  // browser process into this non-browser process, but could also be invoked
414  // through a command line argument to the browser process. The created field
415  // trials are marked as "used" for the purposes of active trial reporting if
416  // |mode| is ACTIVATE_TRIALS. Trial names in |ignored_trial_names| are ignored
417  // when parsing |prior_trials|.
418  static bool CreateTrialsFromString(
419      const std::string& prior_trials,
420      FieldTrialActivationMode mode,
421      const std::set<std::string>& ignored_trial_names);
422
423  // Create a FieldTrial with the given |name| and using 100% probability for
424  // the FieldTrial, force FieldTrial to have the same group string as
425  // |group_name|. This is commonly used in a non-browser process, to carry
426  // randomly selected state in a browser process into this non-browser process.
427  // It returns NULL if there is a FieldTrial that is already registered with
428  // the same |name| but has different finalized group string (|group_name|).
429  static FieldTrial* CreateFieldTrial(const std::string& name,
430                                      const std::string& group_name);
431
432  // Add an observer to be notified when a field trial is irrevocably committed
433  // to being part of some specific field_group (and hence the group_name is
434  // also finalized for that field_trial).
435  static void AddObserver(Observer* observer);
436
437  // Remove an observer.
438  static void RemoveObserver(Observer* observer);
439
440  // Notify all observers that a group has been finalized for |field_trial|.
441  static void NotifyFieldTrialGroupSelection(FieldTrial* field_trial);
442
443  // Return the number of active field trials.
444  static size_t GetFieldTrialCount();
445
446 private:
447  // A map from FieldTrial names to the actual instances.
448  typedef std::map<std::string, FieldTrial*> RegistrationMap;
449
450  // If one-time randomization is enabled, returns a weak pointer to the
451  // corresponding EntropyProvider. Otherwise, returns NULL.
452  static const FieldTrial::EntropyProvider*
453      GetEntropyProviderForOneTimeRandomization();
454
455  // Helper function should be called only while holding lock_.
456  FieldTrial* PreLockedFind(const std::string& name);
457
458  // Register() stores a pointer to the given trial in a global map.
459  // This method also AddRef's the indicated trial.
460  // This should always be called after creating a new FieldTrial instance.
461  static void Register(FieldTrial* trial);
462
463  static FieldTrialList* global_;  // The singleton of this class.
464
465  // This will tell us if there is an attempt to register a field
466  // trial or check if one-time randomization is enabled without
467  // creating the FieldTrialList. This is not an error, unless a
468  // FieldTrialList is created after that.
469  static bool used_without_global_;
470
471  // Lock for access to registered_.
472  base::Lock lock_;
473  RegistrationMap registered_;
474
475  // Entropy provider to be used for one-time randomized field trials. If NULL,
476  // one-time randomization is not supported.
477  scoped_ptr<const FieldTrial::EntropyProvider> entropy_provider_;
478
479  // List of observers to be notified when a group is selected for a FieldTrial.
480  scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_;
481
482  DISALLOW_COPY_AND_ASSIGN(FieldTrialList);
483};
484
485}  // namespace base
486
487#endif  // BASE_METRICS_FIELD_TRIAL_H_
488