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