File: omnibox_field_trial.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1142 lines) | stat: -rw-r--r-- 44,537 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/omnibox/browser/omnibox_field_trial.h"

#include <algorithm>
#include <cmath>
#include <functional>
#include <string>

#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/system/sys_info.h"
#include "base/time/time.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "build/build_config.h"
#include "components/history/core/browser/url_database.h"
#include "components/omnibox/browser/autocomplete_provider.h"
#include "components/omnibox/browser/page_classification_functions.h"
#include "components/omnibox/browser/url_index_private_data.h"
#include "components/omnibox/common/omnibox_features.h"
#include "components/optimization_guide/machine_learning_tflite_buildflags.h"
#include "components/search/search.h"
#include "components/variations/active_field_trials.h"
#include "components/variations/hashing.h"
#include "components/variations/variations_associated_data.h"
#include "third_party/metrics_proto/omnibox_event.pb.h"
#include "ui/base/ui_base_features.h"

using metrics::OmniboxEventProto;

namespace {

typedef std::map<std::string, std::string> VariationParams;
typedef HUPScoringParams::ScoreBuckets ScoreBuckets;

void InitializeBucketsFromString(const std::string& bucket_string,
                                 ScoreBuckets* score_buckets) {
  // Clear the buckets.
  score_buckets->buckets().clear();
  base::StringPairs kv_pairs;
  if (base::SplitStringIntoKeyValuePairs(bucket_string, ':', ',', &kv_pairs)) {
    for (base::StringPairs::const_iterator it = kv_pairs.begin();
         it != kv_pairs.end(); ++it) {
      ScoreBuckets::CountMaxRelevance bucket;
      base::StringToDouble(it->first, &bucket.first);
      base::StringToInt(it->second, &bucket.second);
      score_buckets->buckets().push_back(bucket);
    }
    std::sort(score_buckets->buckets().begin(), score_buckets->buckets().end(),
              std::greater<ScoreBuckets::CountMaxRelevance>());
  }
}

void InitializeScoreBuckets(const VariationParams& params,
                            const char* relevance_cap_param,
                            const char* half_life_param,
                            const char* score_buckets_param,
                            const char* use_decay_factor_param,
                            ScoreBuckets* score_buckets) {
  auto it = params.find(relevance_cap_param);
  if (it != params.end()) {
    int relevance_cap;
    if (base::StringToInt(it->second, &relevance_cap)) {
      score_buckets->set_relevance_cap(relevance_cap);
    }
  }

  it = params.find(use_decay_factor_param);
  if (it != params.end()) {
    int use_decay_factor;
    if (base::StringToInt(it->second, &use_decay_factor)) {
      score_buckets->set_use_decay_factor(use_decay_factor != 0);
    }
  }

  it = params.find(half_life_param);
  if (it != params.end()) {
    int half_life_days;
    if (base::StringToInt(it->second, &half_life_days)) {
      score_buckets->set_half_life_days(half_life_days);
    }
  }

  it = params.find(score_buckets_param);
  if (it != params.end()) {
    // The value of the score bucket is a comma-separated list of
    // {DecayedCount/DecayedFactor + ":" + MaxRelevance}.
    InitializeBucketsFromString(it->second, score_buckets);
  }
}

// Background and implementation details:
//
// Each experiment group in any field trial can come with an optional set of
// parameters (key-value pairs).  In the bundled omnibox experiment
// (kBundledExperimentFieldTrialName), each experiment group comes with a
// list of parameters in the form:
//   key=<Rule>:
//       <OmniboxEventProto::PageClassification (as an int)>:
//       <whether Instant Extended is enabled (as a 1 or 0)>
//     (note that there are no linebreaks in keys; this format is for
//      presentation only>
//   value=<arbitrary string>
// Both the OmniboxEventProto::PageClassification and the Instant Extended
// entries can be "*", which means this rule applies for all values of the
// matching portion of the context.
// One example parameter is
//   key=SearchHistory:6:1
//   value=PreventInlining
// This means in page classification context 6 (a search result page doing
// search term replacement) with Instant Extended enabled, the SearchHistory
// experiment should PreventInlining.
//
// When an exact match to the rule in the current context is missing, we
// give preference to a wildcard rule that matches the instant extended
// context over a wildcard rule that matches the page classification
// context.  Hopefully, though, users will write their field trial configs
// so as not to rely on this fall back order.
//
// In short, this function tries to find the value associated with key
// |rule|:|page_classification|:|instant_extended|, failing that it looks up
// |rule|:*:|instant_extended|, failing that it looks up
// |rule|:|page_classification|:*, failing that it looks up |rule|:*:*,
// and failing that it returns the empty string.
std::string GetValueForRuleInContextFromVariationParams(
    const std::map<std::string, std::string>& params,
    const std::string& rule,
    OmniboxEventProto::PageClassification page_classification) {
  if (params.empty()) {
    return std::string();
  }

  const std::string page_classification_str =
      base::NumberToString(static_cast<int>(page_classification));
  const std::string instant_extended =
      search::IsInstantExtendedAPIEnabled() ? "1" : "0";
  // Look up rule in this exact context.
  VariationParams::const_iterator it = params.find(
      rule + ":" + page_classification_str + ":" + instant_extended);
  if (it != params.end()) {
    return it->second;
  }
  // Fall back to the global page classification context.
  it = params.find(rule + ":*:" + instant_extended);
  if (it != params.end()) {
    return it->second;
  }
  // Fall back to the global instant extended context.
  it = params.find(rule + ":" + page_classification_str + ":*");
  if (it != params.end()) {
    return it->second;
  }
  // Look up rule in the global context.
  it = params.find(rule + ":*:*");
  return (it != params.end()) ? it->second : std::string();
}

OmniboxFieldTrial::MLConfig& GetMLConfigInternal() {
  static base::NoDestructor<OmniboxFieldTrial::MLConfig> s_config;
  return *s_config;
}

bool IsKoreanLocale(const std::string& locale) {
  return locale == "ko" || locale == "ko-KR";
}

#if !BUILDFLAG(IS_IOS)
bool IsEnglishLocale(const std::string& locale) {
  return base::StartsWith(locale, "en", base::CompareCase::SENSITIVE);
}
#endif  // !BUILDFLAG(IS_IOS)

}  // namespace

