File: page_resource_monitor_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 (394 lines) | stat: -rw-r--r-- 16,023 bytes parent folder | download | duplicates (9)
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
// 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/performance_manager/public/metrics/page_resource_monitor.h"

#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/containers/flat_map.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/system/sys_info.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/performance_manager/embedder/graph_features.h"
#include "components/performance_manager/public/features.h"
#include "components/performance_manager/public/graph/frame_node.h"
#include "components/performance_manager/public/graph/graph.h"
#include "components/performance_manager/public/graph/page_node.h"
#include "components/performance_manager/public/graph/process_node.h"
#include "components/performance_manager/public/resource_attribution/cpu_measurement_delegate.h"
#include "components/performance_manager/public/resource_attribution/memory_measurement_delegate.h"
#include "components/performance_manager/test_support/graph_test_harness.h"
#include "components/performance_manager/test_support/mock_graphs.h"
#include "components/performance_manager/test_support/resource_attribution/measurement_delegates.h"
#include "components/ukm/test_ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/metrics/public/mojom/ukm_interface.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace performance_manager::metrics {

namespace {

using PageMeasurementAlgorithm = PageResourceMonitor::PageMeasurementAlgorithm;
using PageMeasurementBackgroundState =
    PageResourceMonitor::PageMeasurementBackgroundState;

using CPUMeasurementDelegate = resource_attribution::CPUMeasurementDelegate;
using FakeMemoryMeasurementDelegateFactory =
    resource_attribution::FakeMemoryMeasurementDelegateFactory;
using MemoryMeasurementDelegate =
    resource_attribution::MemoryMeasurementDelegate;
using SimulatedCPUMeasurementDelegate =
    resource_attribution::SimulatedCPUMeasurementDelegate;
using SimulatedCPUMeasurementDelegateFactory =
    resource_attribution::SimulatedCPUMeasurementDelegateFactory;

class PageResourceMonitorUnitTest : public GraphTestHarness {
 public:
  PageResourceMonitorUnitTest() = default;
  ~PageResourceMonitorUnitTest() override = default;

  PageResourceMonitorUnitTest(const PageResourceMonitorUnitTest&) = delete;
  PageResourceMonitorUnitTest& operator=(const PageResourceMonitorUnitTest&) =
      delete;

  void SetUp() override {
    GetGraphFeatures().EnableResourceAttributionScheduler();
    GraphTestHarness::SetUp();

    // Return 50% CPU used by default.
    cpu_delegate_factory_.SetDefaultCPUUsage(0.5);
    CPUMeasurementDelegate::SetDelegateFactoryForTesting(
        graph(), &cpu_delegate_factory_);
    MemoryMeasurementDelegate::SetDelegateFactoryForTesting(
        graph(), &memory_delegate_factory_);

    std::unique_ptr<PageResourceMonitor> monitor =
        std::make_unique<PageResourceMonitor>(enable_system_cpu_probe_);
    monitor_ = monitor.get();
    graph()->PassToGraph(std::move(monitor));
    ResetUkmRecorder();
    last_collection_time_ = base::TimeTicks::Now();
  }

  void TearDown() override {
    test_ukm_recorder_.reset();
    GraphTestHarness::TearDown();
  }

 protected:
  ukm::TestUkmRecorder* test_ukm_recorder() { return test_ukm_recorder_.get(); }
  PageResourceMonitor* monitor() { return monitor_; }

  SimulatedCPUMeasurementDelegate& GetCPUDelegate(const ProcessNode* node) {
    return cpu_delegate_factory_.GetDelegate(node);
  }

  FakeMemoryMeasurementDelegateFactory& GetMemoryDelegate() {
    return memory_delegate_factory_;
  }

  // Advances the clock to trigger the PageResourceUsage UKM.
  void TriggerCollectPageResourceUsage();

  // Advances the mock clock slightly to give enough time to make asynchronous
  // measurements after TriggerCollectPageResourceUsage(). If
  // `include_system_cpu` is true, also waits for some real time to let the
  // system CpuProbe collect data.
  void WaitForMetrics(bool include_system_cpu = false);

  void ResetUkmRecorder() {
    test_ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
  }

