File: autocomplete_controller_metrics_unittest.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 (658 lines) | stat: -rw-r--r-- 28,735 bytes parent folder | download | duplicates (3)
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
// Copyright 2022 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/autocomplete_controller_metrics.h"

#include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "base/memory/raw_ref.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "components/omnibox/browser/autocomplete_controller.h"
#include "components/omnibox/browser/autocomplete_enums.h"
#include "components/omnibox/browser/autocomplete_result.h"
#include "components/omnibox/browser/fake_autocomplete_controller.h"
#include "components/omnibox/browser/fake_autocomplete_provider.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using testing::ElementsAre;
using testing::ElementsAreArray;

namespace {
// A fake provider that will:
//   a) Consume 1ms to run the sync pass.
//   b) Can be configured whether to be done or not after the sync pass.
class FakeAutocompleteProviderDelayed : public FakeAutocompleteProvider {
 public:
  FakeAutocompleteProviderDelayed(
      Type type,
      raw_ptr<base::test::SingleThreadTaskEnvironment> task_environment,
      bool done_after_sync_pass = false)
      : FakeAutocompleteProvider(type),
        task_environment_(task_environment),
        done_after_sync_pass_(done_after_sync_pass) {}

  void Start(const AutocompleteInput& input, bool minimal_changes) override {
    done_ = done_after_sync_pass_;
    task_environment_->FastForwardBy(base::Milliseconds(1));
    FakeAutocompleteProvider::Start(input, minimal_changes);
  }

  // Used to simulate the sync pass consuming 1ms.
  raw_ptr<base::test::SingleThreadTaskEnvironment> task_environment_ = nullptr;

  // Whether the provider should be done after the sync pass.
  bool done_after_sync_pass_;

 protected:
  ~FakeAutocompleteProviderDelayed() override = default;
};
}  // namespace

class AutocompleteControllerMetricsTest : public testing::Test {
 public:
  AutocompleteControllerMetricsTest()
      : controller_(&task_environment_),
        histogram_tester_(std::make_unique<base::HistogramTester>()) {
    controller_.providers_ = {
        base::MakeRefCounted<FakeAutocompleteProviderDelayed>(
            AutocompleteProvider::Type::TYPE_BOOKMARK, &task_environment_)};

    // Allow tests to simulate an initial update with no changes. Since the
    // 0-matches cases is special handled, tests can't simply do
    // `Simulate(true|false, {})` to simulate an initial update with no changes;
    // this allows tests to instead do `Simulate(true|false, {CreateMatch(0)})`.
    SimulateStart(true, {CreateMatch(0)});
    ResetHistogramTester();
  }

  AutocompleteMatch CreateMatch(int i) {
    const std::string name = base::NumberToString(i);
    AutocompleteMatch match{nullptr, 1000, false,
                            AutocompleteMatchType::HISTORY_URL};
    match.destination_url = GURL{"https://google.com/" + name};
    return match;
  }

  // By default, the controller wants async matches. `SetInputSync()` will
  // explicitly set this behavior.
  void SetInputSync(bool sync) {
    controller_.input_.set_omit_asynchronous_matches(sync);
  }

  // Mimics `AutocompleteController::Start()`'s behavior. `done` determines
  // whether the controller should be done after the sync pass. `old_result` and
  // `new_result` are passed to
  // `AutocompleteControllerMetrics::OnUpdateResult()` to determine which
  // matches changed.
  void SimulateStart(bool done, std::vector<AutocompleteMatch> matches) {
    controller_.GetFakeProvider().matches_ = matches;
    controller_.GetFakeProvider().done_ = true;
    controller_.GetFakeProvider<FakeAutocompleteProviderDelayed>()
        .done_after_sync_pass_ = done;
    controller_.Start(controller_.input_);
  }