HUPScoringParams::ScoreBuckets::ScoreBuckets()
    : relevance_cap_(-1), half_life_days_(-1), use_decay_factor_(false) {}

HUPScoringParams::ScoreBuckets::ScoreBuckets(const ScoreBuckets& other) =
    default;

HUPScoringParams::ScoreBuckets::~ScoreBuckets() = default;

size_t HUPScoringParams::ScoreBuckets::EstimateMemoryUsage() const {
  return base::trace_event::EstimateMemoryUsage(buckets_);
}

double HUPScoringParams::ScoreBuckets::HalfLifeTimeDecay(
    const base::TimeDelta& elapsed_time) const {
  double time_ms;
  if ((half_life_days_ <= 0) ||
      ((time_ms = elapsed_time.InMillisecondsF()) <= 0)) {
    return 1.0;
  }

  const double half_life_intervals =
      time_ms / base::Days(half_life_days_).InMillisecondsF();
  return pow(2.0, -half_life_intervals);
}

size_t HUPScoringParams::EstimateMemoryUsage() const {
  size_t res = 0;

  res += base::trace_event::EstimateMemoryUsage(typed_count_buckets);
  res += base::trace_event::EstimateMemoryUsage(visited_count_buckets);

  return res;
}

int OmniboxFieldTrial::GetDisabledProviderTypes() {
  const std::string& types_string = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName, kDisableProvidersRule);
  int types = 0;
  if (types_string.empty() || !base::StringToInt(types_string, &types)) {
    return 0;
  }
  return types;
}

void OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(
    std::vector<uint32_t>* field_trial_hashes) {
  field_trial_hashes->clear();
  if (base::FieldTrialList::TrialExists(kBundledExperimentFieldTrialName)) {
    field_trial_hashes->push_back(
        variations::HashName(kBundledExperimentFieldTrialName));
  }
}

void OmniboxFieldTrial::GetDemotionsByType(
    OmniboxEventProto::PageClassification current_page_classification,
    DemotionMultipliers* demotions_by_type) {
  demotions_by_type->clear();

  // Explicitly check whether the feature is enabled before calling
  // |GetValueForRuleInContextByFeature| because it is possible for
  // |GetValueForRuleInContextByFeature| to return an empty string even if the
  // feature is enabled, and we don't want to fallback to
  // |GetValueForRuleInContext| in this case.
  std::string demotion_rule =
      base::FeatureList::IsEnabled(omnibox::kOmniboxDemoteByType)
          ? OmniboxFieldTrial::internal::GetValueForRuleInContextByFeature(
                omnibox::kOmniboxDemoteByType, kDemoteByTypeRule,
                current_page_classification)
          : OmniboxFieldTrial::internal::GetValueForRuleInContext(
                kDemoteByTypeRule, current_page_classification);
  // If there is no demotion rule for this context, then use the default
  // value for that context.
  if (demotion_rule.empty()) {
    // This rule demotes URLs as strongly as possible without violating user
    // expectations.  In particular, for URL-seeking inputs, if the user would
    // likely expect a URL first (i.e., it would be inline autocompleted), then
    // that URL will still score strongly enough to be first.  This is done
    // using a demotion multipler of 0.61.  If a URL would get a score high
    // enough to be inline autocompleted (1400+), even after demotion it will
    // score above 850 ( 1400 * 0.61 > 850).  850 is the maximum score for
    // queries when the input has been detected as URL-seeking.
#if BUILDFLAG(IS_ANDROID)
    if (current_page_classification ==
        OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT) {
      demotion_rule = "1:61,2:61,3:61,4:61,16:61,24:61";
    }
#endif
    omnibox::CheckObsoletePageClass(current_page_classification);

    if (current_page_classification == OmniboxEventProto::NTP_REALBOX) {
      demotion_rule = "1:10,2:10,3:10,4:10,5:10,16:10,17:10,24:10,33:0";
    }
  }

  // The value of the DemoteByType rule is a comma-separated list of
  // {ResultType + ":" + Number} where ResultType is an AutocompleteMatchType::
  // Type enum represented as an integer and Number is an integer number
  // between 0 and 100 inclusive.   Relevance scores of matches of that result
  // type are multiplied by Number / 100.  100 means no change.
  base::StringPairs kv_pairs;
  if (base::SplitStringIntoKeyValuePairs(demotion_rule, ':', ',', &kv_pairs)) {
    for (base::StringPairs::const_iterator it = kv_pairs.begin();
         it != kv_pairs.end(); ++it) {
      // This is a best-effort conversion; we trust the hand-crafted parameters
      // downloaded from the server to be perfect.  There's no need to handle
      // errors smartly.
      int k, v;
      base::StringToInt(it->first, &k);
      base::StringToInt(it->second, &v);
      (*demotions_by_type)[static_cast<AutocompleteMatchType::Type>(k)] =
          static_cast<float>(v) / 100.0f;
    }
  }
}

size_t OmniboxFieldTrial::GetProviderMaxMatches(
    AutocompleteProvider::Type provider) {
  size_t default_max_matches_per_provider = 3;

  std::string param_value;
  if (OmniboxFieldTrial::IsMlUrlScoringEnabled()) {
    param_value =
        OmniboxFieldTrial::GetMLConfig().ml_url_scoring_max_matches_by_provider;
  } else {
    param_value = base::GetFieldTrialParamValueByFeature(
        omnibox::kUIExperimentMaxAutocompleteMatches,
        OmniboxFieldTrial::kUIMaxAutocompleteMatchesByProviderParam);
  }

  // If the experiment param specifies a max results for |provider|, return the
  // specified limit.
  // E.g., if param_value = '3:2' and provider = 3, return 2.
  // Otherwise, if the experiment param specifies a default value for
  // unspecified providers, return the default value.
  // E.g., if param_value = '3:3,*:4' and provider = 1, return 4,
  // Otherwise, return |default_max_matches_per_provider|.
  base::StringPairs kv_pairs;
  if (base::SplitStringIntoKeyValuePairs(param_value, ':', ',', &kv_pairs)) {
    for (const auto& kv_pair : kv_pairs) {
      int k;
      base::StringToInt(kv_pair.first, &k);
      size_t v;
      base::StringToSizeT(kv_pair.second, &v);

      if (kv_pair.first == "*") {
        default_max_matches_per_provider = v;
      } else if (k == provider) {
        return v;
      }
    }
  }

  return default_max_matches_per_provider;
}

