Make certificate viewer a tab-modal dialog.
[chromium-blink-merge.git] / base / metrics / field_trial.h
blobb9a5b66dfaa2228e4a8b513c7c0965af942d5a74
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 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
36 // // FieldTrialList.
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,
42 // NULL));
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);
63 // }
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_
79 #include <map>
80 #include <string>
81 #include <vector>
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"
90 namespace base {
92 class FieldTrialList;
94 class BASE_EXPORT FieldTrial : public RefCounted<FieldTrial> {
95 public:
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 {
101 public:
102 virtual ~EntropyProvider();
104 // Returns a double in the range of [0, 1) to be used for the dice roll for
105 // the specified field trial. If |randomization_seed| is not 0, it will be
106 // used in preference to |trial_name| for generating the entropy by entropy
107 // providers that support it. A given instance should always return the same
108 // value given the same input |trial_name| and |randomization_seed| values.
109 virtual double GetEntropyForTrial(const std::string& trial_name,
110 uint32 randomization_seed) const = 0;
113 // A pair representing a Field Trial and its selected group.
114 struct ActiveGroup {
115 std::string trial_name;
116 std::string group_name;
119 typedef std::vector<ActiveGroup> ActiveGroups;
121 // A return value to indicate that a given instance has not yet had a group
122 // assignment (and hence is not yet participating in the trial).
123 static const int kNotFinalized;
125 // Changes the field trial to use one-time randomization, i.e. produce the
126 // same result for the current trial on every run of this client. Must be
127 // called right after construction, before any groups are added.
128 void UseOneTimeRandomization();
130 // Changes the field trial to use one-time randomization, i.e. produce the
131 // same result for the current trial on every run of this client, with a
132 // custom randomization seed for the trial. The |randomization_seed| value
133 // should never be the same for two trials, else this would result in
134 // correlated group assignments. Must be called right after construction,
135 // before any groups are added.
136 void UseOneTimeRandomizationWithCustomSeed(uint32 randomization_seed);
138 // Disables this trial, meaning it always determines the default group
139 // has been selected. May be called immediately after construction, or
140 // at any time after initialization (should not be interleaved with
141 // AppendGroup calls). Once disabled, there is no way to re-enable a
142 // trial.
143 // TODO(mad): http://code.google.com/p/chromium/issues/detail?id=121446
144 // This doesn't properly reset to Default when a group was forced.
145 void Disable();
147 // Establish the name and probability of the next group in this trial.
148 // Sometimes, based on construction randomization, this call may cause the
149 // provided group to be *THE* group selected for use in this instance.
150 // The return value is the group number of the new group.
151 int AppendGroup(const std::string& name, Probability group_probability);
153 // Return the name of the FieldTrial (excluding the group name).
154 const std::string& trial_name() const { return trial_name_; }
156 // Return the randomly selected group number that was assigned, and notify
157 // any/all observers that this finalized group number has presumably been used
158 // (queried), and will never change. Note that this will force an instance to
159 // participate, and make it illegal to attempt to probabilistically add any
160 // other groups to the trial.
161 int group();
163 // If the group's name is empty, a string version containing the group number
164 // is used as the group name. This causes a winner to be chosen if none was.
165 const std::string& group_name();
167 // Helper function for the most common use: as an argument to specify the
168 // name of a HISTOGRAM. Use the original histogram name as the name_prefix.
169 static std::string MakeName(const std::string& name_prefix,
170 const std::string& trial_name);
172 // Enable benchmarking sets field trials to a common setting.
173 static void EnableBenchmarking();
175 // Set the field trial as forced, meaning that it was setup earlier than
176 // the hard coded registration of the field trial to override it.
177 // This allows the code that was hard coded to register the field trial to
178 // still succeed even though the field trial has already been registered.
179 // This must be called after appending all the groups, since we will make
180 // the group choice here. Note that this is a NOOP for already forced trials.
181 // And, as the rest of the FieldTrial code, this is not thread safe and must
182 // be done from the UI thread.
183 void SetForced();
185 private:
186 // Allow tests to access our innards for testing purposes.
187 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, Registration);
188 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, AbsoluteProbabilities);
189 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, RemainingProbability);
190 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, FiftyFiftyProbability);
191 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, MiddleProbabilities);
192 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, OneWinner);
193 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DisableProbability);
194 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, ActiveGroups);
195 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, ActiveGroupsNotFinalized);
196 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, Save);
197 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DuplicateRestore);
198 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, MakeName);
199 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, HashClientId);
200 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, HashClientIdIsUniform);
201 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, NameGroupIds);
202 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, UseOneTimeRandomization);
203 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedTurnFeatureOff);
204 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedTurnFeatureOn);
205 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedChangeDefault_Default);
206 FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedChangeDefault_NonDefault);
208 friend class base::FieldTrialList;
210 friend class RefCounted<FieldTrial>;
212 // This is the group number of the 'default' group when a choice wasn't forced
213 // by a call to FieldTrialList::CreateFieldTrial. It is kept private so that
214 // consumers don't use it by mistake in cases where the group was forced.
215 static const int kDefaultGroupNumber;
217 FieldTrial(const std::string& name,
218 Probability total_probability,
219 const std::string& default_group_name);
220 virtual ~FieldTrial();
222 // Return the default group name of the FieldTrial.
223 std::string default_group_name() const { return default_group_name_; }
225 // Sets the chosen group name and number.
226 void SetGroupChoice(const std::string& group_name, int number);
228 // Ensures that a group is chosen, if it hasn't yet been. The field trial
229 // might yet be disabled, so this call will *not* notify observers of the
230 // status.
231 void FinalizeGroupChoice();
233 // Returns the trial name and selected group name for this field trial via
234 // the output parameter |active_group|, but only if the group has already
235 // been chosen and has been externally observed via |group()| and the trial
236 // has not been disabled. In that case, true is returned and |active_group|
237 // is filled in; otherwise, the result is false and |active_group| is left
238 // untouched.
239 bool GetActiveGroup(ActiveGroup* active_group) const;
241 // Returns the group_name. A winner need not have been chosen.
242 std::string group_name_internal() const { return group_name_; }
244 // The name of the field trial, as can be found via the FieldTrialList.
245 const std::string trial_name_;
247 // The maximum sum of all probabilities supplied, which corresponds to 100%.
248 // This is the scaling factor used to adjust supplied probabilities.
249 const Probability divisor_;
251 // The name of the default group.
252 const std::string default_group_name_;
254 // The randomly selected probability that is used to select a group (or have
255 // the instance not participate). It is the product of divisor_ and a random
256 // number between [0, 1).
257 Probability random_;
259 // Sum of the probabilities of all appended groups.
260 Probability accumulated_group_probability_;
262 int next_group_number_;
264 // The pseudo-randomly assigned group number.
265 // This is kNotFinalized if no group has been assigned.
266 int group_;
268 // A textual name for the randomly selected group. Valid after |group()|
269 // has been called.
270 std::string group_name_;
272 // When enable_field_trial_ is false, field trial reverts to the 'default'
273 // group.
274 bool enable_field_trial_;
276 // When forced_ is true, we return the chosen group from AppendGroup when
277 // appropriate.
278 bool forced_;
280 // Specifies whether the group choice has been reported to observers.
281 bool group_reported_;
283 // When benchmarking is enabled, field trials all revert to the 'default'
284 // group.
285 static bool enable_benchmarking_;
287 DISALLOW_COPY_AND_ASSIGN(FieldTrial);
290 //------------------------------------------------------------------------------
291 // Class with a list of all active field trials. A trial is active if it has
292 // been registered, which includes evaluating its state based on its probaility.
293 // Only one instance of this class exists.
294 class BASE_EXPORT FieldTrialList {
295 public:
296 // Define a separator character to use when creating a persistent form of an
297 // instance. This is intended for use as a command line argument, passed to a
298 // second process to mimic our state (i.e., provide the same group name).
299 static const char kPersistentStringSeparator; // Currently a slash.
301 // Year that is guaranteed to not be expired when instantiating a field trial
302 // via |FactoryGetFieldTrial()|. Set to two years from the build date.
303 static int kNoExpirationYear;
305 // Observer is notified when a FieldTrial's group is selected.
306 class BASE_EXPORT Observer {
307 public:
308 // Notify observers when FieldTrials's group is selected.
309 virtual void OnFieldTrialGroupFinalized(const std::string& trial_name,
310 const std::string& group_name) = 0;
312 protected:
313 virtual ~Observer();
316 // This singleton holds the global list of registered FieldTrials.
318 // To support one-time randomized field trials, specify a non-NULL
319 // |entropy_provider| which should be a source of uniformly distributed
320 // entropy values. Takes ownership of |entropy_provider|. If one time
321 // randomization is not desired, pass in NULL for |entropy_provider|.
322 explicit FieldTrialList(const FieldTrial::EntropyProvider* entropy_provider);
324 // Destructor Release()'s references to all registered FieldTrial instances.
325 ~FieldTrialList();
327 // Get a FieldTrial instance from the factory.
329 // |name| is used to register the instance with the FieldTrialList class,
330 // and can be used to find the trial (only one trial can be present for each
331 // name). |default_group_name| is the name of the default group which will
332 // be chosen if none of the subsequent appended groups get to be chosen.
333 // |default_group_number| can receive the group number of the default group as
334 // AppendGroup returns the number of the subsequence groups. |trial_name| and
335 // |default_group_name| may not be empty but |default_group_number| can be
336 // NULL if the value is not needed.
338 // Group probabilities that are later supplied must sum to less than or equal
339 // to the |total_probability|. Arguments |year|, |month| and |day_of_month|
340 // specify the expiration time. If the build time is after the expiration time
341 // then the field trial reverts to the 'default' group.
343 // Use this static method to get a startup-randomized FieldTrial or a
344 // previously created forced FieldTrial. If you want a one-time randomized
345 // trial, call UseOneTimeRandomization() right after creation.
346 static FieldTrial* FactoryGetFieldTrial(
347 const std::string& trial_name,
348 FieldTrial::Probability total_probability,
349 const std::string& default_group_name,
350 const int year,
351 const int month,
352 const int day_of_month,
353 int* default_group_number);
355 // The Find() method can be used to test to see if a named Trial was already
356 // registered, or to retrieve a pointer to it from the global map.
357 static FieldTrial* Find(const std::string& name);
359 // Returns the group number chosen for the named trial, or
360 // FieldTrial::kNotFinalized if the trial does not exist.
361 static int FindValue(const std::string& name);
363 // Returns the group name chosen for the named trial, or the
364 // empty string if the trial does not exist.
365 static std::string FindFullName(const std::string& name);
367 // Returns true if the named trial has been registered.
368 static bool TrialExists(const std::string& name);
370 // Creates a persistent representation of active FieldTrial instances for
371 // resurrection in another process. This allows randomization to be done in
372 // one process, and secondary processes can be synchronized on the result.
373 // The resulting string contains the name and group name pairs of all
374 // registered FieldTrials for which the group has been chosen and externally
375 // observed (via |group()|) and which have not been disabled, with "/" used
376 // to separate all names and to terminate the string. This string is parsed
377 // by |CreateTrialsFromString()|.
378 static void StatesToString(std::string* output);
380 // Fills in the supplied vector |active_groups| (which must be empty when
381 // called) with a snapshot of all registered FieldTrials for which the group
382 // has been chosen and externally observed (via |group()|) and which have
383 // not been disabled.
384 static void GetActiveFieldTrialGroups(
385 FieldTrial::ActiveGroups* active_groups);
387 // Use a state string (re: StatesToString()) to augment the current list of
388 // field trials to include the supplied trials, and using a 100% probability
389 // for each trial, force them to have the same group string. This is commonly
390 // used in a non-browser process, to carry randomly selected state in a
391 // browser process into this non-browser process, but could also be invoked
392 // through a command line argument to the browser process. The created field
393 // trials are marked as "used" for the purposes of active trial reporting.
394 static bool CreateTrialsFromString(const std::string& prior_trials);
396 // Create a FieldTrial with the given |name| and using 100% probability for
397 // the FieldTrial, force FieldTrial to have the same group string as
398 // |group_name|. This is commonly used in a non-browser process, to carry
399 // randomly selected state in a browser process into this non-browser process.
400 // It returns NULL if there is a FieldTrial that is already registered with
401 // the same |name| but has different finalized group string (|group_name|).
402 static FieldTrial* CreateFieldTrial(const std::string& name,
403 const std::string& group_name);
405 // Add an observer to be notified when a field trial is irrevocably committed
406 // to being part of some specific field_group (and hence the group_name is
407 // also finalized for that field_trial).
408 static void AddObserver(Observer* observer);
410 // Remove an observer.
411 static void RemoveObserver(Observer* observer);
413 // Notify all observers that a group has been finalized for |field_trial|.
414 static void NotifyFieldTrialGroupSelection(FieldTrial* field_trial);
416 // Return the number of active field trials.
417 static size_t GetFieldTrialCount();
419 // If one-time randomization is enabled, returns a weak pointer to the
420 // corresponding EntropyProvider. Otherwise, returns NULL.
421 static const FieldTrial::EntropyProvider*
422 GetEntropyProviderForOneTimeRandomization();
424 private:
425 // A map from FieldTrial names to the actual instances.
426 typedef std::map<std::string, FieldTrial*> RegistrationList;
428 // Helper function should be called only while holding lock_.
429 FieldTrial* PreLockedFind(const std::string& name);
431 // Register() stores a pointer to the given trial in a global map.
432 // This method also AddRef's the indicated trial.
433 // This should always be called after creating a new FieldTrial instance.
434 static void Register(FieldTrial* trial);
436 static FieldTrialList* global_; // The singleton of this class.
438 // This will tell us if there is an attempt to register a field
439 // trial or check if one-time randomization is enabled without
440 // creating the FieldTrialList. This is not an error, unless a
441 // FieldTrialList is created after that.
442 static bool used_without_global_;
444 // Lock for access to registered_.
445 base::Lock lock_;
446 RegistrationList registered_;
448 // Entropy provider to be used for one-time randomized field trials. If NULL,
449 // one-time randomization is not supported.
450 scoped_ptr<const FieldTrial::EntropyProvider> entropy_provider_;
452 // List of observers to be notified when a group is selected for a FieldTrial.
453 scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_;
455 DISALLOW_COPY_AND_ASSIGN(FieldTrialList);
458 } // namespace base
460 #endif // BASE_METRICS_FIELD_TRIAL_H_