  // Mimics `AutocompleteController::NotifyChanged()`'s behavior. `done`
  // determines weather the controller should be done after this async update.
  // `old_result` and `new_result` are passed to
  // `AutocompleteControllerMetrics::OnUpdateResult()` to determine which
  // matches changed.
  void SimulateAsyncUpdate(bool done, std::vector<AutocompleteMatch> matches) {
    controller_.GetFakeProvider().matches_ = matches;
    controller_.GetFakeProvider().done_ = done;
    task_environment_.FastForwardBy(base::Milliseconds(1));
    controller_.OnProviderUpdate(true, &controller_.GetFakeProvider());
  }

  // Simulates `AutocompleteController::Stop()`.
  void SimulateOnStop() {
    task_environment_.FastForwardBy(base::Milliseconds(1));
    controller_.Stop(AutocompleteStopReason::kInteraction);
  }

  // Convenience function to be called before/after EXPECT'ing histograms to
  // avoid old logs converting new logs.
  void ResetHistogramTester() {
    histogram_tester_ = std::make_unique<base::HistogramTester>();
  }

  // Convenience function to call AutocompleteControllerMetrics::OnStop()` and
  // expects it to not log any suggestion finalization metrics. Should be used
  // to simulate the controller completing in which case metrics should have
  // already been logged earlier during `::OnUpdateResult()`. Should not be used
  // when the controller is interrupted in which case metrics are expected to be
  // logged. Does not check provider or cross stability metrics.
  void StopAndExpectNoSuggestionFinalizationMetrics() {
    controller_.Stop(AutocompleteStopReason::kClobbered);
    ExpectNoSuggestionFinalizationMetrics();
  }

  // Convenience method to check the buckets of a single metric.
  void ExpectMetrics(const std::string metric_name,
                     std::optional<int> expected_time_ms) {
    SCOPED_TRACE(metric_name);
    const std::string full_name =
        "Omnibox.AsyncAutocompletionTime2." + metric_name;
    histogram_tester_->ExpectTotalCount(full_name,
                                        expected_time_ms.has_value());
    if (expected_time_ms) {
      // Total sum is exact, whereas buckets aren't. E.g. we can't verify
      // whether a metric recorded 300 or 301 if the containing bucket is [290,
      // 310].
      EXPECT_EQ(histogram_tester_->GetTotalSum(full_name), *expected_time_ms);
    }
  }

  // Convenience method to check the buckets of 3 metrics:
  // - '...<metric>' will be expected to have `buckets`.
  // - '...<metric>.[Completed]' will be expected to either have
  //   `buckets` or be empty, depending on `completed`.
  void ExpectSlicedMetrics(const std::string& metric,
                           std::optional<int> expected_time_ms,
                           bool completed) {
    ExpectMetrics(metric, expected_time_ms);
    ExpectMetrics(metric + ".Completed",
                  completed ? expected_time_ms : std::nullopt);
    ExpectMetrics(metric + ".Interrupted",
                  !completed ? expected_time_ms : std::nullopt);
  }

  // Convenience method to check all 9 suggestion finalization metrics are
  // empty. '...[Done|LastChange|LastDefaultChange][|.Completed]'
  void ExpectNoSuggestionFinalizationMetrics() {
    ExpectSlicedMetrics("Done", {}, false);
    ExpectSlicedMetrics("LastChange", {}, false);
    ExpectSlicedMetrics("LastDefaultChange", {}, false);
  }

  // Convince method to check all 9 suggestion finalization metrics have been
  // logged exactly once with the correct bucket. This should be used if
  // there's been a single controller request logged since the last
  // `ResetHistogramTester()`. If there have been none,
  // `ExpectNoSuggestionFinalizationMetrics()` should be used.
  void ExpectSingleCountSuggestionFinalizationMetrics(
      int done_bucket_min,
      int last_change_bucket_min,
      int last_default_change_bucket_min,
      bool completed) {
    ExpectSlicedMetrics("Done", done_bucket_min, completed);
    ExpectSlicedMetrics("LastChange", last_change_bucket_min, completed);
    ExpectSlicedMetrics("LastDefaultChange", last_default_change_bucket_min,
                        completed);
    ResetHistogramTester();
  }