bool OmniboxFieldTrial::IsMaxURLMatchesFeatureEnabled() {
  return base::FeatureList::IsEnabled(omnibox::kOmniboxMaxURLMatches);
}

size_t OmniboxFieldTrial::GetMaxURLMatches() {
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
  constexpr size_t kDefaultMaxURLMatches = 5;
#else
  constexpr size_t kDefaultMaxURLMatches = 7;
#endif
  return base::GetFieldTrialParamByFeatureAsInt(
      omnibox::kOmniboxMaxURLMatches,
      OmniboxFieldTrial::kOmniboxMaxURLMatchesParam, kDefaultMaxURLMatches);
}

void OmniboxFieldTrial::GetDefaultHUPScoringParams(
    HUPScoringParams* scoring_params) {
  ScoreBuckets* type_score_buckets = &scoring_params->typed_count_buckets;
  type_score_buckets->set_half_life_days(30);
  type_score_buckets->set_use_decay_factor(false);
  // Default typed count buckets based on decayed typed count. The
  // values here are based on the results of field trials to determine what
  // maximized overall result quality.
  const std::string& typed_count_score_buckets_str =
      "1.0:1413,0.97:1390,0.93:1360,0.85:1340,0.72:1320,0.50:1250,0.0:1203";
  InitializeBucketsFromString(typed_count_score_buckets_str,
                              type_score_buckets);

  ScoreBuckets* visit_score_buckets = &scoring_params->visited_count_buckets;
  visit_score_buckets->set_half_life_days(30);
  visit_score_buckets->set_use_decay_factor(false);
  // Buckets based on visit count.  Like the typed count buckets above, the
  // values here were chosen based on field trials.  Note that when a URL hasn't
  // been visited in the last 30 days, we clamp its score to 100, which
  // basically demotes it below any other results in the dropdown.
  const std::string& visit_count_score_buckets_str = "4.0:790,0.5:590,0.0:100";
  InitializeBucketsFromString(visit_count_score_buckets_str,
                              visit_score_buckets);
}

void OmniboxFieldTrial::GetExperimentalHUPScoringParams(
    HUPScoringParams* scoring_params) {
  VariationParams params;
  if (!base::GetFieldTrialParams(kBundledExperimentFieldTrialName, &params)) {
    return;
  }

  InitializeScoreBuckets(params, kHUPNewScoringTypedCountRelevanceCapParam,
                         kHUPNewScoringTypedCountHalfLifeTimeParam,
                         kHUPNewScoringTypedCountScoreBucketsParam,
                         kHUPNewScoringTypedCountUseDecayFactorParam,
                         &scoring_params->typed_count_buckets);
  InitializeScoreBuckets(params, kHUPNewScoringVisitedCountRelevanceCapParam,
                         kHUPNewScoringVisitedCountHalfLifeTimeParam,
                         kHUPNewScoringVisitedCountScoreBucketsParam,
                         kHUPNewScoringVisitedCountUseDecayFactorParam,
                         &scoring_params->visited_count_buckets);
}

float OmniboxFieldTrial::HQPBookmarkValue() {
  std::string bookmark_value_str = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName, kHQPBookmarkValueRule);
  if (bookmark_value_str.empty()) {
    return 10;
  }
  // This is a best-effort conversion; we trust the hand-crafted parameters
  // downloaded from the server to be perfect.  There's no need for handle
  // errors smartly.
  double bookmark_value;
  base::StringToDouble(bookmark_value_str, &bookmark_value);
  return bookmark_value;
}

bool OmniboxFieldTrial::HQPAllowMatchInTLDValue() {
  return base::GetFieldTrialParamValue(kBundledExperimentFieldTrialName,
                                       kHQPAllowMatchInTLDRule) == "true";
}

bool OmniboxFieldTrial::HQPAllowMatchInSchemeValue() {
  return base::GetFieldTrialParamValue(kBundledExperimentFieldTrialName,
                                       kHQPAllowMatchInSchemeRule) == "true";
}

void OmniboxFieldTrial::GetSuggestPollingStrategy(bool* from_last_keystroke,
                                                  int* polling_delay_ms) {
  *from_last_keystroke =
      base::GetFieldTrialParamValue(
          kBundledExperimentFieldTrialName,
          kMeasureSuggestPollingDelayFromLastKeystrokeRule) == "true";

  const std::string& polling_delay_string = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName, kSuggestPollingDelayMsRule);
  if (polling_delay_string.empty() ||
      !base::StringToInt(polling_delay_string, polling_delay_ms) ||
      (*polling_delay_ms <= 0)) {
    *polling_delay_ms = kDefaultMinimumTimeBetweenSuggestQueriesMs;
  }
}

std::string OmniboxFieldTrial::HQPExperimentalScoringBuckets() {
  return base::GetFieldTrialParamValue(kBundledExperimentFieldTrialName,
                                       kHQPExperimentalScoringBucketsParam);
}

float OmniboxFieldTrial::HQPExperimentalTopicalityThreshold() {
  std::string topicality_threshold_str = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName,
      kHQPExperimentalScoringTopicalityThresholdParam);

  double topicality_threshold;
  if (topicality_threshold_str.empty() ||
      !base::StringToDouble(topicality_threshold_str, &topicality_threshold)) {
    return 0.5f;
  }

  return static_cast<float>(topicality_threshold);
}

