Reporting of policy errors via host-offline-reason: part 1
[chromium-blink-merge.git] / base / metrics / field_trial.h
blobe2e543947a10a97595b828c63a432c7710aaab79
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.
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).
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).
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:
27 // UMA_HISTOGRAM_COUNTS("Memory.RendererTotal", count);
29 // Somewhere in main thread initialization code, we'd probably define an
30 // instance of a FieldTrial, with code such as:
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));
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.
52 //------------------------------------------------------------------------------
54 #ifndef BASE_METRICS_FIELD_TRIAL_H_
55 #define BASE_METRICS_FIELD_TRIAL_H_
57 #include <map>
58 #include <set>
59 #include <string>
60 #include <vector>
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"
69 namespace base {
71 class FieldTrialList;
73 class BASE_EXPORT FieldTrial : public RefCounted<FieldTrial> {
74 public:
75 typedef int Probability; // Probability type for being selected in a trial.
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,
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();
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;
103 // A pair representing a Field Trial and its selected group.
104 struct ActiveGroup {
105 std::string trial_name;
106 std::string group_name;
109 typedef std::vector<ActiveGroup> ActiveGroups;
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;
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();
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);
130 // Return the name of the FieldTrial (excluding the group name).
131 const std::string& trial_name() const { return trial_name_; }
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();
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();
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();
154 // Enable benchmarking sets field trials to a common setting.
155 static void EnableBenchmarking();
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).
162 // Note: Using this function will not register the field trial globally in the
163 // running process - for that, use FieldTrialList::FactoryGetFieldTrial().
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);
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);
193 friend class base::FieldTrialList;
195 friend class RefCounted<FieldTrial>;
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;
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();
210 // Return the default group name of the FieldTrial.
211 std::string default_group_name() const { return default_group_name_; }
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();
217 // Sets the chosen group name and number.
218 void SetGroupChoice(const std::string& group_name, int number);
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();
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;
233 // Returns the group_name. A winner need not have been chosen.
234 std::string group_name_internal() const { return group_name_; }
236 // The name of the field trial, as can be found via the FieldTrialList.
237 const std::string trial_name_;
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_;
243 // The name of the default group.
244 const std::string default_group_name_;
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_;
251 // Sum of the probabilities of all appended groups.
252 Probability accumulated_group_probability_;
254 // The number that will be returned by the next AppendGroup() call.
255 int next_group_number_;
257 // The pseudo-randomly assigned group number.
258 // This is kNotFinalized if no group has been assigned.
259 int group_;
261 // A textual name for the randomly selected group. Valid after |group()|
262 // has been called.
263 std::string group_name_;
265 // When enable_field_trial_ is false, field trial reverts to the 'default'
266 // group.
267 bool enable_field_trial_;
269 // When forced_ is true, we return the chosen group from AppendGroup when
270 // appropriate.
271 bool forced_;
273 // Specifies whether the group choice has been reported to observers.
274 bool group_reported_;
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_;
280 // When benchmarking is enabled, field trials all revert to the 'default'
281 // group.
282 static bool enable_benchmarking_;
284 DISALLOW_COPY_AND_ASSIGN(FieldTrial);
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.
291 class BASE_EXPORT FieldTrialList {
292 public:
293 // Specifies whether field trials should be activated (marked as "used"), when
294 // created using |CreateTrialsFromString()|. Has no effect on trials that are
295 // prefixed with |kActivationMarker|, which will always be activated."
296 enum FieldTrialActivationMode {
297 DONT_ACTIVATE_TRIALS,
298 ACTIVATE_TRIALS,
301 // Define a separator character to use when creating a persistent form of an
302 // instance. This is intended for use as a command line argument, passed to a
303 // second process to mimic our state (i.e., provide the same group name).
304 static const char kPersistentStringSeparator; // Currently a slash.
306 // Define a marker character to be used as a prefix to a trial name on the
307 // command line which forces its activation.
308 static const char kActivationMarker; // Currently an asterisk.
310 // Year that is guaranteed to not be expired when instantiating a field trial
311 // via |FactoryGetFieldTrial()|. Set to two years from the build date.
312 static int kNoExpirationYear;
314 // Observer is notified when a FieldTrial's group is selected.
315 class BASE_EXPORT Observer {
316 public:
317 // Notify observers when FieldTrials's group is selected.
318 virtual void OnFieldTrialGroupFinalized(const std::string& trial_name,
319 const std::string& group_name) = 0;
321 protected:
322 virtual ~Observer();
325 // This singleton holds the global list of registered FieldTrials.
327 // To support one-time randomized field trials, specify a non-NULL
328 // |entropy_provider| which should be a source of uniformly distributed
329 // entropy values. Takes ownership of |entropy_provider|. If one time
330 // randomization is not desired, pass in NULL for |entropy_provider|.
331 explicit FieldTrialList(const FieldTrial::EntropyProvider* entropy_provider);
333 // Destructor Release()'s references to all registered FieldTrial instances.
334 ~FieldTrialList();
336 // Get a FieldTrial instance from the factory.
338 // |name| is used to register the instance with the FieldTrialList class,
339 // and can be used to find the trial (only one trial can be present for each
340 // name). |default_group_name| is the name of the default group which will
341 // be chosen if none of the subsequent appended groups get to be chosen.
342 // |default_group_number| can receive the group number of the default group as
343 // AppendGroup returns the number of the subsequence groups. |trial_name| and
344 // |default_group_name| may not be empty but |default_group_number| can be
345 // NULL if the value is not needed.
347 // Group probabilities that are later supplied must sum to less than or equal
348 // to the |total_probability|. Arguments |year|, |month| and |day_of_month|
349 // specify the expiration time. If the build time is after the expiration time
350 // then the field trial reverts to the 'default' group.
352 // Use this static method to get a startup-randomized FieldTrial or a
353 // previously created forced FieldTrial.
354 static FieldTrial* FactoryGetFieldTrial(
355 const std::string& trial_name,
356 FieldTrial::Probability total_probability,
357 const std::string& default_group_name,
358 const int year,
359 const int month,
360 const int day_of_month,
361 FieldTrial::RandomizationType randomization_type,
362 int* default_group_number);
364 // Same as FactoryGetFieldTrial(), but allows specifying a custom seed to be
365 // used on one-time randomized field trials (instead of a hash of the trial
366 // name, which is used otherwise or if |randomization_seed| has value 0). The
367 // |randomization_seed| value (other than 0) should never be the same for two
368 // trials, else this would result in correlated group assignments.
369 // Note: Using a custom randomization seed is only supported by the
370 // PermutedEntropyProvider (which is used when UMA is not enabled).
371 static FieldTrial* FactoryGetFieldTrialWithRandomizationSeed(
372 const std::string& trial_name,
373 FieldTrial::Probability total_probability,
374 const std::string& default_group_name,
375 const int year,
376 const int month,
377 const int day_of_month,
378 FieldTrial::RandomizationType randomization_type,
379 uint32 randomization_seed,
380 int* default_group_number);
382 // The Find() method can be used to test to see if a named Trial was already
383 // registered, or to retrieve a pointer to it from the global map.
384 static FieldTrial* Find(const std::string& name);
386 // Returns the group number chosen for the named trial, or
387 // FieldTrial::kNotFinalized if the trial does not exist.
388 static int FindValue(const std::string& name);
390 // Returns the group name chosen for the named trial, or the
391 // empty string if the trial does not exist.
392 static std::string FindFullName(const std::string& name);
394 // Returns true if the named trial has been registered.
395 static bool TrialExists(const std::string& name);
397 // Creates a persistent representation of active FieldTrial instances for
398 // resurrection in another process. This allows randomization to be done in
399 // one process, and secondary processes can be synchronized on the result.
400 // The resulting string contains the name and group name pairs of all
401 // registered FieldTrials for which the group has been chosen and externally
402 // observed (via |group()|) and which have not been disabled, with "/" used
403 // to separate all names and to terminate the string. This string is parsed
404 // by |CreateTrialsFromString()|.
405 static void StatesToString(std::string* output);
407 // Fills in the supplied vector |active_groups| (which must be empty when
408 // called) with a snapshot of all registered FieldTrials for which the group
409 // has been chosen and externally observed (via |group()|) and which have
410 // not been disabled.
411 static void GetActiveFieldTrialGroups(
412 FieldTrial::ActiveGroups* active_groups);
414 // Use a state string (re: StatesToString()) to augment the current list of
415 // field trials to include the supplied trials, and using a 100% probability
416 // for each trial, force them to have the same group string. This is commonly
417 // used in a non-browser process, to carry randomly selected state in a
418 // browser process into this non-browser process, but could also be invoked
419 // through a command line argument to the browser process. The created field
420 // trials are all marked as "used" for the purposes of active trial reporting
421 // if |mode| is ACTIVATE_TRIALS, otherwise each trial will be marked as "used"
422 // if it is prefixed with |kActivationMarker|. Trial names in
423 // |ignored_trial_names| are ignored when parsing |prior_trials|.
424 static bool CreateTrialsFromString(
425 const std::string& prior_trials,
426 FieldTrialActivationMode mode,
427 const std::set<std::string>& ignored_trial_names);
429 // Create a FieldTrial with the given |name| and using 100% probability for
430 // the FieldTrial, force FieldTrial to have the same group string as
431 // |group_name|. This is commonly used in a non-browser process, to carry
432 // randomly selected state in a browser process into this non-browser process.
433 // It returns NULL if there is a FieldTrial that is already registered with
434 // the same |name| but has different finalized group string (|group_name|).
435 static FieldTrial* CreateFieldTrial(const std::string& name,
436 const std::string& group_name);
438 // Add an observer to be notified when a field trial is irrevocably committed
439 // to being part of some specific field_group (and hence the group_name is
440 // also finalized for that field_trial).
441 static void AddObserver(Observer* observer);
443 // Remove an observer.
444 static void RemoveObserver(Observer* observer);
446 // Notify all observers that a group has been finalized for |field_trial|.
447 static void NotifyFieldTrialGroupSelection(FieldTrial* field_trial);
449 // Return the number of active field trials.
450 static size_t GetFieldTrialCount();
452 private:
453 // A map from FieldTrial names to the actual instances.
454 typedef std::map<std::string, FieldTrial*> RegistrationMap;
456 // If one-time randomization is enabled, returns a weak pointer to the
457 // corresponding EntropyProvider. Otherwise, returns NULL.
458 static const FieldTrial::EntropyProvider*
459 GetEntropyProviderForOneTimeRandomization();
461 // Helper function should be called only while holding lock_.
462 FieldTrial* PreLockedFind(const std::string& name);
464 // Register() stores a pointer to the given trial in a global map.
465 // This method also AddRef's the indicated trial.
466 // This should always be called after creating a new FieldTrial instance.
467 static void Register(FieldTrial* trial);
469 static FieldTrialList* global_; // The singleton of this class.
471 // This will tell us if there is an attempt to register a field
472 // trial or check if one-time randomization is enabled without
473 // creating the FieldTrialList. This is not an error, unless a
474 // FieldTrialList is created after that.
475 static bool used_without_global_;
477 // Lock for access to registered_.
478 base::Lock lock_;
479 RegistrationMap registered_;
481 // Entropy provider to be used for one-time randomized field trials. If NULL,
482 // one-time randomization is not supported.
483 scoped_ptr<const FieldTrial::EntropyProvider> entropy_provider_;
485 // List of observers to be notified when a group is selected for a FieldTrial.
486 scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_;
488 DISALLOW_COPY_AND_ASSIGN(FieldTrialList);
491 } // namespace base
493 #endif // BASE_METRICS_FIELD_TRIAL_H_