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.
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.
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).
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 startup randomization (generated each time the
19 // application starts up, but held constant during the duration of the
20 // process), or by continuous randomization across a run (where the state
21 // can be recalculated again and again, many times during a process).
22 // Continuous randomization is not yet implemented.
24 //------------------------------------------------------------------------------
25 // Example: Suppose we have an experiment involving memory, such as determining
26 // the impact of some pruning algorithm.
27 // We assume that we already have a histogram of memory usage, such as:
29 // HISTOGRAM_COUNTS("Memory.RendererTotal", count);
31 // Somewhere in main thread initialization code, we'd probably define an
32 // instance of a FieldTrial, with code such as:
34 // // FieldTrials are reference counted, and persist automagically until
35 // // process teardown, courtesy of their automatic registration in
37 // // Note: This field trial will run in Chrome instances compiled through
38 // // 8 July, 2015, and after that all instances will be in "StandardMem".
39 // scoped_refptr<base::FieldTrial> trial(
40 // base::FieldTrialList::FactoryGetFieldTrial("MemoryExperiment", 1000,
41 // "StandardMem", 2015, 7, 8,
43 // const int high_mem_group =
44 // trial->AppendGroup("HighMem", 20); // 2% in HighMem group.
45 // const int low_mem_group =
46 // trial->AppendGroup("LowMem", 20); // 2% in LowMem group.
47 // // Take action depending of which group we randomly land in.
48 // if (trial->group() == high_mem_group)
49 // SetPruningAlgorithm(kType1); // Sample setting of browser state.
50 // else if (trial->group() == low_mem_group)
51 // SetPruningAlgorithm(kType2); // Sample alternate setting.
53 // We then, in addition to our original histogram, output histograms which have
54 // slightly different names depending on what group the trial instance happened
55 // to randomly be assigned:
57 // HISTOGRAM_COUNTS("Memory.RendererTotal", count); // The original histogram.
58 // static const bool memory_renderer_total_trial_exists =
59 // FieldTrialList::TrialExists("MemoryExperiment");
60 // if (memory_renderer_total_trial_exists) {
61 // HISTOGRAM_COUNTS(FieldTrial::MakeName("Memory.RendererTotal",
62 // "MemoryExperiment"), count);
65 // The above code will create four distinct histograms, with each run of the
66 // application being assigned to of of the three groups, and for each group, the
67 // correspondingly named histogram will be populated:
69 // Memory.RendererTotal // 100% of users still fill this histogram.
70 // Memory.RendererTotal_HighMem // 2% of users will fill this histogram.
71 // Memory.RendererTotal_LowMem // 2% of users will fill this histogram.
72 // Memory.RendererTotal_StandardMem // 96% of users will fill this histogram.
74 //------------------------------------------------------------------------------
76 #ifndef BASE_METRICS_FIELD_TRIAL_H_
77 #define BASE_METRICS_FIELD_TRIAL_H_
83 #include "base/base_export.h"
84 #include "base/gtest_prod_util.h"
85 #include "base/memory/ref_counted.h"
86 #include "base/observer_list_threadsafe.h"
87 #include "base/synchronization/lock.h"
88 #include "base/time.h"
94 class BASE_EXPORT FieldTrial
: public RefCounted
<FieldTrial
> {
96 typedef int Probability
; // Probability type for being selected in a trial.
98 // EntropyProvider is an interface for providing entropy for one-time
99 // randomized (persistent) field trials.
100 class BASE_EXPORT EntropyProvider
{
102 virtual ~EntropyProvider();
104 // Returns a double in the range of [0, 1) based on |trial_name| that will
105 // be used for the dice roll for the specified field trial. A given instance
106 // should always return the same value given the same input |trial_name|.
107 virtual double GetEntropyForTrial(const std::string
& trial_name
) const = 0;
110 // A pair representing a Field Trial and its selected group.
112 std::string trial_name
;
113 std::string group_name
;
116 typedef std::vector
<ActiveGroup
> ActiveGroups
;
118 // A return value to indicate that a given instance has not yet had a group
119 // assignment (and hence is not yet participating in the trial).
120 static const int kNotFinalized
;
122 // Changes the field trial to use one-time randomization, i.e. produce the
123 // same result for the current trial on every run of this client. Must be
124 // called right after construction.
125 void UseOneTimeRandomization();
127 // Disables this trial, meaning it always determines the default group
128 // has been selected. May be called immediately after construction, or
129 // at any time after initialization (should not be interleaved with
130 // AppendGroup calls). Once disabled, there is no way to re-enable a
132 // TODO(mad): http://code.google.com/p/chromium/issues/detail?id=121446
133 // This doesn't properly reset to Default when a group was forced.
136 // Establish the name and probability of the next group in this trial.
137 // Sometimes, based on construction randomization, this call may cause the
138 // provided group to be *THE* group selected for use in this instance.
139 // The return value is the group number of the new group.
140 int AppendGroup(const std::string
& name
, Probability group_probability
);
142 // Return the name of the FieldTrial (excluding the group name).
143 const std::string
& trial_name() const { return trial_name_
; }
145 // Return the randomly selected group number that was assigned, and notify
146 // any/all observers that this finalized group number has presumably been used
147 // (queried), and will never change. Note that this will force an instance to
148 // participate, and make it illegal to attempt to probabilistically add any
149 // other groups to the trial.
152 // If the group's name is empty, a string version containing the group number
153 // is used as the group name. This causes a winner to be chosen if none was.
154 const std::string
& group_name();
156 // Helper function for the most common use: as an argument to specify the
157 // name of a HISTOGRAM. Use the original histogram name as the name_prefix.
158 static std::string
MakeName(const std::string
& name_prefix
,
159 const std::string
& trial_name
);
161 // Enable benchmarking sets field trials to a common setting.
162 static void EnableBenchmarking();
164 // Set the field trial as forced, meaning that it was setup earlier than
165 // the hard coded registration of the field trial to override it.
166 // This allows the code that was hard coded to register the field trial to
167 // still succeed even though the field trial has already been registered.
168 // This must be called after appending all the groups, since we will make
169 // the group choice here. Note that this is a NOOP for already forced trials.
170 // And, as the rest of the FieldTrial code, this is not thread safe and must
171 // be done from the UI thread.
175 // Allow tests to access our innards for testing purposes.
176 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, Registration
);
177 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, AbsoluteProbabilities
);
178 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, RemainingProbability
);
179 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, FiftyFiftyProbability
);
180 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, MiddleProbabilities
);
181 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, OneWinner
);
182 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, DisableProbability
);
183 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, ActiveGroups
);
184 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, ActiveGroupsNotFinalized
);
185 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, Save
);
186 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, DuplicateRestore
);
187 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, MakeName
);
188 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, HashClientId
);
189 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, HashClientIdIsUniform
);
190 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, NameGroupIds
);
191 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, UseOneTimeRandomization
);
192 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, SetForcedTurnFeatureOff
);
193 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, SetForcedTurnFeatureOn
);
194 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, SetForcedChangeDefault_Default
);
195 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest
, SetForcedChangeDefault_NonDefault
);
197 friend class base::FieldTrialList
;
199 friend class RefCounted
<FieldTrial
>;
201 // This is the group number of the 'default' group when a choice wasn't forced
202 // by a call to FieldTrialList::CreateFieldTrial. It is kept private so that
203 // consumers don't use it by mistake in cases where the group was forced.
204 static const int kDefaultGroupNumber
;
206 FieldTrial(const std::string
& name
,
207 Probability total_probability
,
208 const std::string
& default_group_name
);
209 virtual ~FieldTrial();
211 // Return the default group name of the FieldTrial.
212 std::string
default_group_name() const { return default_group_name_
; }
214 // Sets the chosen group name and number.
215 void SetGroupChoice(const std::string
& group_name
, int number
);
217 // Ensures that a group is chosen, if it hasn't yet been. The field trial
218 // might yet be disabled, so this call will *not* notify observers of the
220 void FinalizeGroupChoice();
222 // Returns the trial name and selected group name for this field trial via
223 // the output parameter |active_group|, but only if the group has already
224 // been chosen and has been externally observed via |group()| and the trial
225 // has not been disabled. In that case, true is returned and |active_group|
226 // is filled in; otherwise, the result is false and |active_group| is left
228 bool GetActiveGroup(ActiveGroup
* active_group
) const;
230 // Returns the group_name. A winner need not have been chosen.
231 std::string
group_name_internal() const { return group_name_
; }
233 // The name of the field trial, as can be found via the FieldTrialList.
234 const std::string trial_name_
;
236 // The maximum sum of all probabilities supplied, which corresponds to 100%.
237 // This is the scaling factor used to adjust supplied probabilities.
238 const Probability divisor_
;
240 // The name of the default group.
241 const std::string default_group_name_
;
243 // The randomly selected probability that is used to select a group (or have
244 // the instance not participate). It is the product of divisor_ and a random
245 // number between [0, 1).
248 // Sum of the probabilities of all appended groups.
249 Probability accumulated_group_probability_
;
251 int next_group_number_
;
253 // The pseudo-randomly assigned group number.
254 // This is kNotFinalized if no group has been assigned.
257 // A textual name for the randomly selected group. Valid after |group()|
259 std::string group_name_
;
261 // When enable_field_trial_ is false, field trial reverts to the 'default'
263 bool enable_field_trial_
;
265 // When forced_ is true, we return the chosen group from AppendGroup when
269 // Specifies whether the group choice has been reported to observers.
270 bool group_reported_
;
272 // When benchmarking is enabled, field trials all revert to the 'default'
274 static bool enable_benchmarking_
;
276 DISALLOW_COPY_AND_ASSIGN(FieldTrial
);
279 //------------------------------------------------------------------------------
280 // Class with a list of all active field trials. A trial is active if it has
281 // been registered, which includes evaluating its state based on its probaility.
282 // Only one instance of this class exists.
283 class BASE_EXPORT FieldTrialList
{
285 // Define a separator character to use when creating a persistent form of an
286 // instance. This is intended for use as a command line argument, passed to a
287 // second process to mimic our state (i.e., provide the same group name).
288 static const char kPersistentStringSeparator
; // Currently a slash.
290 // Year that is guaranteed to not be expired when instantiating a field trial
291 // via |FactoryGetFieldTrial()|. Set to two years from the build date.
292 static int kNoExpirationYear
;
294 // Observer is notified when a FieldTrial's group is selected.
295 class BASE_EXPORT Observer
{
297 // Notify observers when FieldTrials's group is selected.
298 virtual void OnFieldTrialGroupFinalized(const std::string
& trial_name
,
299 const std::string
& group_name
) = 0;
305 // This singleton holds the global list of registered FieldTrials.
307 // To support one-time randomized field trials, specify a non-NULL
308 // |entropy_provider| which should be a source of uniformly distributed
309 // entropy values. Takes ownership of |entropy_provider|. If one time
310 // randomization is not desired, pass in NULL for |entropy_provider|.
311 explicit FieldTrialList(const FieldTrial::EntropyProvider
* entropy_provider
);
313 // Destructor Release()'s references to all registered FieldTrial instances.
316 // Get a FieldTrial instance from the factory.
318 // |name| is used to register the instance with the FieldTrialList class,
319 // and can be used to find the trial (only one trial can be present for each
320 // name). |default_group_name| is the name of the default group which will
321 // be chosen if none of the subsequent appended groups get to be chosen.
322 // |default_group_number| can receive the group number of the default group as
323 // AppendGroup returns the number of the subsequence groups. |trial_name| and
324 // |default_group_name| may not be empty but |default_group_number| can be
325 // NULL if the value is not needed.
327 // Group probabilities that are later supplied must sum to less than or equal
328 // to the |total_probability|. Arguments |year|, |month| and |day_of_month|
329 // specify the expiration time. If the build time is after the expiration time
330 // then the field trial reverts to the 'default' group.
332 // Use this static method to get a startup-randomized FieldTrial or a
333 // previously created forced FieldTrial. If you want a one-time randomized
334 // trial, call UseOneTimeRandomization() right after creation.
335 static FieldTrial
* FactoryGetFieldTrial(
336 const std::string
& trial_name
,
337 FieldTrial::Probability total_probability
,
338 const std::string
& default_group_name
,
341 const int day_of_month
,
342 int* default_group_number
);
344 // The Find() method can be used to test to see if a named Trial was already
345 // registered, or to retrieve a pointer to it from the global map.
346 static FieldTrial
* Find(const std::string
& name
);
348 // Returns the group number chosen for the named trial, or
349 // FieldTrial::kNotFinalized if the trial does not exist.
350 static int FindValue(const std::string
& name
);
352 // Returns the group name chosen for the named trial, or the
353 // empty string if the trial does not exist.
354 static std::string
FindFullName(const std::string
& name
);
356 // Returns true if the named trial has been registered.
357 static bool TrialExists(const std::string
& name
);
359 // Creates a persistent representation of active FieldTrial instances for
360 // resurrection in another process. This allows randomization to be done in
361 // one process, and secondary processes can be synchronized on the result.
362 // The resulting string contains the name and group name pairs of all
363 // registered FieldTrials for which the group has been chosen and externally
364 // observed (via |group()|) and which have not been disabled, with "/" used
365 // to separate all names and to terminate the string. This string is parsed
366 // by |CreateTrialsFromString()|.
367 static void StatesToString(std::string
* output
);
369 // Fills in the supplied vector |active_groups| (which must be empty when
370 // called) with a snapshot of all registered FieldTrials for which the group
371 // has been chosen and externally observed (via |group()|) and which have
372 // not been disabled.
373 static void GetActiveFieldTrialGroups(
374 FieldTrial::ActiveGroups
* active_groups
);
376 // Use a state string (re: StatesToString()) to augment the current list of
377 // field trials to include the supplied trials, and using a 100% probability
378 // for each trial, force them to have the same group string. This is commonly
379 // used in a non-browser process, to carry randomly selected state in a
380 // browser process into this non-browser process, but could also be invoked
381 // through a command line argument to the browser process. The created field
382 // trials are marked as "used" for the purposes of active trial reporting.
383 static bool CreateTrialsFromString(const std::string
& prior_trials
);
385 // Create a FieldTrial with the given |name| and using 100% probability for
386 // the FieldTrial, force FieldTrial to have the same group string as
387 // |group_name|. This is commonly used in a non-browser process, to carry
388 // randomly selected state in a browser process into this non-browser process.
389 // It returns NULL if there is a FieldTrial that is already registered with
390 // the same |name| but has different finalized group string (|group_name|).
391 static FieldTrial
* CreateFieldTrial(const std::string
& name
,
392 const std::string
& group_name
);
394 // Add an observer to be notified when a field trial is irrevocably committed
395 // to being part of some specific field_group (and hence the group_name is
396 // also finalized for that field_trial).
397 static void AddObserver(Observer
* observer
);
399 // Remove an observer.
400 static void RemoveObserver(Observer
* observer
);
402 // Notify all observers that a group has been finalized for |field_trial|.
403 static void NotifyFieldTrialGroupSelection(FieldTrial
* field_trial
);
405 // Return the number of active field trials.
406 static size_t GetFieldTrialCount();
408 // If one-time randomization is enabled, returns a weak pointer to the
409 // corresponding EntropyProvider. Otherwise, returns NULL.
410 static const FieldTrial::EntropyProvider
*
411 GetEntropyProviderForOneTimeRandomization();
414 // A map from FieldTrial names to the actual instances.
415 typedef std::map
<std::string
, FieldTrial
*> RegistrationList
;
417 // Helper function should be called only while holding lock_.
418 FieldTrial
* PreLockedFind(const std::string
& name
);
420 // Register() stores a pointer to the given trial in a global map.
421 // This method also AddRef's the indicated trial.
422 // This should always be called after creating a new FieldTrial instance.
423 static void Register(FieldTrial
* trial
);
425 static FieldTrialList
* global_
; // The singleton of this class.
427 // This will tell us if there is an attempt to register a field
428 // trial or check if one-time randomization is enabled without
429 // creating the FieldTrialList. This is not an error, unless a
430 // FieldTrialList is created after that.
431 static bool used_without_global_
;
433 // Lock for access to registered_.
435 RegistrationList registered_
;
437 // Entropy provider to be used for one-time randomized field trials. If NULL,
438 // one-time randomization is not supported.
439 scoped_ptr
<const FieldTrial::EntropyProvider
> entropy_provider_
;
441 // List of observers to be notified when a group is selected for a FieldTrial.
442 scoped_refptr
<ObserverListThreadSafe
<Observer
> > observer_list_
;
444 DISALLOW_COPY_AND_ASSIGN(FieldTrialList
);
449 #endif // BASE_METRICS_FIELD_TRIAL_H_