File: ephemeral_home_module_backend.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 (226 lines) | stat: -rw-r--r-- 9,018 bytes parent folder | download | duplicates (6)
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
// Copyright 2024 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/segmentation_platform/embedder/home_modules/ephemeral_home_module_backend.h"

#include <memory>
#include <vector>

#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/feature_list.h"
#include "base/task/sequenced_task_runner.h"
#include "build/build_config.h"
#include "components/segmentation_platform/embedder/home_modules/card_selection_info.h"
#include "components/segmentation_platform/embedder/home_modules/card_selection_signals.h"
#include "components/segmentation_platform/embedder/home_modules/constants.h"
#include "components/segmentation_platform/embedder/home_modules/home_modules_card_registry.h"
#include "components/segmentation_platform/internal/metadata/metadata_writer.h"
#include "components/segmentation_platform/public/config.h"
#include "components/segmentation_platform/public/features.h"
#include "components/segmentation_platform/public/model_provider.h"
#include "components/segmentation_platform/public/proto/aggregation.pb.h"
#include "components/segmentation_platform/public/proto/model_metadata.pb.h"

namespace segmentation_platform::home_modules {

namespace {
using proto::SegmentId;

// Default parameters for EphemeralHomeModuleBackend model.
constexpr SegmentId kSegmentId = SegmentId::EPHEMERAL_HOME_MODULE_BACKEND;
// Default parameters for TestEphemeralHomeModuleBackend model.
constexpr SegmentId kTestSegmentId =
    SegmentId::EPHEMERAL_HOME_MODULE_BACKEND_TEST;
constexpr int64_t kModelVersion = 1;
// Store 28 buckets of input data (28 days).
constexpr int64_t kSignalStorageLength = 28;
// Wait until we have 7 days of data.
constexpr int64_t kMinSignalCollectionLength = 0;
// Refresh the result every 7 days.
constexpr int64_t kResultTTLDays = 7;
// Number of labels to return to the caller.
constexpr size_t kMaxOutputLabelsToRank = 1;

constexpr char kEphemeralHomeModuleBackendUmaName[] =
    "EphemeralHomeModuleBackend";

}  // namespace

// static
std::unique_ptr<Config> EphemeralHomeModuleBackend::GetConfig(
    HomeModulesCardRegistry* home_modules_card_registry) {
  if (!base::FeatureList::IsEnabled(
          features::kSegmentationPlatformEphemeralCardRanker)) {
    return nullptr;
  }
  auto config = std::make_unique<Config>();
  config->segmentation_key = kEphemeralHomeModuleBackendKey;
  config->segmentation_uma_name = kEphemeralHomeModuleBackendUmaName;
  config->AddSegmentId(kSegmentId,
                       std::make_unique<EphemeralHomeModuleBackend>(
                           home_modules_card_registry->GetWeakPtr()));
  config->auto_execute_and_cache = false;
  return config;
}

EphemeralHomeModuleBackend::EphemeralHomeModuleBackend(
    base::WeakPtr<HomeModulesCardRegistry> home_modules_card_registry)
    : DefaultModelProvider(kSegmentId),
      home_modules_card_registry_(home_modules_card_registry) {}
EphemeralHomeModuleBackend::~EphemeralHomeModuleBackend() = default;

std::unique_ptr<DefaultModelProvider::ModelConfig>
EphemeralHomeModuleBackend::GetModelConfig() {
  proto::SegmentationModelMetadata metadata;
  if (!home_modules_card_registry_) {
    return std::make_unique<ModelConfig>(std::move(metadata), kModelVersion);
  }
  MetadataWriter writer(&metadata);
  writer.SetDefaultSegmentationMetadataConfig(kMinSignalCollectionLength,
                                              kSignalStorageLength);

  // Set output config.
  const std::vector<std::string>& output_labels =
      home_modules_card_registry_->all_output_labels();
  // Use a threshold slightly greater than the kNotShown value since the
  // threshold checks for strictly less than value.
  float dont_show_threshold =
      EphemeralHomeModuleRankToScore(EphemeralHomeModuleRank::kNotShown) +
      0.001f;
  writer.AddOutputConfigForMultiClassClassifier(
      output_labels, kMaxOutputLabelsToRank, dont_show_threshold);
  writer.AddPredictedResultTTLInOutputConfig(
      /*top_label_to_ttl_list=*/{},
      /*default_ttl=*/kResultTTLDays, proto::TimeUnit::DAY);

  // Set features.
  const auto& all_cards =
      home_modules_card_registry_->get_all_cards_by_priority();
  for (const auto& card : all_cards) {
    const auto& inputs = card->GetInputs();
    for (const auto& key_and_input : inputs) {
      const FeatureQuery& input = key_and_input.second;
      if (input.uma_feature) {
        writer.AddUmaFeatures(&input.uma_feature.value(), 1);
      } else if (input.sql_feature) {
        writer.AddSqlFeature(*input.sql_feature);
      } else if (input.custom_input) {
        writer.AddCustomInput(*input.custom_input);
      }
    }
  }

  return std::make_unique<ModelConfig>(std::move(metadata), kModelVersion);
}

void EphemeralHomeModuleBackend::ExecuteModelWithInput(
    const ModelProvider::Request& inputs,
    ExecutionCallback callback) {
  if (!home_modules_card_registry_ ||
      inputs.size() != home_modules_card_registry_->all_cards_input_size()) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), std::nullopt));
    return;
  }
  const AllCardSignals all_signals(
      home_modules_card_registry_->get_card_signal_map(), std::move(inputs));

  const auto& all_cards =
      home_modules_card_registry_->get_all_cards_by_priority();
  const float dont_show_result =
      EphemeralHomeModuleRankToScore(EphemeralHomeModuleRank::kNotShown);
  ModelProvider::Request result(
      home_modules_card_registry_->all_output_labels().size(),
      dont_show_result);

  size_t position_types =
      static_cast<size_t>(EphemeralHomeModuleRank::kNotShown);
  base::flat_set<EphemeralHomeModuleRank> filled_positions = {
      EphemeralHomeModuleRank::kNotShown};