int OmniboxFieldTrial::MaxNumHQPUrlsIndexedAtStartup() {
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
  // Limits on Android and iOS are chosen based on experiment results. See
  // crbug.com/715852#c18 and crbug.com/1141539#c31.
  constexpr int kDefaultOnLowEndDevices = 100;
  constexpr int kDefaultOnNonLowEndDevices = 400;
#else
  // Use 20,000 entries as a safety cap for users with spammed history,
  // such as users who were stuck in a redirect loop with autogenerated URLs.
  // This limit will only affect 0.01% of Windows users. crbug.com/750845.
  constexpr int kDefaultOnLowEndDevices = 20000;
  constexpr int kDefaultOnNonLowEndDevices = 20000;
#endif

  if (base::SysInfo::IsLowEndDeviceOrPartialLowEndModeEnabled()) {
    return kDefaultOnLowEndDevices;
  } else {
    return kDefaultOnNonLowEndDevices;
  }
}

size_t OmniboxFieldTrial::HQPMaxVisitsToScore() {
  std::string max_visits_str = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName, kHQPMaxVisitsToScoreRule);
  constexpr size_t kDefaultMaxVisitsToScore = 10;
  static_assert(
      URLIndexPrivateData::kMaxVisitsToStoreInCache >= kDefaultMaxVisitsToScore,
      "HQP should store at least as many visits as it expects to score");
  if (max_visits_str.empty()) {
    return kDefaultMaxVisitsToScore;
  }
  // This is a best-effort conversion; we trust the hand-crafted parameters
  // downloaded from the server to be perfect.  There's no need for handle
  // errors smartly.
  size_t max_visits_value;
  base::StringToSizeT(max_visits_str, &max_visits_value);
  return max_visits_value;
}

float OmniboxFieldTrial::HQPTypedValue() {
  std::string typed_value_str = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName, kHQPTypedValueRule);
  if (typed_value_str.empty()) {
    return 1.5;
  }
  // This is a best-effort conversion; we trust the hand-crafted parameters
  // downloaded from the server to be perfect.  There's no need for handle
  // errors smartly.
  double typed_value;
  base::StringToDouble(typed_value_str, &typed_value);
  return typed_value;
}

OmniboxFieldTrial::NumMatchesScores OmniboxFieldTrial::HQPNumMatchesScores() {
  std::string str = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName, kHQPNumMatchesScoresRule);
  static constexpr char kDefaultNumMatchesScores[] = "1:3,2:2.5,3:2,4:1.5";
  if (str.empty()) {
    str = kDefaultNumMatchesScores;
  }
  // The parameter is a comma-separated list of (number, value) pairs such as
  // listed above.
  // This is a best-effort conversion; we trust the hand-crafted parameters
  // downloaded from the server to be perfect.  There's no need to handle
  // errors smartly.
  base::StringPairs kv_pairs;
  if (!base::SplitStringIntoKeyValuePairs(str, ':', ',', &kv_pairs)) {
    return NumMatchesScores{};
  }
  NumMatchesScores num_matches_scores(kv_pairs.size());
  for (size_t i = 0; i < kv_pairs.size(); ++i) {
    base::StringToSizeT(kv_pairs[i].first, &num_matches_scores[i].first);
    // The input must be sorted by number of matches.
    DCHECK((i == 0) ||
           (num_matches_scores[i].first > num_matches_scores[i - 1].first));
    base::StringToDouble(kv_pairs[i].second, &num_matches_scores[i].second);
  }
  return num_matches_scores;
}

size_t OmniboxFieldTrial::HQPNumTitleWordsToAllow() {
  // The value of the rule is a string that encodes an integer (actually
  // size_t) containing the number of words.
  size_t num_title_words;
  if (!base::StringToSizeT(
          base::GetFieldTrialParamValue(kBundledExperimentFieldTrialName,
                                        kHQPNumTitleWordsRule),
          &num_title_words)) {
    return 20;
  }
  return num_title_words;
}

bool OmniboxFieldTrial::HQPAlsoDoHUPLikeScoring() {
  return base::GetFieldTrialParamValue(kBundledExperimentFieldTrialName,
                                       kHQPAlsoDoHUPLikeScoringRule) == "true";
}

bool OmniboxFieldTrial::HUPSearchDatabase() {
  const std::string& value = base::GetFieldTrialParamValue(
      kBundledExperimentFieldTrialName, kHUPSearchDatabaseRule);
  return value.empty() || (value == "true");
}

bool OmniboxFieldTrial::IsOnDeviceHeadSuggestEnabledForIncognito() {
  return base::FeatureList::IsEnabled(omnibox::kOnDeviceHeadProviderIncognito);
}

bool OmniboxFieldTrial::IsOnDeviceHeadSuggestEnabledForNonIncognito() {
  return base::FeatureList::IsEnabled(
      omnibox::kOnDeviceHeadProviderNonIncognito);
}

bool OmniboxFieldTrial::IsOnDeviceHeadSuggestEnabledForAnyMode() {
  return IsOnDeviceHeadSuggestEnabledForIncognito() ||
         IsOnDeviceHeadSuggestEnabledForNonIncognito();
}

bool OmniboxFieldTrial::IsOnDeviceTailSuggestEnabled(
    const std::string& locale) {
  // Tail model will only be enabled when head provider is also enabled.
  if (!IsOnDeviceHeadSuggestEnabledForAnyMode()) {
    return false;
  }

  // Currently only launch for English locales. Remove this flag once i18n is
  // also launched.
  // Do not launch for iOS since the feature is not supported in iOS yet.
#if !BUILDFLAG(IS_IOS)
  if (IsEnglishLocale(locale)) {
    return base::FeatureList::IsEnabled(
        omnibox::kOnDeviceTailEnableEnglishModel);
  }
#endif  // !BUILDFLAG(IS_IOS)

  return base::FeatureList::IsEnabled(omnibox::kOnDeviceTailModel);
}

