File: permissions_aiv3_handler.cc

package info (click to toggle)
chromium 141.0.7390.107-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,246,132 kB
  • sloc: cpp: 35,264,965; ansic: 7,169,920; javascript: 4,250,185; python: 1,460,635; asm: 950,788; xml: 751,751; pascal: 187,972; sh: 89,459; perl: 88,691; objc: 79,953; sql: 53,924; cs: 44,622; fortran: 24,137; makefile: 22,313; tcl: 15,277; php: 14,018; yacc: 8,995; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (159 lines) | stat: -rw-r--r-- 6,906 bytes parent folder | download | duplicates (4)
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
// 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/permissions/prediction_service/permissions_aiv3_handler.h"

#include <memory>

#include "base/feature_list.h"
#include "components/optimization_guide/core/delivery/optimization_guide_model_provider.h"
#include "components/permissions/features.h"
#include "components/permissions/prediction_service/permissions_aiv3_executor.h"
#include "components/version_info/version_info.h"

namespace permissions {

namespace {
using ModelInput = PermissionsAiv3Executor::ModelInput;
using ModelOutput = PermissionsAiv3Executor::ModelOutput;

// This is the timeout for the model execution. If the model execution takes
// longer than this timeout, the callback will be called with a nullopt result.
constexpr auto kModelExecutionTimeoutSeconds =
    base::Seconds(PermissionsAiv3Handler::kModelExecutionTimeout);
}  // namespace

PermissionsAiv3Handler::PermissionsAiv3Handler(
    optimization_guide::OptimizationGuideModelProvider* model_provider,
    optimization_guide::proto::OptimizationTarget optimization_target,
    RequestType request_type,
    std::unique_ptr<PermissionsAiv3Executor> model_executor,
    scoped_refptr<base::SequencedTaskRunner> model_executor_task_runner,
    scoped_refptr<base::SequencedTaskRunner> reply_task_runner)
    : ModelHandler<ModelOutput, const ModelInput&>(
          model_provider,
          model_executor_task_runner,
          std::move(model_executor),
          /*model_inference_timeout=*/std::nullopt,
          optimization_target,
          /*model_metadata=*/std::nullopt,
          reply_task_runner) {}

PermissionsAiv3Handler::PermissionsAiv3Handler(
    optimization_guide::OptimizationGuideModelProvider* model_provider,
    optimization_guide::proto::OptimizationTarget optimization_target,
    RequestType request_type)
    : PermissionsAiv3Handler(
          model_provider,
          optimization_target,
          request_type,
          /*model_executor=*/
          std::make_unique<PermissionsAiv3Executor>(request_type)) {}

PermissionsAiv3Handler::~PermissionsAiv3Handler() = default;

void PermissionsAiv3Handler::OnModelUpdated(
    optimization_guide::proto::OptimizationTarget optimization_target,
    base::optional_ref<const optimization_guide::ModelInfo> model_info) {
  // First invoke parent to update internal status.
  optimization_guide::ModelHandler<
      ModelOutput, const ModelInput&>::OnModelUpdated(optimization_target,
                                                      model_info);
  if (model_info.has_value()) {
    // The parent class should always set the model availability to true after
    // having received an updated model.
    DCHECK(ModelAvailable());
    model_metadata_ =
        ParsedSupportedFeaturesForLoadedModel<PermissionsAiv3ModelMetadata>();
  }
}

void PermissionsAiv3Handler::ExecuteModel(ExecutionCallback callback,
                                          ModelInput model_input) {
  DCHECK(!model_input.snapshot.drawsNothing());
  VLOG(1) << "PermissionsAiv3Handler::ExecuteModel";
  base::UmaHistogramBoolean("Permissions.AIv3.ModelExecutionAlreadyInProgress",
                            is_execution_in_progress_);
  // If an execution is already in progress, there is no way to cancel it and
  // we cannot wait until it is done because this will add extra latency, so
  // we will return an empty response to the callback.
  if (is_execution_in_progress_) {
    VLOG(1) << "[PermissionsAIv3] ExecuteModel: Execution already in "
               "progress. Returning empty response.";
    // The callback is no longer valid because a new execution was requested
    // while the previous one was still in progress.
    is_callback_valid_ = false;
    std::move(callback).Run(std::nullopt);
    return;
  } else {
    VLOG(1) << "[PermissionsAIv3] ExecuteModel: Execution not in "
               "progress. Starting execution.";
  }
  is_execution_in_progress_ = true;
  is_callback_valid_ = true;

  model_input.metadata = model_metadata_;

  current_callback_ = std::move(callback);
  ExecutionCallback on_complete_callback =
      base::BindOnce(&PermissionsAiv3Handler::OnModelExecutionComplete,
                     weak_factory_.GetWeakPtr());

  ExecuteModelWithInput(std::move(on_complete_callback), model_input);

  // In parallel with the model execution, we will start a timer that will
  // call `OnModelExecutionTimeout` with a nullopt result if the model
  // execution takes longer than the timeout.
  timeout_timer_.Start(
      FROM_HERE, kModelExecutionTimeoutSeconds,
      base::BindOnce(&PermissionsAiv3Handler::OnModelExecutionTimeout,
                     weak_factory_.GetWeakPtr(), std::nullopt));
}

void PermissionsAiv3Handler::OnModelExecutionTimeout(
    const std::optional<PermissionRequestRelevance>& relevance) {
  VLOG(1) << "[PermissionsAIv3] OnModelExecutionTimeout: Model execution took "
             "longer than the timeout. Returning empty response.";
  base::UmaHistogramBoolean("Permissions.AIv3.ModelExecutionTimeout", true);
  std::move(current_callback_).Run(std::nullopt);
}

void PermissionsAiv3Handler::OnModelExecutionComplete(
    const std::optional<PermissionRequestRelevance>& relevance) {
  VLOG(1) << "[PermissionsAIv3] OnModelExecutionComplete: Model execution "
             "completed. Returning relevance: "
          << (relevance.has_value() ? static_cast<int>(relevance.value()) : -1);
  timeout_timer_.Stop();
  is_execution_in_progress_ = false;

  if (!current_callback_) {
    VLOG(1) << "[PermissionsAIv3] OnModelExecutionComplete: Callback was "
               "replaced. Ignoring the result.";
    // The callback was executed in `OnModelExecutionTimeout` before the model
    // execution completed.
    // The timeout logic does not reset
    // `is_execution_in_progress_` flag, so in the case of a new request we will
    // not save a new callback to avoid delivering a stale model execution
    // result to a new permission prompt.
    return;
  }

  if (is_callback_valid_) {
    VLOG(1) << "[PermissionsAIv3] OnModelExecutionComplete: Callback is "
               "valid. Delivering relevance: "
            << (relevance.has_value() ? static_cast<int>(relevance.value())
                                      : -1);
    std::move(current_callback_).Run(relevance);
  } else {
    VLOG(1) << "[PermissionsAIv3] OnModelExecutionComplete: Callback is no "
               "longer valid. Ignoring the result.";
    // The callback is no longer valid because a new execution was requested
    // while the previous one was still in progress. We will return an empty
    // response to the callback because there is no UI to which the relevance
    // can be applied.
    std::move(current_callback_).Run(std::nullopt);
  }
}

}  // namespace permissions