  // Waits for metrics collection and tests whether the BackgroundState logged
  // for each ukm::SourceId matches the given expectation, then clears the
  // collected UKM's for the next slice.
  void WaitForMetricsAndTestBackgroundStates(
      std::map<ukm::SourceId, PageMeasurementBackgroundState> expected_states);

  // Subclasses can override this before calling
  // PageResourceMonitorUnitTest::SetUp() to simulate an environment where
  // CPUProbe::Create() returns nullptr.
  bool enable_system_cpu_probe_ = true;

  raw_ptr<PageResourceMonitor> monitor_ = nullptr;

 private:
  // Advances the mock clock to `target_time`.
  void WaitUntil(base::TimeTicks target_time) {
    ASSERT_GT(target_time, base::TimeTicks::Now());
    task_env().FastForwardBy(target_time - base::TimeTicks::Now());
  }

  std::unique_ptr<ukm::TestUkmRecorder> test_ukm_recorder_;

  // The last time TriggerCollectPageResourceUsage() was called.
  base::TimeTicks last_collection_time_;

  // Factories to return fake measurement delegates. These must be deleted after
  // `monitor_` to ensure that they outlive all delegates they create.
  SimulatedCPUMeasurementDelegateFactory cpu_delegate_factory_;
  FakeMemoryMeasurementDelegateFactory memory_delegate_factory_;
};

void PageResourceMonitorUnitTest::TriggerCollectPageResourceUsage() {
  WaitUntil(last_collection_time_ + monitor_->GetCollectionDelayForTesting());
  last_collection_time_ = base::TimeTicks::Now();
}

void PageResourceMonitorUnitTest::WaitForMetrics(bool include_system_cpu) {
  if (include_system_cpu) {
    // Page CPU can use the mock clock, but CPUProbe needs real time to pass.
    base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
  }
  // GraphTestHarness uses ThreadPoolExecutionMode::QUEUED, so RunLoop only
  // pumps the main thread. FastForwardBy also pumps ThreadPool threads. With
  // the mock clock, any timeout will pump the threads enough to post the tasks
  // that gather and record metrics.
  task_env().FastForwardBy(TestTimeouts::tiny_timeout());
}

void PageResourceMonitorUnitTest::WaitForMetricsAndTestBackgroundStates(
    std::map<ukm::SourceId, PageMeasurementBackgroundState> expected_states) {
  WaitForMetrics();
  auto entries = test_ukm_recorder()->GetEntriesByName(
      ukm::builders::PerformanceManager_PageResourceUsage2::kEntryName);
  // Expect 1 entry per page.
  EXPECT_EQ(entries.size(), expected_states.size());
  for (const ukm::mojom::UkmEntry* entry : entries) {
    test_ukm_recorder()->ExpectEntryMetric(
        entry, "BackgroundState",
        static_cast<int64_t>(expected_states.at(entry->source_id)));
  }
  ResetUkmRecorder();
}

TEST_F(PageResourceMonitorUnitTest, TestPageResourceUsage) {
  MockSinglePageInSingleProcessGraph mock_graph(graph());
  ukm::SourceId mock_source_id = ukm::NoURLSourceId();
  mock_graph.page->SetType(performance_manager::PageType::kTab);
  mock_graph.page->SetUkmSourceId(mock_source_id);

  TriggerCollectPageResourceUsage();
  WaitForMetrics();

  auto entries = test_ukm_recorder()->GetEntriesByName(
      ukm::builders::PerformanceManager_PageResourceUsage2::kEntryName);
  EXPECT_EQ(entries.size(), 1u);
}

TEST_F(PageResourceMonitorUnitTest, TestPageResourceUsageNavigation) {
  MockSinglePageInSingleProcessGraph mock_graph(graph());
  ukm::SourceId mock_source_id =
      ukm::AssignNewSourceId();  // ukm::NoURLSourceId();
  ukm::SourceId mock_source_id_2 = ukm::AssignNewSourceId();

  mock_graph.page->SetUkmSourceId(mock_source_id);
  mock_graph.page->SetType(performance_manager::PageType::kTab);

  // Each SourceId should record an entry.
  std::vector<ukm::SourceId> expected_ids{mock_source_id, mock_source_id_2};

  TriggerCollectPageResourceUsage();
  WaitForMetrics();

  auto entries = test_ukm_recorder()->GetEntriesByName(
      ukm::builders::PerformanceManager_PageResourceUsage2::kEntryName);
  EXPECT_EQ(entries.size(), 1u);

  mock_graph.page->SetUkmSourceId(mock_source_id_2);

  TriggerCollectPageResourceUsage();
  WaitForMetrics();

  entries = test_ukm_recorder()->GetEntriesByName(
      ukm::builders::PerformanceManager_PageResourceUsage2::kEntryName);
  EXPECT_EQ(entries.size(), 2u);

  std::vector<ukm::SourceId> ids;
  for (const ukm::mojom::UkmEntry* entry : entries) {
    const int64_t* algorithm =
        test_ukm_recorder()->GetEntryMetric(entry, "MeasurementAlgorithm");
    ASSERT_NE(algorithm, nullptr);
    EXPECT_EQ(static_cast<PageMeasurementAlgorithm>(*algorithm),
              PageMeasurementAlgorithm::kEvenSplitAndAggregate);
    ids.emplace_back(entry->source_id);
  }

  EXPECT_THAT(ids, ::testing::UnorderedElementsAreArray(expected_ids));
}

TEST_F(PageResourceMonitorUnitTest, TestOnlyRecordTabs) {
  MockSinglePageInSingleProcessGraph mock_graph(graph());
  ukm::SourceId mock_source_id = ukm::NoURLSourceId();
  mock_graph.page->SetUkmSourceId(mock_source_id);

  TriggerCollectPageResourceUsage();
  WaitForMetrics();

  auto entries2 = test_ukm_recorder()->GetEntriesByName(
      ukm::builders::PerformanceManager_PageResourceUsage2::kEntryName);
  EXPECT_EQ(entries2.size(), 0UL);
}

TEST_F(PageResourceMonitorUnitTest, TestResourceUsage) {
  MockMultiplePagesWithMultipleProcessesGraph mock_graph(graph());

  // Register fake memory results. Make sure they're divisible by 2 for easier
  // matching when divided between frames.
  MemoryMeasurementDelegate::MemorySummaryMap& memory_summaries =
      GetMemoryDelegate().memory_summaries();
  memory_summaries[mock_graph.process->GetResourceContext()] = {
      .resident_set_size_kb = 1230};
  memory_summaries[mock_graph.other_process->GetResourceContext()] = {
      .resident_set_size_kb = 4560, .private_footprint_kb = 7890};

  const ukm::SourceId mock_source_id = ukm::AssignNewSourceId();
  mock_graph.page->SetType(performance_manager::PageType::kTab);
  mock_graph.page->SetUkmSourceId(mock_source_id);

  const ukm::SourceId mock_source_id2 = ukm::AssignNewSourceId();
  mock_graph.other_page->SetType(performance_manager::PageType::kTab);
  mock_graph.other_page->SetUkmSourceId(mock_source_id2);

  TriggerCollectPageResourceUsage();
  WaitForMetrics();

  auto entries = test_ukm_recorder()->GetEntriesByName(
      ukm::builders::PerformanceManager_PageResourceUsage2::kEntryName);
  // Expect 1 entry per page.
  EXPECT_EQ(entries.size(), 2u);

  // `page` gets its memory from `frame`, which is 1/2 the memory from
  // `process`.
  // `other_page` gets its memory from `other_frame` (1/2 of `process`) +
  // `child_frame` (all of `other_process`).
  // See the diagram in
  // components/performance_manager/test_support/mock_graphs.h.
  const base::flat_map<ukm::SourceId, int64_t> expected_resident_set_size{
      {mock_source_id, 1230 / 2},
      {mock_source_id2, 1230 / 2 + 4560},
  };
  const base::flat_map<ukm::SourceId, int64_t> expected_private_footprint{
      {mock_source_id, 0},
      {mock_source_id2, 7890},
  };
  // The SimulatedCPUMeasurementDelegate returns 50% of the CPU is used.
  // `process` contains `frame` and `other_frame` -> each gets 25%
  // `other_process` contains `child_frame` -> 50%
  const base::flat_map<ukm::SourceId, int64_t> expected_cpu_usage{
      // `page` contains `frame`
      {mock_source_id, 2500},
      // `other_page` gets the sum of `other_frame` and `child_frame`
      {mock_source_id2, 7500},
  };
  const auto kExpectedAllCPUUsage = 2500 + 7500;

  // Each SourceId should record an entry.
  std::vector<ukm::SourceId> expected_ids{mock_source_id, mock_source_id2};

  std::vector<ukm::SourceId> ids;
  for (const ukm::mojom::UkmEntry* entry : entries) {
    test_ukm_recorder()->ExpectEntryMetric(
        entry, "ResidentSetSizeEstimate",
        expected_resident_set_size.at(entry->source_id));
    test_ukm_recorder()->ExpectEntryMetric(
        entry, "PrivateFootprintEstimate",
        expected_private_footprint.at(entry->source_id));
    test_ukm_recorder()->ExpectEntryMetric(
        entry, "RecentCPUUsage", expected_cpu_usage.at(entry->source_id));
    test_ukm_recorder()->ExpectEntryMetric(entry, "TotalRecentCPUUsageAllPages",
                                           kExpectedAllCPUUsage);
    const int64_t* algorithm =
        test_ukm_recorder()->GetEntryMetric(entry, "MeasurementAlgorithm");
    ASSERT_NE(algorithm, nullptr);
    EXPECT_EQ(static_cast<PageMeasurementAlgorithm>(*algorithm),
              PageMeasurementAlgorithm::kEvenSplitAndAggregate);
    ids.emplace_back(entry->source_id);
  }
  EXPECT_THAT(ids, ::testing::UnorderedElementsAreArray(expected_ids));
}

TEST_F(PageResourceMonitorUnitTest, TestResourceUsageBackgroundState) {
  MockMultiplePagesWithMultipleProcessesGraph mock_graph(graph());
  const ukm::SourceId mock_source_id = ukm::AssignNewSourceId();
  mock_graph.page->SetType(performance_manager::PageType::kTab);
  mock_graph.page->SetUkmSourceId(mock_source_id);

  const ukm::SourceId mock_source_id2 = ukm::AssignNewSourceId();
  mock_graph.other_page->SetType(performance_manager::PageType::kTab);
  mock_graph.other_page->SetUkmSourceId(mock_source_id2);

  // Start with page 1 in foreground. Pages remain in the same state for all
  // of the first measurement period.
  mock_graph.page->SetIsVisible(true);
  mock_graph.other_page->SetIsVisible(false);
  TriggerCollectPageResourceUsage();

  // Pages become audible for all of next measurement period. Change the state
  // before waiting for the metrics to finish logging so the change happens at
  // the beginning of the period.
  mock_graph.page->SetIsAudible(true);
  mock_graph.other_page->SetIsAudible(true);

  // Test the metrics from the first measurement period.
  WaitForMetricsAndTestBackgroundStates(
      {{mock_source_id, PageMeasurementBackgroundState::kForeground},
       {mock_source_id2, PageMeasurementBackgroundState::kBackground}});

  // Finish the second measurement period.
  TriggerCollectPageResourceUsage();
  WaitForMetricsAndTestBackgroundStates(
      {{mock_source_id, PageMeasurementBackgroundState::kForeground},
       {mock_source_id2,
        PageMeasurementBackgroundState::kAudibleInBackground}});

  // Partway through next measurement period:
  // - Page 1 moves to background (still audible).
  // - Page 2 stops playing audio.
  const base::TimeDelta partial_delay =
      monitor_->GetCollectionDelayForTesting() / 4;
  task_env().FastForwardBy(partial_delay);
  mock_graph.page->SetIsVisible(false);
  mock_graph.other_page->SetIsAudible(false);
  TriggerCollectPageResourceUsage();
  WaitForMetricsAndTestBackgroundStates(
      {{mock_source_id,
        PageMeasurementBackgroundState::kMixedForegroundBackground},
       {mock_source_id2,
        PageMeasurementBackgroundState::kBackgroundMixedAudible}});

  // Partway through next measurement period, page 2 moves to foreground (still
  // inaudible).
  task_env().FastForwardBy(partial_delay);
  mock_graph.other_page->SetIsVisible(true);
  TriggerCollectPageResourceUsage();
  WaitForMetricsAndTestBackgroundStates(
      {{mock_source_id, PageMeasurementBackgroundState::kAudibleInBackground},
       {mock_source_id2,
        PageMeasurementBackgroundState::kMixedForegroundBackground}});
}

}  // namespace

}  // namespace performance_manager::metrics