  // Convenience method to check the 3 metrics for a specific provider are
  // empty. '...Provider.<Provider>[|.Completed]'
  void ExpectNoProviderMetrics(const std::string& provider) {
    ExpectSlicedMetrics("Provider." + provider, {}, false);
  }

  // Convenience method to check the 3 metrics for a specific provider have
  // been logged exactly once with the correct bucket. This should be used if
  // there's been a single log for the specified provider since the last
  // `ResetHistogramTester()`. If there have been none,
  // `ExpectNoProviderMetrics()` should be used.
  void ExpectProviderMetrics(const std::string& provider,
                             int bucket_min,
                             bool completed) {
    ExpectSlicedMetrics("Provider." + provider, bucket_min, completed);
  }

  // Used to control time passed between calls. Many metrics tested are timing
  // metrics.
  base::test::SingleThreadTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  FakeAutocompleteController controller_;
  std::unique_ptr<base::HistogramTester> histogram_tester_;
};

TEST_F(AutocompleteControllerMetricsTest, SuggestionFinalization_SyncInput) {
  // Sync inputs should not log metrics.
  SetInputSync(true);
  SimulateStart(true, {CreateMatch(1)});
  SimulateOnStop();
  ExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_OnlySyncUpdate) {
  // Sync updates should log metrics.
  SimulateStart(true, {CreateMatch(1)});
  ExpectSingleCountSuggestionFinalizationMetrics(1, 1, 1, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_OnlySyncUpdateWithNoChanges) {
  // Sync updates without changes should log metrics.
  SimulateStart(true, {CreateMatch(0)});
  ExpectSingleCountSuggestionFinalizationMetrics(1, 0, 0, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_SyncAnd3AsyncUpdate) {
  // This is the typical flow: 1 sync update followed by multiple async updates.
  SimulateStart(false, {CreateMatch(1)});
  // 1st async update.
  SimulateAsyncUpdate(false, {CreateMatch(2)});
  // 2nd async update.
  SimulateAsyncUpdate(false, {CreateMatch(3)});
  // Last async update.
  SimulateAsyncUpdate(true, {CreateMatch(4)});
  ExpectSingleCountSuggestionFinalizationMetrics(4, 4, 4, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_SyncAnd3AsyncUpdateWithNoChanges) {
  // 1 sync and 3 async updates, none of the 4 has a change.
  SimulateStart(false, {CreateMatch(0)});
  // 1st async update.
  SimulateAsyncUpdate(false, {CreateMatch(0)});
  // 2nd async update.
  SimulateAsyncUpdate(false, {CreateMatch(0)});
  // Last async update.
  SimulateAsyncUpdate(true, {CreateMatch(0)});
  ExpectSingleCountSuggestionFinalizationMetrics(4, 0, 0, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(
    AutocompleteControllerMetricsTest,
    SuggestionFinalization_UnchangedSyncAnd2UnchangedAnd1ChangedAsyncUpdates) {
  // 1 sync and 3 async updates, only the last of the 4 has a change.
  SimulateStart(false, {CreateMatch(0)});
  // 1st async update.
  SimulateAsyncUpdate(false, {CreateMatch(0)});
  // 2nd async update.
  SimulateAsyncUpdate(false, {CreateMatch(0)});
  // Last async update.
  SimulateAsyncUpdate(true, {CreateMatch(1)});
  ExpectSingleCountSuggestionFinalizationMetrics(4, 4, 4, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(
    AutocompleteControllerMetricsTest,
    SuggestionFinalization_UnchangedSyncAnd1ChangedAnd2UnchangedAsyncUpdates) {
  // 1 sync and 3 async updates, only the 2nd of the 4 has a change. Because of
  // debouncing, the change doesn't apply until the 4th update.
  SimulateStart(false, {CreateMatch(0)});
  // 1st async update.
  SimulateAsyncUpdate(false, {CreateMatch(1)});
  // 2nd async update.
  SimulateAsyncUpdate(false, {CreateMatch(1)});
  // Last async update.
  SimulateAsyncUpdate(true, {CreateMatch(1)});
  ExpectSingleCountSuggestionFinalizationMetrics(4, 4, 4, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(
    AutocompleteControllerMetricsTest,
    SuggestionFinalization_UnchangedSyncAnd1ChangedAnd2UnchangedAsyncUpdates_ChangeAppliedBeforeDone) {
  // 1 sync and 3 async updates, only the 2nd of the 4 has a change. The
  // debounced change applies before the last update.
  SimulateStart(false, {CreateMatch(0)});
  // 1st async update.
  SimulateAsyncUpdate(false, {CreateMatch(1)});
  task_environment_.FastForwardBy(base::Milliseconds(250));
  // 2nd async update.
  SimulateAsyncUpdate(false, {CreateMatch(1)});
  // Last async update.
  SimulateAsyncUpdate(true, {CreateMatch(1)});
  ExpectSingleCountSuggestionFinalizationMetrics(254, 202, 202, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_ChangedSyncAnd3UnchangedAsyncUpdates) {
  // 1 sync and 3 async updates, only the 1st of the 4 has a change.
  SimulateStart(false, {CreateMatch(1)});
  // 1st async update.
  SimulateAsyncUpdate(false, {CreateMatch(1)});
  // 2nd async update.
  SimulateAsyncUpdate(false, {CreateMatch(1)});
  // Last async update.
  SimulateAsyncUpdate(true, {CreateMatch(1)});
  ExpectSingleCountSuggestionFinalizationMetrics(4, 1, 1, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_StopTimerReached) {
  // Simulates the case where the async updates take longer than the 1.5s stop
  // timer. It's not possible for the sync update to take longer, as the stop
  // timer only starts after the sync update. The logged times should however
  // measure starting from before the sync update.
  SimulateStart(false, {CreateMatch(1)});
  // 1st async update.
  SimulateAsyncUpdate(false, {CreateMatch(1)});
  // Stop timer.
  SimulateOnStop();
  ExpectSingleCountSuggestionFinalizationMetrics(3, 1, 1, false);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest, SuggestionFinalization_Interrupted) {
  // Start 1st input.
  SimulateStart(false, {CreateMatch(1)});
  // 1 async update for 1st input.
  SimulateAsyncUpdate(false, {CreateMatch(2)});
  // Wait for the debouncer.
  task_environment_.FastForwardBy(base::Milliseconds(250));
  ExpectNoSuggestionFinalizationMetrics();
  // Interrupted by 2nd input. The log should include the time until
  // interruption.
  SimulateStart(false, {CreateMatch(3)});
  ExpectSingleCountSuggestionFinalizationMetrics(252, 202, 202, false);
  // Interrupted by 3rd input.
  task_environment_.FastForwardBy(base::Milliseconds(1));
  SimulateStart(false, {CreateMatch(4)});
  ExpectSingleCountSuggestionFinalizationMetrics(2, 1, 1, false);
  // 1st async update for 3rd input. Controller completes with the 2nd async
  // update.
  SimulateAsyncUpdate(false, {CreateMatch(5)});
  ExpectNoSuggestionFinalizationMetrics();
  // 2nd and last async update for 3rd input.
  SimulateAsyncUpdate(true, {CreateMatch(6)});
  ExpectSingleCountSuggestionFinalizationMetrics(3, 3, 3, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest, SuggestionFinalization_ExpireTimer) {
  SimulateStart(true, {CreateMatch(0), CreateMatch(1)});
  ResetHistogramTester();
  // A sync update without matches. The transferred match should remain.
  SimulateStart(false, {CreateMatch(2)});
  // Wait for the expire timer.
  task_environment_.FastForwardBy(base::Milliseconds(1000));
  // Last update with no matches.
  ExpectNoSuggestionFinalizationMetrics();
  SimulateAsyncUpdate(true, {CreateMatch(2)});
  // 500 expire timer + 200 debounce timer + 1 sync pass delay = 701.
  ExpectSingleCountSuggestionFinalizationMetrics(1002, 701, 1, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_MatchDeletion) {
  SimulateStart(true, {CreateMatch(0), CreateMatch(1)});
  ResetHistogramTester();

  auto match = CreateMatch(0);
  match.provider = &controller_.GetFakeProvider();
  match.deletable = true;

  // Match deletion with changes. Since autocompletion is complete, finalization
  // metrics aren't logged. Stability metrics are logged, but that's just
  // arbitrary for consistency with historic behavior / code simplicity, and we
  // could stop logging them for deletions if we chose.
  controller_.DeleteMatch(match);
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition"),
              testing::ElementsAre(base::Bucket(1, 1)));
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest,
       SuggestionFinalization_DefaultUnchanged) {
  // Sync update with a default match change.
  SimulateStart(false, {CreateMatch(1)});
  // 1st async update with non-default match changed.
  SimulateAsyncUpdate(false, {CreateMatch(1), CreateMatch(2)});
  // Wait for the debounce timer.
  task_environment_.FastForwardBy(base::Milliseconds(200));
  // 2nd async update with no matches changed.
  SimulateAsyncUpdate(true, {CreateMatch(1), CreateMatch(2)});
  ExpectSingleCountSuggestionFinalizationMetrics(203, 202, 1, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
}

TEST_F(AutocompleteControllerMetricsTest, Provider_SyncAndAsyncCompletion) {
  controller_.providers_ = {
      base::MakeRefCounted<FakeAutocompleteProviderDelayed>(
          AutocompleteProvider::Type::TYPE_BOOKMARK, &task_environment_, true),
      base::MakeRefCounted<FakeAutocompleteProviderDelayed>(
          AutocompleteProvider::Type::TYPE_KEYWORD, &task_environment_),
      base::MakeRefCounted<FakeAutocompleteProviderDelayed>(
          AutocompleteProvider::Type::TYPE_BUILTIN, &task_environment_),
  };
  {
    SCOPED_TRACE("Sync update with 1st provider completing.");
    controller_.GetFakeProvider(0).matches_ = {CreateMatch(0)};
    controller_.Start(controller_.input_);
    ExpectNoProviderMetrics(controller_.GetFakeProvider(0).GetName());
    ExpectNoProviderMetrics(controller_.GetFakeProvider(1).GetName());
    ExpectNoProviderMetrics(controller_.GetFakeProvider(2).GetName());
    ExpectNoSuggestionFinalizationMetrics();
    ResetHistogramTester();
  }
  {
    SCOPED_TRACE("1st async update with 2nd provider completing.");
    task_environment_.FastForwardBy(base::Milliseconds(1));
    controller_.GetFakeProvider(1).done_ = true;
    controller_.OnProviderUpdate(true, &controller_.GetFakeProvider(1));
    ExpectNoProviderMetrics(controller_.GetFakeProvider(0).GetName());
    ExpectProviderMetrics(controller_.GetFakeProvider(1).GetName(), 4, true);
    ExpectNoProviderMetrics(controller_.GetFakeProvider(2).GetName());
    ExpectNoSuggestionFinalizationMetrics();
    ResetHistogramTester();
  }
  {
    SCOPED_TRACE("Last async update with 3rd provider completing.");
    task_environment_.FastForwardBy(base::Milliseconds(1));
    controller_.GetFakeProvider(2).done_ = true;
    controller_.OnProviderUpdate(true, &controller_.GetFakeProvider(2));
    ExpectNoProviderMetrics(controller_.GetFakeProvider(0).GetName());
    ExpectNoProviderMetrics(controller_.GetFakeProvider(1).GetName());
    ExpectProviderMetrics(controller_.GetFakeProvider(2).GetName(), 5, true);
    ExpectSingleCountSuggestionFinalizationMetrics(5, 0, 0, true);
    ResetHistogramTester();
  }
  {
    SCOPED_TRACE("Stop.");
    StopAndExpectNoSuggestionFinalizationMetrics();
    ExpectNoProviderMetrics(controller_.GetFakeProvider(0).GetName());
    ExpectNoProviderMetrics(controller_.GetFakeProvider(1).GetName());
    ExpectNoProviderMetrics(controller_.GetFakeProvider(2).GetName());
    ResetHistogramTester();
  }
}

TEST_F(AutocompleteControllerMetricsTest,
       Provider_1ProviderWithMultipleUpdates) {
  // Sync update without completion.
  controller_.GetFakeProvider().done_ = true;
  SimulateStart(false, {CreateMatch(0)});

  // 1st async update without completion.
  SimulateAsyncUpdate(false, {CreateMatch(0)});

  // Last async update with completion.
  SimulateAsyncUpdate(true, {CreateMatch(0)});
  ExpectProviderMetrics(controller_.GetFakeProvider().GetName(), 3, true);
  ExpectSingleCountSuggestionFinalizationMetrics(3, 0, 0, true);
  StopAndExpectNoSuggestionFinalizationMetrics();
  ExpectNoProviderMetrics(controller_.GetFakeProvider().GetName());
}

TEST_F(AutocompleteControllerMetricsTest, Provider_Interrupted) {
  controller_.providers_ = {
      base::MakeRefCounted<FakeAutocompleteProviderDelayed>(
          AutocompleteProvider::Type::TYPE_BOOKMARK, &task_environment_),
      base::MakeRefCounted<FakeAutocompleteProviderDelayed>(
          AutocompleteProvider::Type::TYPE_KEYWORD, &task_environment_),
  };

  // Sync update. 1st provider completes; 2nd provider does not.
  controller_.GetFakeProvider(0).done_ = true;
  controller_.GetFakeProvider(1).done_ = true;
  controller_.GetFakeProvider<FakeAutocompleteProviderDelayed>(0)
      .done_after_sync_pass_ = true;
  controller_.GetFakeProvider<FakeAutocompleteProviderDelayed>(1)
      .done_after_sync_pass_ = false;
  controller_.Start(controller_.input_);

  // 2nd provider is interrupted by stop.
  SimulateOnStop();

  ExpectNoProviderMetrics(controller_.GetFakeProvider(0).GetName());
  ExpectProviderMetrics(controller_.GetFakeProvider(1).GetName(), 3, false);
  ExpectSingleCountSuggestionFinalizationMetrics(3, 0, 0, false);
}

TEST_F(AutocompleteControllerMetricsTest, MatchStability) {
  auto create_result = [&](std::vector<int> ids) {
    std::vector<AutocompleteMatch> matches;
    std::ranges::transform(ids, std::back_inserter(matches), [&](int id) {
      auto match = CreateMatch(id);
      match.relevance -= id;
      return match;
    });
    return matches;
  };

  const auto first_result = create_result({10, 11, 12, 13, 14});
  // Same as `first_result`, but with these changes:
  //  - Last two matches removed.
  //  - Default match updated to a new URL.
  //  - Third match updated to a new URL.
  const auto second_result = create_result({0, 11, 20});
  // Same as `second_result`, but with these changes:
  //  - 2 new matches appended to the bottom.
  const auto third_result = create_result({0, 11, 20, 21, 22});

  // Verify logging to the CrossInput* histograms.
  SimulateStart(true, first_result);
  ResetHistogramTester();
  SimulateStart(true, second_result);
  // Expect the default match, third match, and last two matches to be logged
  // as changed, and nothing else.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.CrossInput"),
              testing::ElementsAre(base::Bucket(0, 1), base::Bucket(2, 1),
                                   base::Bucket(3, 1), base::Bucket(4, 1)));
  // Expect that we log that at least one of the matches has changed.
  EXPECT_THAT(
      histogram_tester_->GetAllSamples(
          "Omnibox.MatchStability2.MatchChangeInAnyPosition.CrossInput"),
      testing::ElementsAre(base::Bucket(1, 1)));
  // Expect that we don't log sync updates to the Async histograms.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.Async"),
              testing::ElementsAre());
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition.Async"),
              testing::ElementsAre());
  // Verify the unsliced histograms.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex"),
              testing::ElementsAre(base::Bucket(0, 1), base::Bucket(2, 1),
                                   base::Bucket(3, 1), base::Bucket(4, 1)));
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition"),
              testing::ElementsAre(base::Bucket(1, 1)));
  ResetHistogramTester();

  // Verify logging to the Async* histograms.
  SimulateStart(false, first_result);
  ResetHistogramTester();
  SimulateAsyncUpdate(true, second_result);
  // Expect the default match, third match, and last two matches to be logged
  // as changed, and nothing else.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.Async"),
              testing::ElementsAre(base::Bucket(0, 1), base::Bucket(2, 1),
                                   base::Bucket(3, 1), base::Bucket(4, 1)));
  // Expect that we log that at least one of the matches has changed.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition.Async"),
              testing::ElementsAre(base::Bucket(1, 1)));
  // Expect that we don't log sync updates to the CrossInput histograms.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.CrossInput"),
              testing::ElementsAre());
  EXPECT_THAT(
      histogram_tester_->GetAllSamples(
          "Omnibox.MatchStability2.MatchChangeInAnyPosition.CrossInput"),
      testing::ElementsAre());
  // Verify the unsliced histograms.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex"),
              testing::ElementsAre(base::Bucket(0, 1), base::Bucket(2, 1),
                                   base::Bucket(3, 1), base::Bucket(4, 1)));
  // Expect that we log that at least one of the matches has changed.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition"),
              testing::ElementsAre(base::Bucket(1, 1)));
  ResetHistogramTester();

  // Verify no logging when appending matches for sync updates.
  SimulateStart(true, second_result);
  ResetHistogramTester();
  SimulateStart(true, third_result);
  // Expect no changes logged; expect 1 false logged to each
  // MatchChangeInAnyPosition.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.CrossInput"),
              testing::ElementsAre());
  EXPECT_THAT(
      histogram_tester_->GetAllSamples(
          "Omnibox.MatchStability2.MatchChangeInAnyPosition.CrossInput"),
      testing::ElementsAre(base::Bucket(0, 1)));
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.Async"),
              testing::ElementsAre());
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition.Async"),
              testing::ElementsAre());
  // Verify the unsliced histograms.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex"),
              testing::ElementsAre());
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition"),
              testing::ElementsAre(base::Bucket(0, 1)));
  ResetHistogramTester();

  // Verify no logging when appending matches for async updates.
  SimulateStart(false, second_result);
  ResetHistogramTester();
  SimulateAsyncUpdate(true, third_result);
  // Expect no changes logged; expect 1 false logged to each
  // MatchChangeInAnyPosition.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.CrossInput"),
              testing::ElementsAre());
  EXPECT_THAT(
      histogram_tester_->GetAllSamples(
          "Omnibox.MatchStability2.MatchChangeInAnyPosition.CrossInput"),
      testing::ElementsAre());
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex.Async"),
              testing::ElementsAre());
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition.Async"),
              testing::ElementsAre(base::Bucket(0, 1)));
  // Verify the unsliced histograms.
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeIndex"),
              testing::ElementsAre());
  EXPECT_THAT(histogram_tester_->GetAllSamples(
                  "Omnibox.MatchStability2.MatchChangeInAnyPosition"),
              testing::ElementsAre(base::Bucket(0, 1)));
  ResetHistogramTester();
}