bool OmniboxFieldTrial::ShouldEncodeLeadingSpaceForOnDeviceTailSuggest() {
  return base::GetFieldTrialParamByFeatureAsBool(omnibox::kOnDeviceTailModel,
                                                 "ShouldEncodeLeadingSpace",
                                                 /*default_value=*/false);
}

bool OmniboxFieldTrial::ShouldApplyOnDeviceHeadModelSelectionFix() {
  return base::GetFieldTrialParamByFeatureAsBool(
             omnibox::kOnDeviceHeadProviderNonIncognito,
             OmniboxFieldTrial::kOnDeviceHeadModelSelectionFix,
             /*default_value=*/true) ||
         base::GetFieldTrialParamByFeatureAsBool(
             omnibox::kOnDeviceHeadProviderIncognito,
             OmniboxFieldTrial::kOnDeviceHeadModelSelectionFix,
             /*default_value=*/true);
}

bool OmniboxFieldTrial::IsOnDeviceHeadSuggestEnabledForLocale(
    const std::string& locale) {
  if (IsKoreanLocale(locale) &&
      !base::FeatureList::IsEnabled(omnibox::kOnDeviceHeadProviderKorean)) {
    return false;
  }
  return IsOnDeviceHeadSuggestEnabledForAnyMode();
}

std::string OmniboxFieldTrial::OnDeviceHeadModelLocaleConstraint(
    bool is_incognito) {
  const base::Feature* feature =
      is_incognito ? &omnibox::kOnDeviceHeadProviderIncognito
                   : &omnibox::kOnDeviceHeadProviderNonIncognito;
  std::string constraint = base::GetFieldTrialParamValueByFeature(
      *feature, kOnDeviceHeadModelLocaleConstraint);
  if (constraint.empty()) {
    constraint = "500000";
  }
  return constraint;
}

const char OmniboxFieldTrial::kBundledExperimentFieldTrialName[] =
    "OmniboxBundledExperimentV1";
const char OmniboxFieldTrial::kDisableProvidersRule[] = "DisableProviders";
const char OmniboxFieldTrial::kDemoteByTypeRule[] = "DemoteByType";
const char OmniboxFieldTrial::kHQPBookmarkValueRule[] = "HQPBookmarkValue";
const char OmniboxFieldTrial::kHQPTypedValueRule[] = "HQPTypedValue";
const char OmniboxFieldTrial::kHQPAllowMatchInTLDRule[] = "HQPAllowMatchInTLD";
const char OmniboxFieldTrial::kHQPAllowMatchInSchemeRule[] =
    "HQPAllowMatchInScheme";
const char
    OmniboxFieldTrial::kMeasureSuggestPollingDelayFromLastKeystrokeRule[] =
        "MeasureSuggestPollingDelayFromLastKeystroke";
const char OmniboxFieldTrial::kSuggestPollingDelayMsRule[] =
    "SuggestPollingDelayMs";
const char OmniboxFieldTrial::kHQPMaxVisitsToScoreRule[] =
    "HQPMaxVisitsToScoreRule";
const char OmniboxFieldTrial::kHQPNumMatchesScoresRule[] =
    "HQPNumMatchesScores";
const char OmniboxFieldTrial::kHQPNumTitleWordsRule[] = "HQPNumTitleWords";
const char OmniboxFieldTrial::kHQPAlsoDoHUPLikeScoringRule[] =
    "HQPAlsoDoHUPLikeScoring";
const char OmniboxFieldTrial::kHUPSearchDatabaseRule[] = "HUPSearchDatabase";
const char OmniboxFieldTrial::kHUPNewScoringTypedCountRelevanceCapParam[] =
    "TypedCountRelevanceCap";
const char OmniboxFieldTrial::kHUPNewScoringTypedCountHalfLifeTimeParam[] =
    "TypedCountHalfLifeTime";
const char OmniboxFieldTrial::kHUPNewScoringTypedCountScoreBucketsParam[] =
    "TypedCountScoreBuckets";
const char OmniboxFieldTrial::kHUPNewScoringTypedCountUseDecayFactorParam[] =
    "TypedCountUseDecayFactor";
const char OmniboxFieldTrial::kHUPNewScoringVisitedCountRelevanceCapParam[] =
    "VisitedCountRelevanceCap";
const char OmniboxFieldTrial::kHUPNewScoringVisitedCountHalfLifeTimeParam[] =
    "VisitedCountHalfLifeTime";
const char OmniboxFieldTrial::kHUPNewScoringVisitedCountScoreBucketsParam[] =
    "VisitedCountScoreBuckets";
const char OmniboxFieldTrial::kHUPNewScoringVisitedCountUseDecayFactorParam[] =
    "VisitedCountUseDecayFactor";

const char OmniboxFieldTrial::kHQPExperimentalScoringBucketsParam[] =
    "HQPExperimentalScoringBuckets";
const char
    OmniboxFieldTrial::kHQPExperimentalScoringTopicalityThresholdParam[] =
        "HQPExperimentalScoringTopicalityThreshold";

const char
    OmniboxFieldTrial::kMaxNumHQPUrlsIndexedAtStartupOnLowEndDevicesParam[] =
        "MaxNumHQPUrlsIndexedAtStartupOnLowEndDevices";
const char
    OmniboxFieldTrial::kMaxNumHQPUrlsIndexedAtStartupOnNonLowEndDevicesParam[] =
        "MaxNumHQPUrlsIndexedAtStartupOnNonLowEndDevices";

const char OmniboxFieldTrial::kMaxZeroSuggestMatchesParam[] =
    "MaxZeroSuggestMatches";
const char OmniboxFieldTrial::kOmniboxMaxURLMatchesParam[] =
    "OmniboxMaxURLMatches";
const char OmniboxFieldTrial::kUIMaxAutocompleteMatchesByProviderParam[] =
    "UIMaxAutocompleteMatchesByProvider";
const char OmniboxFieldTrial::kUIMaxAutocompleteMatchesParam[] =
    "UIMaxAutocompleteMatches";
