File: group_suggestions_tracker.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 (319 lines) | stat: -rw-r--r-- 11,642 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
// Copyright 2025 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/visited_url_ranking/internal/url_grouping/group_suggestions_tracker.h"

#include <cstdint>
#include <unordered_set>

#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/flat_set.h"
#include "base/hash/hash.h"
#include "base/json/values_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/time/time.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/visited_url_ranking/public/features.h"
#include "components/visited_url_ranking/public/url_grouping/group_suggestions.h"
#include "components/visited_url_ranking/public/url_visit_schema.h"

namespace visited_url_ranking {

namespace {

using segmentation_platform::processing::ProcessedValue;

constexpr auto kReasonToMaxOverlappingTabs =
    base::MakeFixedFlatMap<GroupSuggestion::SuggestionReason, float>({
        {GroupSuggestion::SuggestionReason::kRecentlyOpened, 0.55},
        {GroupSuggestion::SuggestionReason::kSwitchedBetween, 0.60},
        {GroupSuggestion::SuggestionReason::kSimilarSource, 0.55},
        {GroupSuggestion::SuggestionReason::kSameOrigin, 0.55},
    });

float GetOverlappingTabCount(const base::flat_set<int>& shown_tabs,
                             const std::vector<int>& tab_ids) {
  std::vector<int> overlap;
  for (int x : tab_ids) {
    if (shown_tabs.count(x)) {
      overlap.push_back(x);
    }
  }
  return static_cast<float>(overlap.size()) / tab_ids.size();
}

std::optional<std::string> GetHostForTab(
    const std::vector<scoped_refptr<segmentation_platform::InputContext>>&
        inputs,
    float tab_id) {
  const char* tab_id_input =
      GetNameForInput(URLVisitAggregateRankingModelInputSignals::kTabId);
  for (const auto& input : inputs) {
    std::optional<ProcessedValue> tab_id_value =
        input->GetMetadataArgument(tab_id_input);
    std::optional<ProcessedValue> url_value = input->GetMetadataArgument("url");
    if (!tab_id_value || !url_value) {
      continue;
    }
    if (tab_id_value->float_val == tab_id) {
      if (!url_value->url->host().empty()) {
        return url_value->url->host();
      }
      return std::nullopt;
    }
  }
  return std::nullopt;
}

}  // namespace

const char GroupSuggestionsTracker::kGroupSuggestionsTrackerStatePref[] =
    "group_suggestions_tracker.state";
const char GroupSuggestionsTracker::kGroupSuggestionsTrackerTimeKey[] =
    "time_shown";
const char GroupSuggestionsTracker::kGroupSuggestionsTrackerUserResponseKey[] =
    "user_response";
const char GroupSuggestionsTracker::kGroupSuggestionsTrackerUserTabIdsKey[] =
    "tab_ids";
const char GroupSuggestionsTracker::kGroupSuggestionsTrackerHostHashesKey[] =
    "host_hashes";

GroupSuggestionsTracker::GroupSuggestionsTracker(PrefService* pref_service)
    : pref_service_(pref_service) {
  const auto& old_suggestion_list =
      pref_service_->GetList(kGroupSuggestionsTrackerStatePref);
  base::Time now = base::Time::Now();
  base::Value::List new_suggestion_list;
  for (const base::Value& old_suggestion : old_suggestion_list) {
    // Not including old suggestions in the new list.
    auto suggestion_optional =
        GroupSuggestionsTracker::ShownSuggestion::FromDict(
            old_suggestion.GetDict());
    if (suggestion_optional.has_value() &&
        (now - suggestion_optional->time_shown <=
         features::kGroupSuggestionThrottleAgeLimit.Get())) {
      suggestions_.push_back(std::move(suggestion_optional.value()));
      new_suggestion_list.Append(old_suggestion.Clone());
    }
  }
  pref_service_->SetList(kGroupSuggestionsTrackerStatePref,
                         std::move(new_suggestion_list));
}

GroupSuggestionsTracker::~GroupSuggestionsTracker() = default;

GroupSuggestionsTracker::ShownSuggestion::ShownSuggestion() = default;
GroupSuggestionsTracker::ShownSuggestion::~ShownSuggestion() = default;
GroupSuggestionsTracker::ShownSuggestion::ShownSuggestion(
    GroupSuggestionsTracker::ShownSuggestion&&) = default;
GroupSuggestionsTracker::ShownSuggestion&
GroupSuggestionsTracker::ShownSuggestion::operator=(
    GroupSuggestionsTracker::ShownSuggestion&& suggestion) = default;

base::Value::Dict GroupSuggestionsTracker::ShownSuggestion::ToDict() const {
  base::Value::Dict shown_suggestion_dict;
  shown_suggestion_dict.Set(kGroupSuggestionsTrackerTimeKey,
                            base::TimeToValue(time_shown));
  base::Value::List suggestion_tab_ids;
  for (int tab_id : tab_ids) {
    suggestion_tab_ids.Append(tab_id);
  }
  shown_suggestion_dict.Set(kGroupSuggestionsTrackerUserTabIdsKey,
                            std::move(suggestion_tab_ids));
  base::Value::List suggestion_host_hashes;
  for (int host_hash : host_hashes) {
    suggestion_host_hashes.Append(host_hash);
  }
  shown_suggestion_dict.Set(kGroupSuggestionsTrackerHostHashesKey,
                            std::move(suggestion_host_hashes));
  shown_suggestion_dict.Set(kGroupSuggestionsTrackerUserResponseKey,
                            static_cast<int>(user_response));
  return shown_suggestion_dict;
}

std::optional<GroupSuggestionsTracker::ShownSuggestion>
GroupSuggestionsTracker::ShownSuggestion::FromDict(
    const base::Value::Dict& dict) {
  ShownSuggestion suggestion;
  // Populate shown time.
  const base::Value* timestamp_ptr = dict.Find(kGroupSuggestionsTrackerTimeKey);
  if (!timestamp_ptr) {
    return std::nullopt;
  }
  std::optional<base::Time> timestamp = base::ValueToTime(*timestamp_ptr);
  if (!timestamp.has_value()) {
    return std::nullopt;
  }
  suggestion.time_shown = timestamp.value();

  // Populate tab ids.
  std::vector<int> tab_ids;
  auto* tab_ids_list_ptr = dict.FindList(kGroupSuggestionsTrackerUserTabIdsKey);
  if (!tab_ids_list_ptr) {
    return std::nullopt;
  }
  for (const auto& i : *tab_ids_list_ptr) {
    tab_ids.push_back(i.GetInt());
  }
  suggestion.tab_ids = std::move(tab_ids);

  // Populate host hashes.
  std::set<int> host_hashes;
  auto* host_hashes_list_ptr =
      dict.FindList(kGroupSuggestionsTrackerHostHashesKey);
  if (!host_hashes_list_ptr) {
    return std::nullopt;
  }
  for (const auto& i : *host_hashes_list_ptr) {
    host_hashes.insert(i.GetInt());
  }
  suggestion.host_hashes = std::move(host_hashes);

  // Populate user response.
  auto user_response_optional =
      dict.FindInt(kGroupSuggestionsTrackerUserResponseKey);
  if (!user_response_optional.has_value()) {
    return std::nullopt;
  }
  suggestion.user_response =
      static_cast<UserResponse>(user_response_optional.value());
  return suggestion;
}

void GroupSuggestionsTracker::RegisterProfilePrefs(
    PrefRegistrySimple* registry) {
  registry->RegisterListPref(kGroupSuggestionsTrackerStatePref);
}

void GroupSuggestionsTracker::AddShownSuggestion(
    const GroupSuggestion& suggestion,
    const std::vector<scoped_refptr<segmentation_platform::InputContext>>&
        inputs,
    UserResponse user_response) {
  if (last_cached_suggestions_and_inputs_.has_value()) {
    // Try to remove the shown suggestion from the cached list.
    std::erase_if(last_cached_suggestions_and_inputs_->first.suggestions,
                  [&](const auto& cached_suggestion) {
                    return cached_suggestion.suggestion_id ==
                           suggestion.suggestion_id;
                  });
    if (last_cached_suggestions_and_inputs_->first.suggestions.empty()) {
      InvalidateCache();
    }
  }
  ShownSuggestion item;
  item.time_shown = base::Time::Now();
  item.tab_ids = suggestion.tab_ids;
  item.user_response = user_response;
  for (const int tab_id : item.tab_ids) {
    std::optional<std::string> host_optional = GetHostForTab(inputs, tab_id);
    if (host_optional.has_value()) {
      item.host_hashes.insert(base::PersistentHash(*host_optional));
    }
  }
  suggestions_.push_back(std::move(item));

  // Append latest suggestion and remove old suggestions in storage.
  base::Time now = base::Time::Now();
  std::erase_if(suggestions_, [&](const ShownSuggestion& item) {
    return now - item.time_shown >
           features::kGroupSuggestionThrottleAgeLimit.Get();
  });
  base::Value::List new_suggestion_list;
  for (const ShownSuggestion& shown_suggestion : suggestions_) {
    new_suggestion_list.Append(shown_suggestion.ToDict());
  }
  pref_service_->SetList(kGroupSuggestionsTrackerStatePref,
                         std::move(new_suggestion_list));
}

bool GroupSuggestionsTracker::ShouldShowSuggestion(
    const GroupSuggestion& suggestion,
    const std::vector<scoped_refptr<segmentation_platform::InputContext>>&
        inputs) {
  if (suggestion.tab_ids.empty() ||
      suggestion.suggestion_reason ==
          GroupSuggestion::SuggestionReason::kUnknown) {
    return false;
  }

  base::Time now = base::Time::Now();

  // Remove any old suggestions:
  std::erase_if(suggestions_, [&](const ShownSuggestion& item) {
    return now - item.time_shown >
           features::kGroupSuggestionThrottleAgeLimit.Get();
  });

  if (HasOverlappingTabs(suggestion)) {
    base::UmaHistogramEnumeration(
        "GroupSuggestionsService.SuggestionThrottledReason",
        TabGroupSuggestionThrottleReason::kOverlappingTabs);
    return false;
  }
  if (HasOverlappingHosts(suggestion, inputs)) {
    base::UmaHistogramEnumeration(
        "GroupSuggestionsService.SuggestionThrottledReason",
        TabGroupSuggestionThrottleReason::kOverlappingHosts);
    return false;
  }

  return true;
}

bool GroupSuggestionsTracker::HasOverlappingTabs(
    const GroupSuggestion& suggestion) const {
  base::flat_set<int> all_shown;
  for (const auto& item : suggestions_) {
    all_shown.insert(item.tab_ids.begin(), item.tab_ids.end());
  }
  float overlap = GetOverlappingTabCount(all_shown, suggestion.tab_ids);
  return overlap > kReasonToMaxOverlappingTabs.at(suggestion.suggestion_reason);
}

bool GroupSuggestionsTracker::HasOverlappingHosts(
    const GroupSuggestion& suggestion,
    const std::vector<scoped_refptr<segmentation_platform::InputContext>>&
        inputs) const {
  base::flat_set<int> all_shown_hosts;
  for (const auto& item : suggestions_) {
    all_shown_hosts.insert(item.host_hashes.begin(), item.host_hashes.end());
  }
  std::vector<int> suggestion_hosts;
  for (const int tab_id : suggestion.tab_ids) {
    std::optional<std::string> host_optional = GetHostForTab(inputs, tab_id);
    if (host_optional) {
      suggestion_hosts.push_back(base::PersistentHash(*host_optional));
    }
  }
  float hosts_overlap =
      GetOverlappingTabCount(all_shown_hosts, suggestion_hosts);
  return hosts_overlap >
         kReasonToMaxOverlappingTabs.at(suggestion.suggestion_reason);
}

void GroupSuggestionsTracker::CacheSuggestions(
    GroupSuggestions suggestions,
    std::vector<scoped_refptr<segmentation_platform::InputContext>> inputs) {
  last_cached_suggestions_and_inputs_ =
      std::make_pair(std::move(suggestions), std::move(inputs));
}

std::optional<CachedSuggestionsAndInputs>
GroupSuggestionsTracker::GetCachedSuggestions() const {
  if (last_cached_suggestions_and_inputs_) {
    return std::make_pair(last_cached_suggestions_and_inputs_->first.DeepCopy(),
                          last_cached_suggestions_and_inputs_->second);
  }
  return std::nullopt;
}

void GroupSuggestionsTracker::InvalidateCache() {
  last_cached_suggestions_and_inputs_.reset();
}

}  // namespace visited_url_ranking