Fix +x on Windows-only binary after https://chromium.googlesource.com/chromium/src...
[chromium-blink-merge.git] / components / omnibox / omnibox_field_trial.cc
blob6dd2302fdebd84b8dccd7a6f3b0c93f87387ec8a
1 // Copyright 2014 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 #include "components/omnibox/omnibox_field_trial.h"
7 #include <cmath>
8 #include <string>
10 #include "base/command_line.h"
11 #include "base/metrics/field_trial.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/time/time.h"
17 #include "components/metrics/proto/omnibox_event.pb.h"
18 #include "components/omnibox/omnibox_switches.h"
19 #include "components/search/search.h"
20 #include "components/variations/active_field_trials.h"
21 #include "components/variations/metrics_util.h"
22 #include "components/variations/variations_associated_data.h"
24 using metrics::OmniboxEventProto;
26 namespace {
28 typedef std::map<std::string, std::string> VariationParams;
29 typedef HUPScoringParams::ScoreBuckets ScoreBuckets;
31 // Field trial names.
32 const char kStopTimerFieldTrialName[] = "OmniboxStopTimer";
34 // The autocomplete dynamic field trial name prefix. Each field trial is
35 // configured dynamically and is retrieved automatically by Chrome during
36 // the startup.
37 const char kAutocompleteDynamicFieldTrialPrefix[] = "AutocompleteDynamicTrial_";
38 // The maximum number of the autocomplete dynamic field trials (aka layers).
39 const int kMaxAutocompleteDynamicFieldTrials = 5;
42 // Concatenates the autocomplete dynamic field trial prefix with a field trial
43 // ID to form a complete autocomplete field trial name.
44 std::string DynamicFieldTrialName(int id) {
45 return base::StringPrintf("%s%d", kAutocompleteDynamicFieldTrialPrefix, id);
48 void InitializeScoreBuckets(const VariationParams& params,
49 const char* relevance_cap_param,
50 const char* half_life_param,
51 const char* score_buckets_param,
52 ScoreBuckets* score_buckets) {
53 VariationParams::const_iterator it = params.find(relevance_cap_param);
54 if (it != params.end()) {
55 int relevance_cap;
56 if (base::StringToInt(it->second, &relevance_cap))
57 score_buckets->set_relevance_cap(relevance_cap);
60 it = params.find(half_life_param);
61 if (it != params.end()) {
62 int half_life_days;
63 if (base::StringToInt(it->second, &half_life_days))
64 score_buckets->set_half_life_days(half_life_days);
67 it = params.find(score_buckets_param);
68 if (it != params.end()) {
69 // The value of the score bucket is a comma-separated list of
70 // {DecayedCount + ":" + MaxRelevance}.
71 base::StringPairs kv_pairs;
72 if (base::SplitStringIntoKeyValuePairs(it->second, ':', ',', &kv_pairs)) {
73 for (base::StringPairs::const_iterator it = kv_pairs.begin();
74 it != kv_pairs.end(); ++it) {
75 ScoreBuckets::CountMaxRelevance bucket;
76 base::StringToDouble(it->first, &bucket.first);
77 base::StringToInt(it->second, &bucket.second);
78 score_buckets->buckets().push_back(bucket);
80 std::sort(score_buckets->buckets().begin(),
81 score_buckets->buckets().end(),
82 std::greater<ScoreBuckets::CountMaxRelevance>());
87 } // namespace
89 HUPScoringParams::ScoreBuckets::ScoreBuckets()
90 : relevance_cap_(-1),
91 half_life_days_(-1) {
94 HUPScoringParams::ScoreBuckets::~ScoreBuckets() {
97 double HUPScoringParams::ScoreBuckets::HalfLifeTimeDecay(
98 const base::TimeDelta& elapsed_time) const {
99 double time_ms;
100 if ((half_life_days_ <= 0) ||
101 ((time_ms = elapsed_time.InMillisecondsF()) <= 0))
102 return 1.0;
104 const double half_life_intervals =
105 time_ms / base::TimeDelta::FromDays(half_life_days_).InMillisecondsF();
106 return pow(2.0, -half_life_intervals);
109 void OmniboxFieldTrial::ActivateDynamicTrials() {
110 // Initialize all autocomplete dynamic field trials. This method may be
111 // called multiple times.
112 for (int i = 0; i < kMaxAutocompleteDynamicFieldTrials; ++i)
113 base::FieldTrialList::FindValue(DynamicFieldTrialName(i));
116 int OmniboxFieldTrial::GetDisabledProviderTypes() {
117 const std::string& types_string = variations::GetVariationParamValue(
118 kBundledExperimentFieldTrialName,
119 kDisableProvidersRule);
120 int types = 0;
121 if (types_string.empty() || !base::StringToInt(types_string, &types)) {
122 return 0;
124 return types;
127 void OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(
128 std::vector<uint32>* field_trial_hashes) {
129 field_trial_hashes->clear();
130 for (int i = 0; i < kMaxAutocompleteDynamicFieldTrials; ++i) {
131 const std::string& trial_name = DynamicFieldTrialName(i);
132 if (base::FieldTrialList::TrialExists(trial_name))
133 field_trial_hashes->push_back(metrics::HashName(trial_name));
135 if (base::FieldTrialList::TrialExists(kBundledExperimentFieldTrialName)) {
136 field_trial_hashes->push_back(
137 metrics::HashName(kBundledExperimentFieldTrialName));
141 base::TimeDelta OmniboxFieldTrial::StopTimerFieldTrialDuration() {
142 int stop_timer_ms;
143 if (base::StringToInt(
144 base::FieldTrialList::FindFullName(kStopTimerFieldTrialName),
145 &stop_timer_ms))
146 return base::TimeDelta::FromMilliseconds(stop_timer_ms);
147 return base::TimeDelta::FromMilliseconds(1500);
150 bool OmniboxFieldTrial::InZeroSuggestFieldTrial() {
151 if (variations::GetVariationParamValue(
152 kBundledExperimentFieldTrialName, kZeroSuggestRule) == "true")
153 return true;
154 if (variations::GetVariationParamValue(
155 kBundledExperimentFieldTrialName, kZeroSuggestRule) == "false")
156 return false;
157 #if defined(OS_WIN) || defined(OS_CHROMEOS) || defined(OS_LINUX) || \
158 (defined(OS_MACOSX) && !defined(OS_IOS))
159 return true;
160 #else
161 return false;
162 #endif
165 bool OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial() {
166 return InZeroSuggestMostVisitedWithoutSerpFieldTrial() ||
167 variations::GetVariationParamValue(
168 kBundledExperimentFieldTrialName,
169 kZeroSuggestVariantRule) == "MostVisited";
172 bool OmniboxFieldTrial::InZeroSuggestMostVisitedWithoutSerpFieldTrial() {
173 return variations::GetVariationParamValue(
174 kBundledExperimentFieldTrialName,
175 kZeroSuggestVariantRule) == "MostVisitedWithoutSERP";
178 bool OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial() {
179 return variations::GetVariationParamValue(
180 kBundledExperimentFieldTrialName,
181 kZeroSuggestVariantRule) == "AfterTyping";
184 bool OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() {
185 return variations::GetVariationParamValue(
186 kBundledExperimentFieldTrialName,
187 kZeroSuggestVariantRule) == "Personalized";
190 bool OmniboxFieldTrial::ShortcutsScoringMaxRelevance(
191 OmniboxEventProto::PageClassification current_page_classification,
192 int* max_relevance) {
193 // The value of the rule is a string that encodes an integer containing
194 // the max relevance.
195 const std::string& max_relevance_str =
196 OmniboxFieldTrial::GetValueForRuleInContext(
197 kShortcutsScoringMaxRelevanceRule, current_page_classification);
198 if (max_relevance_str.empty())
199 return false;
200 if (!base::StringToInt(max_relevance_str, max_relevance))
201 return false;
202 return true;
205 bool OmniboxFieldTrial::SearchHistoryPreventInlining(
206 OmniboxEventProto::PageClassification current_page_classification) {
207 return OmniboxFieldTrial::GetValueForRuleInContext(
208 kSearchHistoryRule, current_page_classification) == "PreventInlining";
211 bool OmniboxFieldTrial::SearchHistoryDisable(
212 OmniboxEventProto::PageClassification current_page_classification) {
213 return OmniboxFieldTrial::GetValueForRuleInContext(
214 kSearchHistoryRule, current_page_classification) == "Disable";
217 void OmniboxFieldTrial::GetDemotionsByType(
218 OmniboxEventProto::PageClassification current_page_classification,
219 DemotionMultipliers* demotions_by_type) {
220 demotions_by_type->clear();
221 std::string demotion_rule = OmniboxFieldTrial::GetValueForRuleInContext(
222 kDemoteByTypeRule, current_page_classification);
223 // If there is no demotion rule for this context, then use the default
224 // value for that context. At the moment the default value is non-empty
225 // only for the fakebox-focus context.
226 if (demotion_rule.empty() &&
227 (current_page_classification ==
228 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS))
229 demotion_rule = "1:61,2:61,3:61,4:61,16:61";
231 // The value of the DemoteByType rule is a comma-separated list of
232 // {ResultType + ":" + Number} where ResultType is an AutocompleteMatchType::
233 // Type enum represented as an integer and Number is an integer number
234 // between 0 and 100 inclusive. Relevance scores of matches of that result
235 // type are multiplied by Number / 100. 100 means no change.
236 base::StringPairs kv_pairs;
237 if (base::SplitStringIntoKeyValuePairs(demotion_rule, ':', ',', &kv_pairs)) {
238 for (base::StringPairs::const_iterator it = kv_pairs.begin();
239 it != kv_pairs.end(); ++it) {
240 // This is a best-effort conversion; we trust the hand-crafted parameters
241 // downloaded from the server to be perfect. There's no need to handle
242 // errors smartly.
243 int k, v;
244 base::StringToInt(it->first, &k);
245 base::StringToInt(it->second, &v);
246 (*demotions_by_type)[static_cast<AutocompleteMatchType::Type>(k)] =
247 static_cast<float>(v) / 100.0f;
252 void OmniboxFieldTrial::GetExperimentalHUPScoringParams(
253 HUPScoringParams* scoring_params) {
254 scoring_params->experimental_scoring_enabled = false;
256 VariationParams params;
257 if (!variations::GetVariationParams(kBundledExperimentFieldTrialName,
258 &params))
259 return;
261 VariationParams::const_iterator it = params.find(kHUPNewScoringEnabledParam);
262 if (it != params.end()) {
263 int enabled = 0;
264 if (base::StringToInt(it->second, &enabled))
265 scoring_params->experimental_scoring_enabled = (enabled != 0);
268 InitializeScoreBuckets(params, kHUPNewScoringTypedCountRelevanceCapParam,
269 kHUPNewScoringTypedCountHalfLifeTimeParam,
270 kHUPNewScoringTypedCountScoreBucketsParam,
271 &scoring_params->typed_count_buckets);
272 InitializeScoreBuckets(params, kHUPNewScoringVisitedCountRelevanceCapParam,
273 kHUPNewScoringVisitedCountHalfLifeTimeParam,
274 kHUPNewScoringVisitedCountScoreBucketsParam,
275 &scoring_params->visited_count_buckets);
278 int OmniboxFieldTrial::HQPBookmarkValue() {
279 std::string bookmark_value_str =
280 variations::GetVariationParamValue(kBundledExperimentFieldTrialName,
281 kHQPBookmarkValueRule);
282 if (bookmark_value_str.empty())
283 return 10;
284 // This is a best-effort conversion; we trust the hand-crafted parameters
285 // downloaded from the server to be perfect. There's no need for handle
286 // errors smartly.
287 int bookmark_value;
288 base::StringToInt(bookmark_value_str, &bookmark_value);
289 return bookmark_value;
292 bool OmniboxFieldTrial::HQPExperimentalScoringEnabled() {
293 return variations::GetVariationParamValue(
294 kBundledExperimentFieldTrialName,
295 kHQPExperimentalScoringEnabledParam) == "true";
298 std::string OmniboxFieldTrial::HQPExperimentalScoringBuckets() {
299 if (!HQPExperimentalScoringEnabled())
300 return "";
302 return variations::GetVariationParamValue(
303 kBundledExperimentFieldTrialName,
304 kHQPExperimentalScoringBucketsParam);
307 float OmniboxFieldTrial::HQPExperimentalTopicalityThreshold() {
308 if (!HQPExperimentalScoringEnabled())
309 return -1;
311 std::string topicality_threhold_str =
312 variations::GetVariationParamValue(
313 kBundledExperimentFieldTrialName,
314 kHQPExperimentalScoringTopicalityThresholdParam);
316 double topicality_threshold;
317 if (!base::StringToDouble(topicality_threhold_str, &topicality_threshold))
318 return -1;
320 return static_cast<float>(topicality_threshold);
323 bool OmniboxFieldTrial::HQPAllowMatchInTLDValue() {
324 return variations::GetVariationParamValue(
325 kBundledExperimentFieldTrialName,
326 kHQPAllowMatchInTLDRule) == "true";
329 bool OmniboxFieldTrial::HQPAllowMatchInSchemeValue() {
330 return variations::GetVariationParamValue(
331 kBundledExperimentFieldTrialName,
332 kHQPAllowMatchInSchemeRule) == "true";
335 bool OmniboxFieldTrial::EnableAnswersInSuggest() {
336 const base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
337 if (cl->HasSwitch(switches::kDisableAnswersInSuggest))
338 return false;
339 if (cl->HasSwitch(switches::kEnableAnswersInSuggest))
340 return true;
342 return variations::GetVariationParamValue(
343 kBundledExperimentFieldTrialName,
344 kAnswersInSuggestRule) == "true";
347 bool OmniboxFieldTrial::DisplayHintTextWhenPossible() {
348 return variations::GetVariationParamValue(
349 kBundledExperimentFieldTrialName,
350 kDisplayHintTextWhenPossibleRule) == "true";
353 bool OmniboxFieldTrial::DisableResultsCaching() {
354 return variations::GetVariationParamValue(
355 kBundledExperimentFieldTrialName,
356 kDisableResultsCachingRule) == "true";
359 void OmniboxFieldTrial::GetSuggestPollingStrategy(bool* from_last_keystroke,
360 int* polling_delay_ms) {
361 *from_last_keystroke = variations::GetVariationParamValue(
362 kBundledExperimentFieldTrialName,
363 kMeasureSuggestPollingDelayFromLastKeystrokeRule) == "true";
365 const std::string& polling_delay_string = variations::GetVariationParamValue(
366 kBundledExperimentFieldTrialName,
367 kSuggestPollingDelayMsRule);
368 if (polling_delay_string.empty() ||
369 !base::StringToInt(polling_delay_string, polling_delay_ms) ||
370 (*polling_delay_ms <= 0)) {
371 *polling_delay_ms = kDefaultMinimumTimeBetweenSuggestQueriesMs;
375 const char OmniboxFieldTrial::kBundledExperimentFieldTrialName[] =
376 "OmniboxBundledExperimentV1";
377 const char OmniboxFieldTrial::kDisableProvidersRule[] = "DisableProviders";
378 const char OmniboxFieldTrial::kShortcutsScoringMaxRelevanceRule[] =
379 "ShortcutsScoringMaxRelevance";
380 const char OmniboxFieldTrial::kSearchHistoryRule[] = "SearchHistory";
381 const char OmniboxFieldTrial::kDemoteByTypeRule[] = "DemoteByType";
382 const char OmniboxFieldTrial::kHQPBookmarkValueRule[] =
383 "HQPBookmarkValue";
384 const char OmniboxFieldTrial::kHQPAllowMatchInTLDRule[] = "HQPAllowMatchInTLD";
385 const char OmniboxFieldTrial::kHQPAllowMatchInSchemeRule[] =
386 "HQPAllowMatchInScheme";
387 const char OmniboxFieldTrial::kZeroSuggestRule[] = "ZeroSuggest";
388 const char OmniboxFieldTrial::kZeroSuggestVariantRule[] = "ZeroSuggestVariant";
389 const char OmniboxFieldTrial::kAnswersInSuggestRule[] = "AnswersInSuggest";
390 const char OmniboxFieldTrial::kDisplayHintTextWhenPossibleRule[] =
391 "DisplayHintTextWhenPossible";
392 const char OmniboxFieldTrial::kDisableResultsCachingRule[] =
393 "DisableResultsCaching";
394 const char
395 OmniboxFieldTrial::kMeasureSuggestPollingDelayFromLastKeystrokeRule[] =
396 "MeasureSuggestPollingDelayFromLastKeystroke";
397 const char OmniboxFieldTrial::kSuggestPollingDelayMsRule[] =
398 "SuggestPollingDelayMs";
400 const char OmniboxFieldTrial::kHUPNewScoringEnabledParam[] =
401 "HUPExperimentalScoringEnabled";
402 const char OmniboxFieldTrial::kHUPNewScoringTypedCountRelevanceCapParam[] =
403 "TypedCountRelevanceCap";
404 const char OmniboxFieldTrial::kHUPNewScoringTypedCountHalfLifeTimeParam[] =
405 "TypedCountHalfLifeTime";
406 const char OmniboxFieldTrial::kHUPNewScoringTypedCountScoreBucketsParam[] =
407 "TypedCountScoreBuckets";
408 const char OmniboxFieldTrial::kHUPNewScoringVisitedCountRelevanceCapParam[] =
409 "VisitedCountRelevanceCap";
410 const char OmniboxFieldTrial::kHUPNewScoringVisitedCountHalfLifeTimeParam[] =
411 "VisitedCountHalfLifeTime";
412 const char OmniboxFieldTrial::kHUPNewScoringVisitedCountScoreBucketsParam[] =
413 "VisitedCountScoreBuckets";
415 const char OmniboxFieldTrial::kHQPExperimentalScoringEnabledParam[] =
416 "HQPExperimentalScoringEnabled";
417 const char OmniboxFieldTrial::kHQPExperimentalScoringBucketsParam[] =
418 "HQPExperimentalScoringBuckets";
419 const char
420 OmniboxFieldTrial::kHQPExperimentalScoringTopicalityThresholdParam[] =
421 "HQPExperimentalScoringTopicalityThreshold";
423 // static
424 int OmniboxFieldTrial::kDefaultMinimumTimeBetweenSuggestQueriesMs = 100;
426 // Background and implementation details:
428 // Each experiment group in any field trial can come with an optional set of
429 // parameters (key-value pairs). In the bundled omnibox experiment
430 // (kBundledExperimentFieldTrialName), each experiment group comes with a
431 // list of parameters in the form:
432 // key=<Rule>:
433 // <OmniboxEventProto::PageClassification (as an int)>:
434 // <whether Instant Extended is enabled (as a 1 or 0)>
435 // (note that there are no linebreaks in keys; this format is for
436 // presentation only>
437 // value=<arbitrary string>
438 // Both the OmniboxEventProto::PageClassification and the Instant Extended
439 // entries can be "*", which means this rule applies for all values of the
440 // matching portion of the context.
441 // One example parameter is
442 // key=SearchHistory:6:1
443 // value=PreventInlining
444 // This means in page classification context 6 (a search result page doing
445 // search term replacement) with Instant Extended enabled, the SearchHistory
446 // experiment should PreventInlining.
448 // When an exact match to the rule in the current context is missing, we
449 // give preference to a wildcard rule that matches the instant extended
450 // context over a wildcard rule that matches the page classification
451 // context. Hopefully, though, users will write their field trial configs
452 // so as not to rely on this fall back order.
454 // In short, this function tries to find the value associated with key
455 // |rule|:|page_classification|:|instant_extended|, failing that it looks up
456 // |rule|:*:|instant_extended|, failing that it looks up
457 // |rule|:|page_classification|:*, failing that it looks up |rule|:*:*,
458 // and failing that it returns the empty string.
459 std::string OmniboxFieldTrial::GetValueForRuleInContext(
460 const std::string& rule,
461 OmniboxEventProto::PageClassification page_classification) {
462 VariationParams params;
463 if (!variations::GetVariationParams(kBundledExperimentFieldTrialName,
464 &params)) {
465 return std::string();
467 const std::string page_classification_str =
468 base::IntToString(static_cast<int>(page_classification));
469 const std::string instant_extended =
470 chrome::IsInstantExtendedAPIEnabled() ? "1" : "0";
471 // Look up rule in this exact context.
472 VariationParams::const_iterator it = params.find(
473 rule + ":" + page_classification_str + ":" + instant_extended);
474 if (it != params.end())
475 return it->second;
476 // Fall back to the global page classification context.
477 it = params.find(rule + ":*:" + instant_extended);
478 if (it != params.end())
479 return it->second;
480 // Fall back to the global instant extended context.
481 it = params.find(rule + ":" + page_classification_str + ":*");
482 if (it != params.end())
483 return it->second;
484 // Look up rule in the global context.
485 it = params.find(rule + ":*:*");
486 return (it != params.end()) ? it->second : std::string();