const char OmniboxFieldTrial::kDynamicMaxAutocompleteUrlCutoffParam[] =
    "OmniboxDynamicMaxAutocompleteUrlCutoff";
const char OmniboxFieldTrial::kDynamicMaxAutocompleteIncreasedLimitParam[] =
    "OmniboxDynamicMaxAutocompleteIncreasedLimit";
const char OmniboxFieldTrial::kSuppressPsuggestBackfillWithMIAParam[] =
    "SuppressPsuggestBackfillWithMIA";

const char OmniboxFieldTrial::kOnDeviceHeadModelLocaleConstraint[] =
    "ForceModelLocaleConstraint";
const char OmniboxFieldTrial::kOnDeviceHeadModelSelectionFix[] = "SelectionFix";

int OmniboxFieldTrial::kDefaultMinimumTimeBetweenSuggestQueriesMs = 100;

namespace OmniboxFieldTrial {

// Local history zero-prefix (aka zero-suggest) and prefix suggestions:

// Whether to ignore all ZPS prefetch responses received from the Suggest
// service when the user is on a Google SRP. This can be used, for example,
// during experimentation to measure the performance impact of only the
// request/response portion of ZPS prefetching (i.e. without updating the
// user-visible list of suggestions in the Omnibox).
const base::FeatureParam<bool> kZeroSuggestPrefetchingOnSRPCounterfactual(
    &omnibox::kZeroSuggestPrefetchingOnSRP,
    "ZeroSuggestPrefetchingOnSRPCounterfactual",
    false);

// The debouncing delay (in milliseconds) to use when throttling ZPS prefetch
// requests.
const base::FeatureParam<int> kZeroSuggestPrefetchDebounceDelay(
    &omnibox::kZeroSuggestPrefetchDebouncing,
    "ZeroSuggestPrefetchDebounceDelay",
    300);

// Whether to calculate debouncing delay relative to the latest successful run
// (instead of the latest run request).
const base::FeatureParam<bool> kZeroSuggestPrefetchDebounceFromLastRun(
    &omnibox::kZeroSuggestPrefetchDebouncing,
    "ZeroSuggestPrefetchDebounceFromLastRun",
    true);

// The maximum number of entries stored by the in-memory zero-suggest cache at
// at any given time (LRU eviction policy is used to enforce this limit).
const base::FeatureParam<int> kZeroSuggestCacheMaxSize(
    &omnibox::kZeroSuggestInMemoryCaching,
    "ZeroSuggestCacheMaxSize",
    5);

bool IsZeroSuggestPrefetchingEnabled() {
  return base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetching) ||
         base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetchingOnSRP) ||
         base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetchingOnWeb);
}

bool IsZeroSuggestPrefetchingEnabledInContext(
    metrics::OmniboxEventProto::PageClassification page_classification) {
  switch (page_classification) {
    case metrics::OmniboxEventProto::NTP_ZPS_PREFETCH:
      return base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetching);
    case metrics::OmniboxEventProto::SRP_ZPS_PREFETCH:
      return base::FeatureList::IsEnabled(
          omnibox::kZeroSuggestPrefetchingOnSRP);
    case metrics::OmniboxEventProto::OTHER_ZPS_PREFETCH:
      return base::FeatureList::IsEnabled(
          omnibox::kZeroSuggestPrefetchingOnWeb);
    default:
      return false;
  }
}

bool IsOnFocusZeroSuggestEnabledInContext(
    metrics::OmniboxEventProto::PageClassification page_classification) {
  static bool enabled =
      base::FeatureList::IsEnabled(omnibox::kFocusTriggersWebAndSRPZeroSuggest);

  switch (page_classification) {
    case metrics::OmniboxEventProto::
        SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT:
    case metrics::OmniboxEventProto::OTHER:
      return enabled;
    default:
      return false;
  }
}

bool IsHideSuggestionGroupHeadersEnabledInContext(
    metrics::OmniboxEventProto::PageClassification page_classification) {
  static bool enabled =
      base::FeatureList::IsEnabled(omnibox::kHideSuggestionGroupHeaders);

  switch (page_classification) {
    case metrics::OmniboxEventProto::
        SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT:
    case metrics::OmniboxEventProto::OTHER:
      return enabled;
    default:
      return false;
  }
}

// Rich autocompletion.

bool IsRichAutocompletionEnabled() {
  return base::FeatureList::IsEnabled(omnibox::kRichAutocompletion);
}

const base::FeatureParam<size_t> kRichAutocompletionAutocompleteTitlesMinChar(
    &omnibox::kRichAutocompletion,
    "RichAutocompletionAutocompleteTitlesMinChar",
    3);

const base::FeatureParam<size_t>
    kRichAutocompletionAutocompleteShortcutTextMinChar(
        &omnibox::kRichAutocompletion,
        "RichAutocompletionAutocompleteShortcutTextMinChar",
        3);

const base::FeatureParam<bool> kDomainSuggestionsCounterfactual(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsCounterfactual",
    false);

const base::FeatureParam<int> kDomainSuggestionsTypedUrlsThreshold(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsTypedUrlsThreshold",
    7);

const base::FeatureParam<int> kDomainSuggestionsTypedUrlsOffset(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsTypedUrlsOffset",
    1);

const base::FeatureParam<int> kDomainSuggestionsTypedVisitThreshold(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsTypedVisitThreshold",
    4);

const base::FeatureParam<int> kDomainSuggestionsTypedVisitOffset(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsTypedVisitOffset",
    1);

const base::FeatureParam<int> kDomainSuggestionsTypedVisitCapPerVisit(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsTypedVisitCapPerVisit",
    2);

const base::FeatureParam<int> kDomainSuggestionsMinInputLength(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsMinInputLength",
    4);

const base::FeatureParam<int> kDomainSuggestionsMaxMatchesPerDomain(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsMaxMatchesPerDomain",
    2);

const base::FeatureParam<double> kDomainSuggestionsScoreFactor(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsScoreFactor",
    1);

