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