File: segment_result_provider.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 (438 lines) | stat: -rw-r--r-- 19,909 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
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
// Copyright 2021 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/internal/selection/segment_result_provider.h"

#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/task/sequenced_task_runner.h"
#include "components/segmentation_platform/internal/database/segment_info_database.h"
#include "components/segmentation_platform/internal/database/signal_storage_config.h"
#include "components/segmentation_platform/internal/execution/execution_request.h"
#include "components/segmentation_platform/internal/logging.h"
#include "components/segmentation_platform/internal/metadata/metadata_utils.h"
#include "components/segmentation_platform/internal/proto/model_prediction.pb.h"
#include "components/segmentation_platform/internal/scheduler/execution_service.h"
#include "components/segmentation_platform/internal/stats.h"
#include "components/segmentation_platform/public/model_provider.h"
#include "components/segmentation_platform/public/proto/model_metadata.pb.h"

namespace segmentation_platform {
namespace {

float ComputeDiscreteMapping(const std::string& discrete_mapping_key,
                             float model_score,
                             const proto::SegmentationModelMetadata& metadata) {
  float rank = metadata_utils::ConvertToDiscreteScore(discrete_mapping_key,
                                                      model_score, metadata);
  VLOG(1) << __func__ << ": segment=" << discrete_mapping_key
          << ": result=" << model_score << ", rank=" << rank;

  return rank;
}

ModelProvider* GetModelProvider(ExecutionService* execution_service,
                                SegmentId segment_id,
                                ModelSource model_source) {
  return execution_service
             ? execution_service->GetModelProvider(segment_id, model_source)
             : nullptr;
}

class SegmentResultProviderImpl : public SegmentResultProvider {
 public:
  SegmentResultProviderImpl(SegmentInfoDatabase* segment_database,
                            SignalStorageConfig* signal_storage_config,
                            ExecutionService* execution_service,
                            base::Clock* clock,
                            bool force_refresh_results)
      : segment_database_(segment_database),
        signal_storage_config_(signal_storage_config),
        execution_service_(execution_service),
        clock_(clock),
        force_refresh_results_(force_refresh_results),
        task_runner_(base::SequencedTaskRunner::GetCurrentDefault()) {}

  void GetSegmentResult(std::unique_ptr<GetResultOptions> options) override;

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

 private:
  struct RequestState {
    std::unique_ptr<GetResultOptions> options;
  };

  // TODO (b/294267021) : Refactor this enum to give fallback source to execute.
  // `fallback_action` tells us whether to get score from database or execute
  // server or default model next.
  enum class FallbackAction {
    kGetResultFromDatabaseForServerModel = 0,
    kExecuteServerModel = 1,
    kGetResultFromDatabaseForDefaultModel = 2,
    kExecuteDefaultModel = 3,
  };

  void OnGotModelScore(FallbackAction fallback_action,
                       std::unique_ptr<RequestState> request_state,
                       std::unique_ptr<SegmentResult> db_result);

  using ResultCallbackWithState =
      base::OnceCallback<void(std::unique_ptr<RequestState>,
                              std::unique_ptr<SegmentResult>)>;

  void GetCachedModelScore(std::unique_ptr<RequestState> request_state,
                           ModelSource model_source,
                           ResultCallbackWithState callback);
  void ExecuteModelAndGetScore(std::unique_ptr<RequestState> request_state,
                               ModelSource model_source,
                               ResultCallbackWithState callback);

  void OnModelExecuted(std::unique_ptr<RequestState> request_state,
                       ModelSource model_source,
                       ResultCallbackWithState callback,
                       std::unique_ptr<ModelExecutionResult> result);

  void PostResultCallback(std::unique_ptr<RequestState> request_state,
                          std::unique_ptr<SegmentResult> result);

  void OnSavedSegmentResult(SegmentId segment_id,
                            std::unique_ptr<RequestState> request_state,
                            std::unique_ptr<SegmentResult> segment_result,
                            ResultCallbackWithState callback,
                            bool success);

  const raw_ptr<SegmentInfoDatabase> segment_database_;
  const raw_ptr<SignalStorageConfig> signal_storage_config_;
  const raw_ptr<ExecutionService> execution_service_;
  const raw_ptr<base::Clock> clock_;
  const bool force_refresh_results_;
  scoped_refptr<base::SequencedTaskRunner> task_runner_;