const base::FeatureParam<bool> kDomainSuggestionsAlternativeScoring(
    &omnibox::kDomainSuggestions,
    "DomainSuggestionsAlternativeScoring",
    false);

// ---------------------------------------------------------
// ML Relevance Scoring ->

// If true, enables scoring signal annotators for logging Omnibox scoring
// signals to OmniboxEventProto.
const base::FeatureParam<bool> kEnableScoringSignalsAnnotatorsForLogging(
    &omnibox::kLogUrlScoringSignals,
    "enable_scoring_signals_annotators",
    false);

// If true, enables scoring signal annotators for ML scoring.
const base::FeatureParam<bool> kEnableScoringSignalsAnnotatorsForMlScoring(
    &omnibox::kMlUrlScoring,
    "enable_scoring_signals_annotators_for_ml_scoring",
    true);

// If true, runs the ML scoring model but does not assign new relevance scores
// to the URL suggestions and does not rerank them.
const base::FeatureParam<bool> kMlUrlScoringCounterfactual(
    &omnibox::kMlUrlScoring,
    "MlUrlScoringCounterfactual",
    false);

// If true, increases the number of candidates the URL autocomplete providers
// pass to the controller beyond `provider_max_matches`.
const base::FeatureParam<bool> kMlUrlScoringUnlimitedNumCandidates(
    &omnibox::kMlUrlScoring,
    "MlUrlScoringUnlimitedNumCandidates",
    false);

const base::FeatureParam<std::string> kMlUrlScoringMaxMatchesByProvider(
    &omnibox::kMlUrlScoring,
    "MlUrlScoringMaxMatchesByProvider",
    "");

MLConfig::MLConfig() {
  log_url_scoring_signals =
      base::FeatureList::IsEnabled(omnibox::kLogUrlScoringSignals);
  enable_history_scoring_signals_annotator_for_searches =
      base::FeatureList::IsEnabled(
          omnibox::kEnableHistoryScoringSignalsAnnotatorForSearches);
  enable_scoring_signals_annotators =
      kEnableScoringSignalsAnnotatorsForLogging.Get() ||
      kEnableScoringSignalsAnnotatorsForMlScoring.Get();
  shortcut_document_signals =
      base::FeatureParam<bool>(&omnibox::kLogUrlScoringSignals,
                               "MlUrlScoringShortcutDocumentSignals", false)
          .Get() ||
      base::FeatureParam<bool>(&omnibox::kMlUrlScoring,
                               "MlUrlScoringShortcutDocumentSignals", true)
          .Get();

  ml_url_scoring = base::FeatureList::IsEnabled(omnibox::kMlUrlScoring);
  ml_url_scoring_counterfactual = kMlUrlScoringCounterfactual.Get();
  ml_url_scoring_unlimited_num_candidates =
      kMlUrlScoringUnlimitedNumCandidates.Get();
  ml_url_scoring_max_matches_by_provider =
      kMlUrlScoringMaxMatchesByProvider.Get();

  // `kMlUrlSearchBlending` parameters.
  mapped_search_blending =
      base::FeatureParam<bool>(&omnibox::kMlUrlSearchBlending,
                               "MlUrlSearchBlending_MappedSearchBlending",
                               mapped_search_blending)
          .Get();
  mapped_search_blending_min =
      base::FeatureParam<int>(&omnibox::kMlUrlSearchBlending,
                              "MlUrlSearchBlending_MappedSearchBlendingMin",
                              mapped_search_blending_min)
          .Get();
  mapped_search_blending_max =
      base::FeatureParam<int>(&omnibox::kMlUrlSearchBlending,
                              "MlUrlSearchBlending_MappedSearchBlendingMax",
                              mapped_search_blending_max)
          .Get();
  mapped_search_blending_grouping_threshold =
      base::FeatureParam<int>(
          &omnibox::kMlUrlSearchBlending,
          "MlUrlSearchBlending_MappedSearchBlendingGroupingThreshold",
          mapped_search_blending_grouping_threshold)
          .Get();

  // `kMlUrlPiecewiseMappedSearchBlending` parameters.
  piecewise_mapped_search_blending =
      base::FeatureParam<bool>(&omnibox::kMlUrlPiecewiseMappedSearchBlending,
                               "MlUrlPiecewiseMappedSearchBlending",
                               piecewise_mapped_search_blending)
          .Get();
  piecewise_mapped_search_blending_grouping_threshold =
      base::FeatureParam<int>(
          &omnibox::kMlUrlPiecewiseMappedSearchBlending,
          "MlUrlPiecewiseMappedSearchBlending_GroupingThreshold",
          piecewise_mapped_search_blending_grouping_threshold)
          .Get();
  piecewise_mapped_search_blending_break_points =
      base::FeatureParam<std::string>(
          &omnibox::kMlUrlPiecewiseMappedSearchBlending,
          "MlUrlPiecewiseMappedSearchBlending_BreakPoints", "")
          .Get();
  piecewise_mapped_search_blending_break_points_verbatim_url =
      base::FeatureParam<std::string>(
          &omnibox::kMlUrlPiecewiseMappedSearchBlending,
          "MlUrlPiecewiseMappedSearchBlending_BreakPoints_VerbatimUrl",
          piecewise_mapped_search_blending_break_points.c_str())
          .Get();
  piecewise_mapped_search_blending_break_points_search =
      base::FeatureParam<std::string>(
          &omnibox::kMlUrlPiecewiseMappedSearchBlending,
          "MlUrlPiecewiseMappedSearchBlending_BreakPoints_Search", "0,0;1,1400")
          .Get();
  piecewise_mapped_search_blending_relevance_bias =
      base::FeatureParam<int>(
          &omnibox::kMlUrlPiecewiseMappedSearchBlending,
          "MlUrlPiecewiseMappedSearchBlending_RelevanceBias",
          piecewise_mapped_search_blending_relevance_bias)
          .Get();

  url_scoring_model = base::FeatureList::IsEnabled(omnibox::kUrlScoringModel);

  ml_url_score_caching =
      base::FeatureList::IsEnabled(omnibox::kMlUrlScoreCaching);
  max_ml_score_cache_size =
      base::FeatureParam<int>(&omnibox::kMlUrlScoreCaching,
                              "MlUrlScoreCaching_MaxMlScoreCacheSize",
                              max_ml_score_cache_size)
          .Get();

  enable_ml_scoring_for_searches =
      base::FeatureParam<bool>(&omnibox::kMlUrlScoring,
                               "MlUrlScoring_EnableMlScoringForSearches", false)
          .Get();
  enable_ml_scoring_for_verbatim_urls =
      base::FeatureParam<bool>(&omnibox::kMlUrlScoring,
                               "MlUrlScoring_EnableMlScoringForVerbatimUrls",
                               false)
          .Get();
}