#if BUILDFLAG(IS_IOS)
  filled_positions.insert(EphemeralHomeModuleRank::kLast);
#endif  // BUILDFLAG(IS_IOS)

  for (const auto& card : all_cards) {
    CardSelectionSignals card_signals(&all_signals, card->card_name());
    CardSelectionInfo::ShowResult card_result =
        card->ComputeCardResult(card_signals);

    if (filled_positions.contains(card_result.position)) {
      continue;
    }
    std::string label = card->card_name();
    if (card_result.result_label) {
      label = *card_result.result_label;
    }
    result[home_modules_card_registry_->get_label_index(
        *card_result.result_label)] =
        EphemeralHomeModuleRankToScore(card_result.position);

    filled_positions.insert(card_result.position);

    // This assumes only one card per position type is shown.
    if (filled_positions.size() == position_types + 1) {
      break;
    }
  }

  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), std::move(result)));
}

// static
std::unique_ptr<Config> TestEphemeralHomeModuleBackend::GetConfig() {
  auto config = std::make_unique<Config>();
  config->segmentation_key = kEphemeralHomeModuleBackendKey;
  config->segmentation_uma_name = kEphemeralHomeModuleBackendUmaName;
  config->AddSegmentId(kTestSegmentId,
                       std::make_unique<TestEphemeralHomeModuleBackend>());
  config->auto_execute_and_cache = false;
  return config;
}

TestEphemeralHomeModuleBackend::TestEphemeralHomeModuleBackend()
    : DefaultModelProvider(kTestSegmentId) {}

std::unique_ptr<DefaultModelProvider::ModelConfig>
TestEphemeralHomeModuleBackend::GetModelConfig() {
  proto::SegmentationModelMetadata metadata;
  MetadataWriter writer(&metadata);
  writer.SetDefaultSegmentationMetadataConfig(kMinSignalCollectionLength,
                                              kSignalStorageLength);

  writer.AddOutputConfigForMultiClassClassifier(
      base::span_from_ref(+kPriceTrackingNotificationPromo),
      kMaxOutputLabelsToRank,
      EphemeralHomeModuleRankToScore(EphemeralHomeModuleRank::kNotShown));
  writer.AddPredictedResultTTLInOutputConfig(
      /*top_label_to_ttl_list=*/{},
      /*default_ttl=*/kResultTTLDays, proto::TimeUnit::DAY);

  writer.AddFromInputContext("is_new_user", segmentation_platform::kIsNewUser);
  writer.AddFromInputContext("is_synced", segmentation_platform::kIsSynced);

  return std::make_unique<ModelConfig>(std::move(metadata), kModelVersion);
}

void TestEphemeralHomeModuleBackend::ExecuteModelWithInput(
    const ModelProvider::Request& inputs,
    ExecutionCallback callback) {
  const float dont_show_result =
      EphemeralHomeModuleRankToScore(EphemeralHomeModuleRank::kNotShown);
  ModelProvider::Request response(1, dont_show_result);
  std::string card_type =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          kEphemeralModuleBackendRankerTestOverride);
  if (card_type == "price_tracking_notification_promo") {
    response[0] = 1;
  }

  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), response));
}

}  // namespace segmentation_platform::home_modules