  base::WeakPtrFactory<SegmentResultProviderImpl> weak_ptr_factory_{this};
};

void SegmentResultProviderImpl::GetSegmentResult(
    std::unique_ptr<GetResultOptions> options) {
  auto request_state = std::make_unique<RequestState>();
  request_state->options = std::move(options);
  // If `ignore_db_scores` is true than the server model will be executed now,
  // if that fails to give result, fallback to default model, hence default
  // model is the `fallback_action` if `ignore_db_score` is true. If
  // `ignore_db_scores` is false than the score from database would be read, if
  // that fails to read score from database, fallback to running server model,
  // hence running server model is the `fallback_action` if
  // `ignore_db_score` is false.
  FallbackAction fallback_action = request_state->options->ignore_db_scores
                                       ? FallbackAction::kExecuteDefaultModel
                                       : FallbackAction::kExecuteServerModel;
  auto db_score_callback =
      base::BindOnce(&SegmentResultProviderImpl::OnGotModelScore,
                     weak_ptr_factory_.GetWeakPtr(), fallback_action);

  if (request_state->options->ignore_db_scores) {
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << " ignoring DB score, executing model.";
    ExecuteModelAndGetScore(std::move(request_state),
                            ModelSource::SERVER_MODEL_SOURCE,
                            std::move(db_score_callback));
    return;
  }

  GetCachedModelScore(std::move(request_state),
                      ModelSource::SERVER_MODEL_SOURCE,
                      std::move(db_score_callback));
}

void SegmentResultProviderImpl::OnGotModelScore(
    FallbackAction fallback_action,
    std::unique_ptr<RequestState> request_state,
    std::unique_ptr<SegmentResult> db_result) {
  if (db_result && db_result->rank.has_value()) {
    PostResultCallback(std::move(request_state), std::move(db_result));
    return;
  }

  // If previously the `fallback_action` was server model, that means
  // that the server model will be running this time, and if that fails to
  // provide the result, the fallback to this would be eithier getting score for
  // default model from database or executing default models based on
  // `ignore_db_scores`.
  if (fallback_action == FallbackAction::kExecuteServerModel) {
    FallbackAction new_fallback_action =
        request_state->options->ignore_db_scores
            ? FallbackAction::kExecuteDefaultModel
            : FallbackAction::kGetResultFromDatabaseForDefaultModel;
    auto db_score_callback =
        base::BindOnce(&SegmentResultProviderImpl::OnGotModelScore,
                       weak_ptr_factory_.GetWeakPtr(), new_fallback_action);
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << " failed to get score from database, executing server model.";
    ExecuteModelAndGetScore(std::move(request_state),
                            ModelSource::SERVER_MODEL_SOURCE,
                            std::move(db_score_callback));
    return;
  }

  // Handling default models.
  ModelProvider* default_model =
      GetModelProvider(execution_service_, request_state->options->segment_id,
                       ModelSource::DEFAULT_MODEL_SOURCE);
  if (!default_model || !default_model->ModelAvailable()) {
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << " default provider not available";
    // Make sure the metrics record state of database model failure when client
    // did not provide a default model.
    PostResultCallback(std::move(request_state),
                       std::make_unique<SegmentResult>(db_result->state));
    return;
  }

  if (fallback_action ==
      FallbackAction::kGetResultFromDatabaseForDefaultModel) {
    auto db_score_callback = base::BindOnce(
        &SegmentResultProviderImpl::OnGotModelScore,
        weak_ptr_factory_.GetWeakPtr(), FallbackAction::kExecuteDefaultModel);
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << " failed to get score from executing server model, getting "
               "score from default model from db.";
    GetCachedModelScore(std::move(request_state),
                        ModelSource::DEFAULT_MODEL_SOURCE,
                        std::move(db_score_callback));
    return;
  }
  VLOG(1) << __func__
          << ": segment=" << SegmentId_Name(request_state->options->segment_id)
          << " failed to get database model score, trying default model.";
  ExecuteModelAndGetScore(
      std::move(request_state), ModelSource::DEFAULT_MODEL_SOURCE,
      base::BindOnce(&SegmentResultProviderImpl::PostResultCallback,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SegmentResultProviderImpl::GetCachedModelScore(
    std::unique_ptr<RequestState> request_state,
    ModelSource model_source,
    ResultCallbackWithState callback) {
  const auto* db_segment_info = segment_database_->GetCachedSegmentInfo(
      request_state->options->segment_id, model_source);
  if (!db_segment_info) {
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << " does not have a segment info.";
    std::move(callback).Run(
        std::move(request_state),
        std::make_unique<SegmentResult>(
            model_source == ModelSource::DEFAULT_MODEL_SOURCE
                ? ResultState::kDefaultModelSegmentInfoNotAvailable
                : ResultState::kServerModelSegmentInfoNotAvailable));
    return;
  }

  if (force_refresh_results_ || metadata_utils::HasExpiredOrUnavailableResult(
                                    *db_segment_info, clock_->Now())) {
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << " has expired or unavailable result.";
    std::move(callback).Run(
        std::move(request_state),
        std::make_unique<SegmentResult>(
            model_source == ModelSource::DEFAULT_MODEL_SOURCE
                ? ResultState::kDefaultModelDatabaseScoreNotReady
                : ResultState::kServerModelDatabaseScoreNotReady));
    return;
  }

  VLOG(1) << __func__ << ": Retrieved prediction from database: "
          << segmentation_platform::PredictionResultToDebugString(
                 db_segment_info->prediction_result())
          << " for segment "
          << proto::SegmentId_Name(request_state->options->segment_id);

  float rank =
      ComputeDiscreteMapping(request_state->options->discrete_mapping_key,
                             db_segment_info->prediction_result().result()[0],
                             db_segment_info->model_metadata());
  std::move(callback).Run(std::move(request_state),
                          std::make_unique<SegmentResult>(
                              model_source == ModelSource::DEFAULT_MODEL_SOURCE
                                  ? ResultState::kDefaultModelDatabaseScoreUsed
                                  : ResultState::kServerModelDatabaseScoreUsed,
                              db_segment_info->prediction_result(), rank));
}

void SegmentResultProviderImpl::ExecuteModelAndGetScore(
    std::unique_ptr<RequestState> request_state,
    ModelSource model_source,
    ResultCallbackWithState callback) {
  const auto* segment_info = segment_database_->GetCachedSegmentInfo(
      request_state->options->segment_id, model_source);
  if (!segment_info) {
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << (model_source == ModelSource::SERVER_MODEL_SOURCE ? " server"
                                                                 : " default")
            << " segment info not available";
    auto state = model_source == ModelSource::SERVER_MODEL_SOURCE
                     ? ResultState::kServerModelSegmentInfoNotAvailable
                     : ResultState::kDefaultModelSegmentInfoNotAvailable;
    std::move(callback).Run(std::move(request_state),
                            std::make_unique<SegmentResult>(state));
    return;
  }

  DCHECK_EQ(metadata_utils::ValidationResult::kValidationSuccess,
            metadata_utils::ValidateMetadata(segment_info->model_metadata()));
  if (!force_refresh_results_ &&
      !signal_storage_config_->MeetsSignalCollectionRequirement(
          segment_info->model_metadata())) {
    VLOG(1) << __func__ << ": segment="
            << SegmentId_Name(request_state->options->segment_id)
            << " signal collection not met";
    auto state = model_source == ModelSource::SERVER_MODEL_SOURCE
                     ? ResultState::kServerModelSignalsNotCollected
                     : ResultState::kDefaultModelSignalsNotCollected;
    std::move(callback).Run(std::move(request_state),
                            std::make_unique<SegmentResult>(state));
    return;
  }

  ModelProvider* provider = GetModelProvider(
      execution_service_, request_state->options->segment_id, model_source);

  auto request = std::make_unique<ExecutionRequest>();
  request->input_context = request_state->options->input_context;
  request->segment_id = segment_info->segment_id();
  request->model_source = model_source;

  request->callback =
      base::BindOnce(&SegmentResultProviderImpl::OnModelExecuted,
                     weak_ptr_factory_.GetWeakPtr(), std::move(request_state),
                     model_source, std::move(callback));
  request->model_provider = provider;

  execution_service_->RequestModelExecution(std::move(request));
}

void SegmentResultProviderImpl::OnModelExecuted(
    std::unique_ptr<RequestState> request_state,
    ModelSource model_source,
    ResultCallbackWithState callback,
    std::unique_ptr<ModelExecutionResult> result) {
  SegmentId segment_id = request_state->options->segment_id;
  ResultState state = ResultState::kUnknown;
  proto::PredictionResult prediction_result;

  const auto* segment_info =
      segment_database_->GetCachedSegmentInfo(segment_id, model_source);
  if (!segment_info) {
    state = model_source == ModelSource::SERVER_MODEL_SOURCE
                 ? ResultState::kServerModelSegmentInfoNotAvailable
                 : ResultState::kDefaultModelSegmentInfoNotAvailable;
    std::move(callback).Run(std::move(request_state),
                            std::make_unique<SegmentResult>(state));
    return;
  }

  bool is_default_model = model_source == ModelSource::DEFAULT_MODEL_SOURCE;
  bool success = result->status == ModelExecutionStatus::kSuccess &&
                 !result->scores.empty();
  std::unique_ptr<SegmentResult> segment_result;
  if (success) {
    state = is_default_model ? ResultState::kDefaultModelExecutionScoreUsed
                             : ResultState::kServerModelExecutionScoreUsed;
    prediction_result = metadata_utils::CreatePredictionResult(
        result->scores, segment_info->model_metadata().output_config(),
        clock_->Now(), segment_info->model_version());
    float rank = ComputeDiscreteMapping(
        request_state->options->discrete_mapping_key,
        prediction_result.result(0), segment_info->model_metadata());
    segment_result =
        std::make_unique<SegmentResult>(state, prediction_result, rank);
    segment_result->model_inputs = std::move(result->inputs);
    VLOG(1) << __func__ << ": " << (is_default_model ? "Default" : "Server")
            << " model executed successfully. Result: "
            << segmentation_platform::PredictionResultToDebugString(
                   prediction_result)
            << " for segment " << proto::SegmentId_Name(segment_id);
  } else {
    state = is_default_model ? ResultState::kDefaultModelExecutionFailed
                             : ResultState::kServerModelExecutionFailed;
    segment_result = std::make_unique<SegmentResult>(state);
    VLOG(1) << __func__ << ": " << (is_default_model ? "Default" : "Server")
            << " model execution failed" << " for segment "
            << proto::SegmentId_Name(segment_id);
  }

  if (request_state->options->save_results_to_db) {
    segment_database_->SaveSegmentResult(
        segment_id, model_source,
        success ? std::make_optional(prediction_result) : std::nullopt,
        base::BindOnce(&SegmentResultProviderImpl::OnSavedSegmentResult,
                       weak_ptr_factory_.GetWeakPtr(),
                       segment_info->segment_id(), std::move(request_state),
                       std::move(segment_result), std::move(callback)));
    return;
  }
  std::move(callback).Run(std::move(request_state), std::move(segment_result));
}

void SegmentResultProviderImpl::PostResultCallback(
    std::unique_ptr<RequestState> request_state,
    std::unique_ptr<SegmentResult> result) {
  task_runner_->PostTask(
      FROM_HERE, base::BindOnce(std::move(request_state->options->callback),
                                std::move(result)));
}

void SegmentResultProviderImpl::OnSavedSegmentResult(
    SegmentId segment_id,
    std::unique_ptr<RequestState> request_state,
    std::unique_ptr<SegmentResult> segment_result,
    ResultCallbackWithState callback,
    bool success) {
  stats::RecordModelExecutionSaveResult(segment_id, success);
  if (!success) {
    // TODO(ssid): Consider removing this enum, this is the only case where the
    // execution status is recorded twice for the same execution request.
    stats::RecordModelExecutionStatus(
        segment_id,
        /*default_provider=*/false,
        ModelExecutionStatus::kFailedToSaveResultAfterSuccess);
  }
  std::move(callback).Run(std::move(request_state), std::move(segment_result));
}

}  // namespace

SegmentResultProvider::SegmentResult::SegmentResult(ResultState state)
    : state(state) {}
SegmentResultProvider::SegmentResult::SegmentResult(
    ResultState state,
    const proto::PredictionResult& prediction_result,
    float rank)
    : state(state), result(prediction_result), rank(rank) {}
SegmentResultProvider::SegmentResult::~SegmentResult() = default;

SegmentResultProvider::GetResultOptions::GetResultOptions() = default;
SegmentResultProvider::GetResultOptions::~GetResultOptions() = default;

// static
std::unique_ptr<SegmentResultProvider> SegmentResultProvider::Create(
    SegmentInfoDatabase* segment_database,
    SignalStorageConfig* signal_storage_config,
    ExecutionService* execution_service,
    base::Clock* clock,
    bool force_refresh_results) {
  return std::make_unique<SegmentResultProviderImpl>(
      segment_database, signal_storage_config, execution_service, clock,
      force_refresh_results);
}

}  // namespace segmentation_platform