MLConfig::~MLConfig() = default;

MLConfig::MLConfig(const MLConfig&) = default;

MLConfig& MLConfig::operator=(const MLConfig& other) = default;

ScopedMLConfigForTesting::ScopedMLConfigForTesting()
    : original_config_(std::make_unique<MLConfig>(GetMLConfig())) {
  GetMLConfigInternal() = {};
}

ScopedMLConfigForTesting::~ScopedMLConfigForTesting() {
  GetMLConfigInternal() = *original_config_;
}

MLConfig& ScopedMLConfigForTesting::GetMLConfig() {
  return GetMLConfigInternal();
}

const MLConfig& GetMLConfig() {
  return GetMLConfigInternal();
}

bool IsReportingUrlScoringSignalsEnabled() {
  return GetMLConfig().log_url_scoring_signals;
}

bool IsPopulatingUrlScoringSignalsEnabled() {
  return IsReportingUrlScoringSignalsEnabled() || IsMlUrlScoringEnabled();
}

bool AreScoringSignalsAnnotatorsEnabled() {
  return GetMLConfig().enable_scoring_signals_annotators;
}
bool IsMlUrlScoringEnabled() {
#if BUILDFLAG(BUILD_WITH_TFLITE_LIB)
  return IsUrlScoringModelEnabled() && GetMLConfig().ml_url_scoring;
#else
  return false;
#endif  // BUILDFLAG(BUILD_WITH_TFLITE_LIB)
}
bool IsMlUrlScoringCounterfactual() {
  return IsMlUrlScoringEnabled() && GetMLConfig().ml_url_scoring_counterfactual;
}
bool IsMlUrlScoringUnlimitedNumCandidatesEnabled() {
  return IsMlUrlScoringEnabled() &&
         GetMLConfig().ml_url_scoring_unlimited_num_candidates;
}
bool IsUrlScoringModelEnabled() {
  return GetMLConfig().url_scoring_model;
}
bool IsMlUrlScoreCachingEnabled() {
  return GetMLConfig().ml_url_score_caching;
}

std::vector<std::pair<double, int>> GetPiecewiseMappingBreakPoints(
    PiecewiseMappingVariant mapping_variant) {
  std::vector<std::pair<double, int>> break_points;

  std::string param_value;
  switch (mapping_variant) {
    case PiecewiseMappingVariant::kRegular:
      param_value = OmniboxFieldTrial::GetMLConfig()
                        .piecewise_mapped_search_blending_break_points;
      break;
    case PiecewiseMappingVariant::kVerbatimUrl:
      param_value =
          OmniboxFieldTrial::GetMLConfig()
              .piecewise_mapped_search_blending_break_points_verbatim_url;
      break;
    case PiecewiseMappingVariant::kSearch:
      param_value = OmniboxFieldTrial::GetMLConfig()
                        .piecewise_mapped_search_blending_break_points_search;
      break;
    default:
      NOTREACHED();
  }

  base::StringPairs pairs;
  if (base::SplitStringIntoKeyValuePairs(param_value, ',', ';', &pairs)) {
    for (const auto& p : pairs) {
      double ml_score;
      base::StringToDouble(p.first, &ml_score);
      int relevance;
      base::StringToInt(p.second, &relevance);

      break_points.push_back(std::make_pair(ml_score, relevance));
    }
  }

  return break_points;
}

// <- ML Relevance Scoring
// ---------------------------------------------------------
// Touch Down Trigger For Prefetch ->
const base::FeatureParam<int>
    kTouchDownTriggerForPrefetchMaxPrefetchesPerOmniboxSession(
        &omnibox::kOmniboxTouchDownTriggerForPrefetch,
        "max_prefetches_per_omnibox_session",
        5);
// <- Touch Down Trigger For Prefetch
// ---------------------------------------------------------
// Site Search Starter Pack ->
const base::FeatureParam<std::string> kGeminiUrlOverride(
    &omnibox::kStarterPackExpansion,
    "StarterPackGeminiUrlOverride",
    "https://gemini.google.com/prompt?"
    "utm_source=chrome_omnibox&utm_medium=owned&utm_campaign=gemini_shortcut");

bool IsStarterPackExpansionEnabled() {
  return base::FeatureList::IsEnabled(omnibox::kStarterPackExpansion);
}

bool IsStarterPackIPHEnabled() {
  return base::FeatureList::IsEnabled(omnibox::kStarterPackIPH);
}

// <- Site Search Starter Pack
}  // namespace OmniboxFieldTrial

std::string OmniboxFieldTrial::internal::GetValueForRuleInContext(
    const std::string& rule,
    OmniboxEventProto::PageClassification page_classification) {
  VariationParams params;
  if (!base::GetFieldTrialParams(kBundledExperimentFieldTrialName, &params)) {
    return std::string();
  }

  return GetValueForRuleInContextFromVariationParams(params, rule,
                                                     page_classification);
}

std::string OmniboxFieldTrial::internal::GetValueForRuleInContextByFeature(
    const base::Feature& feature,
    const std::string& rule,
    metrics::OmniboxEventProto::PageClassification page_classification) {
  VariationParams params;
  if (!base::GetFieldTrialParamsByFeature(feature, &params)) {
    return std::string();
  }

  return GetValueForRuleInContextFromVariationParams(params, rule,
                                                     page_classification);
}