Coverage Report

Created: 2026-08-07 05:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_meta_mgr.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
#include "cloud/cloud_meta_mgr.h"
18
19
#include <brpc/channel.h>
20
#include <brpc/controller.h>
21
#include <brpc/errno.pb.h>
22
#include <bthread/bthread.h>
23
#include <bthread/condition_variable.h>
24
#include <bthread/mutex.h>
25
#include <gen_cpp/FrontendService.h>
26
#include <gen_cpp/HeartbeatService_types.h>
27
#include <gen_cpp/PlanNodes_types.h>
28
#include <gen_cpp/Types_types.h>
29
#include <gen_cpp/cloud.pb.h>
30
#include <gen_cpp/olap_file.pb.h>
31
#include <glog/logging.h>
32
33
#include <algorithm>
34
#include <atomic>
35
#include <chrono>
36
#include <cstdint>
37
#include <memory>
38
#include <mutex>
39
#include <random>
40
#include <shared_mutex>
41
#include <string>
42
#include <type_traits>
43
#include <vector>
44
45
#include "cloud/cloud_ms_backpressure_handler.h"
46
#include "cloud/cloud_ms_rpc_rate_limiters.h"
47
#include "cloud/cloud_storage_engine.h"
48
#include "cloud/cloud_tablet.h"
49
#include "cloud/cloud_warm_up_manager.h"
50
#include "cloud/config.h"
51
#include "cloud/delete_bitmap_file_reader.h"
52
#include "cloud/delete_bitmap_file_writer.h"
53
#include "cloud/pb_convert.h"
54
#include "common/config.h"
55
#include "common/logging.h"
56
#include "common/status.h"
57
#include "cpp/sync_point.h"
58
#include "io/fs/obj_storage_client.h"
59
#include "load/stream_load/stream_load_context.h"
60
#include "runtime/cluster_info.h"
61
#include "runtime/exec_env.h"
62
#include "service/backend_options.h"
63
#include "storage/olap_common.h"
64
#include "storage/rowset/rowset.h"
65
#include "storage/rowset/rowset_factory.h"
66
#include "storage/rowset/rowset_fwd.h"
67
#include "storage/storage_engine.h"
68
#include "storage/tablet/tablet_meta.h"
69
#include "util/client_cache.h"
70
#include "util/client_connection_provider.h"
71
#include "util/network_util.h"
72
#include "util/s3_util.h"
73
#include "util/thrift_rpc_helper.h"
74
75
namespace doris::cloud {
76
using namespace ErrorCode;
77
78
1.47M
void* run_bthread_work(void* arg) {
79
1.47M
    auto* f = reinterpret_cast<std::function<void()>*>(arg);
80
1.47M
    (*f)();
81
1.47M
    delete f;
82
1.47M
    return nullptr;
83
1.47M
}
84
85
292k
Status bthread_fork_join(const std::vector<std::function<Status()>>& tasks, int concurrency) {
86
292k
    if (tasks.empty()) {
87
4.61k
        return Status::OK();
88
4.61k
    }
89
90
288k
    bthread::Mutex lock;
91
288k
    bthread::ConditionVariable cond;
92
288k
    Status status; // Guard by lock
93
288k
    int count = 0; // Guard by lock
94
95
1.24M
    for (const auto& task : tasks) {
96
1.24M
        {
97
1.24M
            std::unique_lock lk(lock);
98
            // Wait until there are available slots
99
1.30M
            while (status.ok() && count >= concurrency) {
100
54.0k
                cond.wait(lk);
101
54.0k
            }
102
1.24M
            if (!status.ok()) {
103
2
                break;
104
2
            }
105
106
            // Increase running task count
107
1.24M
            ++count;
108
1.24M
        }
109
110
        // dispatch task into bthreads
111
1.23M
        auto* fn = new std::function<void()>([&, &task = task] {
112
1.23M
            auto st = task();
113
1.23M
            {
114
1.23M
                std::lock_guard lk(lock);
115
1.23M
                --count;
116
1.23M
                if (!st.ok()) {
117
4
                    std::swap(st, status);
118
4
                }
119
1.23M
                cond.notify_one();
120
1.23M
            }
121
1.23M
        });
122
123
1.24M
        bthread_t bthread_id;
124
1.24M
        if (bthread_start_background(&bthread_id, nullptr, run_bthread_work, fn) != 0) {
125
0
            run_bthread_work(fn);
126
0
        }
127
1.24M
    }
128
129
    // Wait until all running tasks have done
130
288k
    {
131
288k
        std::unique_lock lk(lock);
132
888k
        while (count > 0) {
133
600k
            cond.wait(lk);
134
600k
        }
135
288k
    }
136
137
288k
    return status;
138
292k
}
139
140
Status bthread_fork_join(std::vector<std::function<Status()>>&& tasks, int concurrency,
141
229k
                         std::future<Status>* fut) {
142
    // std::function will cause `copy`, we need to use heap memory to avoid copy ctor called
143
229k
    auto prom = std::make_shared<std::promise<Status>>();
144
229k
    *fut = prom->get_future();
145
229k
    std::function<void()>* fn = new std::function<void()>(
146
231k
            [tasks = std::move(tasks), concurrency, p = std::move(prom)]() mutable {
147
231k
                p->set_value(bthread_fork_join(tasks, concurrency));
148
231k
            });
149
150
229k
    bthread_t bthread_id;
151
229k
    if (bthread_start_background(&bthread_id, nullptr, run_bthread_work, fn) != 0) {
152
0
        delete fn;
153
0
        return Status::InternalError<false>("failed to create bthread");
154
0
    }
155
229k
    return Status::OK();
156
229k
}
157
158
// Resolve the status code returned by Meta Service (MS) for BE/FE clients of different version.
159
// Assuming MS is always the latest version, it sends both the meta-service error code and a code that
160
// older clients can decode:
161
//
162
//                              latest MS
163
//                 +---------------------------------------+
164
//                 | actual_code = meta-service error code |
165
//                 | code        = compatible code         |
166
//                 +----------------+----------------------+
167
//                                  |
168
//                    +-------------+-------------+
169
//                    |                           |
170
//           old BE/FE without              old BE/FE with
171
//          the actual_code field         the actual_code field
172
//                    |                           |
173
//          ignores actual_code            local enum recognizes
174
//          and reads code                 actual_code value?
175
//                                         yes                  no
176
//                                         |                     |
177
//                                  use actual code      use code only when it
178
//                                                       is explicit and non-OK
179
//                                                                 |
180
//                                                          otherwise return
181
//                                                           UNDEFINED_ERR
182
//
183
// After MS adds an error code, an older actual_code-aware client may not have that enum value;
184
// MetaServiceCode_IsValid detects this case. The non-OK fallback check is essential:
185
// if MS ignore or incorrectly converts the compatible code to OK, an unknown error
186
// must remain an error instead of becoming a false success.
187
742k
MetaServiceCode get_response_code(const MetaServiceResponseStatus& status) {
188
743k
    if (status.has_actual_code()) {
189
        // Check whether this client build contains the code in its MetaServiceCode enum.
190
744k
        if (MetaServiceCode_IsValid(status.actual_code())) {
191
744k
            return static_cast<MetaServiceCode>(status.actual_code());
192
744k
        }
193
        // An older client may use the compatible code, but unsupported cases must return an explicit error.
194
        // Return the non-OK compatible code prepared by MS for older clients.
195
18.4E
        if (status.has_code() && status.code() != MetaServiceCode::OK) {
196
1
            return status.code();
197
1
        }
198
        // Never return OK when the compatible code is absent or invalid.
199
18.4E
        return MetaServiceCode::UNDEFINED_ERR;
200
18.4E
    }
201
    // A legacy response has only code, so return its explicit value, including a real OK.
202
18.4E
    if (status.has_code()) {
203
2
        return status.code();
204
2
    }
205
    // A response missing both fields is invalid and must be rejected.
206
18.4E
    return MetaServiceCode::UNDEFINED_ERR;
207
18.4E
}
208
209
namespace {
210
constexpr int kBrpcRetryTimes = 3;
211
212
743k
void restore_actual_code(MetaServiceResponseStatus* status) {
213
743k
    status->set_code(get_response_code(*status));
214
743k
}
215
216
bvar::LatencyRecorder _get_rowset_latency("doris_cloud_meta_mgr_get_rowset");
217
bvar::LatencyRecorder g_cloud_commit_txn_resp_redirect_latency("cloud_table_stats_report_latency");
218
bvar::Adder<uint64_t> g_cloud_meta_mgr_rpc_timeout_count("cloud_meta_mgr_rpc_timeout_count");
219
bvar::Window<bvar::Adder<uint64_t>> g_cloud_ms_rpc_timeout_count_window(
220
        "cloud_meta_mgr_rpc_timeout_qps", &g_cloud_meta_mgr_rpc_timeout_count, 30);
221
bvar::Adder<uint64_t> g_cloud_meta_mgr_ms_too_busy_reason_total_count(
222
        "cloud_meta_mgr_ms_too_busy_reason", "total");
223
bvar::Adder<uint64_t> g_cloud_meta_mgr_ms_too_busy_reason_fdb_cluster_count(
224
        "cloud_meta_mgr_ms_too_busy_reason", "fdb_cluster");
225
bvar::Adder<uint64_t> g_cloud_meta_mgr_ms_too_busy_reason_fdb_client_thread_count(
226
        "cloud_meta_mgr_ms_too_busy_reason", "fdb_client_thread");
227
bvar::Adder<uint64_t> g_cloud_meta_mgr_ms_too_busy_reason_ms_resource_count(
228
        "cloud_meta_mgr_ms_too_busy_reason", "ms_resource");
229
bvar::Adder<uint64_t> g_cloud_meta_mgr_ms_too_busy_reason_test_injection_count(
230
        "cloud_meta_mgr_ms_too_busy_reason", "test_injection");
231
bvar::Adder<uint64_t> g_cloud_meta_mgr_ms_too_busy_reason_no_stress_condition_matched_count(
232
        "cloud_meta_mgr_ms_too_busy_reason", "no_stress_condition_matched");
233
bvar::LatencyRecorder g_cloud_be_mow_get_dbm_lock_backoff_sleep_time(
234
        "cloud_be_mow_get_dbm_lock_backoff_sleep_time");
235
bvar::Adder<uint64_t> g_cloud_version_hole_filled_count("cloud_version_hole_filled_count");
236
237
class MetaServiceProxy {
238
public:
239
736k
    static Status get_proxy(MetaServiceProxy** proxy) {
240
        // The 'stub' is a useless parameter, added only to reuse the `get_pooled_client` function.
241
736k
        std::shared_ptr<MetaService_Stub> stub;
242
736k
        return get_pooled_client(&stub, proxy);
243
736k
    }
244
245
0
    void set_unhealthy() {
246
0
        std::unique_lock lock(_mutex);
247
0
        maybe_unhealthy = true;
248
0
    }
249
250
1.48M
    bool need_reconn(long now) {
251
1.48M
        return maybe_unhealthy && ((now - last_reconn_time_ms.front()) >
252
0
                                   config::meta_service_rpc_reconnect_interval_ms);
253
1.48M
    }
254
255
1.47M
    Status get(std::shared_ptr<MetaService_Stub>* stub) {
256
1.47M
        using namespace std::chrono;
257
258
1.47M
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
259
1.47M
        {
260
1.47M
            std::shared_lock lock(_mutex);
261
1.48M
            if (_deadline_ms >= now && !is_idle_timeout(now) && !need_reconn(now)) {
262
1.48M
                _last_access_at_ms.store(now, std::memory_order_relaxed);
263
1.48M
                *stub = _stub;
264
1.48M
                return Status::OK();
265
1.48M
            }
266
1.47M
        }
267
268
18.4E
        auto channel = std::make_unique<brpc::Channel>();
269
18.4E
        Status s = init_channel(channel.get());
270
18.4E
        if (!s.ok()) [[unlikely]] {
271
0
            return s;
272
0
        }
273
274
18.4E
        *stub = std::make_shared<MetaService_Stub>(channel.release(),
275
18.4E
                                                   google::protobuf::Service::STUB_OWNS_CHANNEL);
276
277
18.4E
        long deadline = now;
278
        // connection age only works without list endpoint.
279
18.4E
        if (config::meta_service_connection_age_base_seconds > 0) {
280
1.21k
            std::default_random_engine rng(static_cast<uint32_t>(now));
281
1.21k
            std::uniform_int_distribution<> uni(
282
1.21k
                    config::meta_service_connection_age_base_seconds,
283
1.21k
                    config::meta_service_connection_age_base_seconds * 2);
284
1.21k
            deadline = now + duration_cast<milliseconds>(seconds(uni(rng))).count();
285
1.21k
        }
286
287
        // Last one WIN
288
18.4E
        std::unique_lock lock(_mutex);
289
18.4E
        _last_access_at_ms.store(now, std::memory_order_relaxed);
290
18.4E
        _deadline_ms = deadline;
291
18.4E
        _stub = *stub;
292
293
18.4E
        last_reconn_time_ms.push(now);
294
18.4E
        last_reconn_time_ms.pop();
295
18.4E
        maybe_unhealthy = false;
296
297
18.4E
        return Status::OK();
298
18.4E
    }
299
300
private:
301
1.48M
    static bool is_meta_service_endpoint_list() {
302
1.48M
        return config::meta_service_endpoint.find(',') != std::string::npos;
303
1.48M
    }
304
305
    /**
306
    * This function initializes a pool of `MetaServiceProxy` objects and selects one using
307
    * round-robin. It returns a client stub via the selected proxy.
308
    *
309
    * @param stub A pointer to a shared pointer of `MetaService_Stub` to be retrieved.
310
    * @param proxy (Optional) A pointer to store the selected `MetaServiceProxy`.
311
    *
312
    * @return Status Returns `Status::OK()` on success or an error status on failure.
313
    */
314
    static Status get_pooled_client(std::shared_ptr<MetaService_Stub>* stub,
315
741k
                                    MetaServiceProxy** proxy) {
316
741k
        static std::once_flag proxies_flag;
317
741k
        static size_t num_proxies = 1;
318
741k
        static std::atomic<size_t> index(0);
319
741k
        static std::unique_ptr<MetaServiceProxy[]> proxies;
320
741k
        if (config::meta_service_endpoint.empty()) {
321
21
            return Status::InvalidArgument(
322
21
                    "Meta service endpoint is empty. Please configure manually or wait for "
323
21
                    "heartbeat to obtain.");
324
21
        }
325
741k
        std::call_once(
326
741k
                proxies_flag, +[]() {
327
1
                    if (config::meta_service_connection_pooled) {
328
1
                        num_proxies = config::meta_service_connection_pool_size;
329
1
                    }
330
1
                    proxies = std::make_unique<MetaServiceProxy[]>(num_proxies);
331
1
                });
332
333
743k
        for (size_t i = 0; i + 1 < num_proxies; ++i) {
334
741k
            size_t next_index = index.fetch_add(1, std::memory_order_relaxed) % num_proxies;
335
741k
            Status s = proxies[next_index].get(stub);
336
743k
            if (proxy != nullptr) {
337
743k
                *proxy = &(proxies[next_index]);
338
743k
            }
339
741k
            if (s.ok()) return Status::OK();
340
741k
        }
341
342
1.83k
        size_t next_index = index.fetch_add(1, std::memory_order_relaxed) % num_proxies;
343
1.83k
        if (proxy != nullptr) {
344
0
            *proxy = &(proxies[next_index]);
345
0
        }
346
1.83k
        return proxies[next_index].get(stub);
347
741k
    }
348
349
1.21k
    static Status init_channel(brpc::Channel* channel) {
350
1.21k
        static std::atomic<size_t> index = 1;
351
352
1.21k
        const char* load_balancer_name = nullptr;
353
1.21k
        std::string endpoint;
354
1.21k
        if (is_meta_service_endpoint_list()) {
355
0
            endpoint = fmt::format("list://{}", config::meta_service_endpoint);
356
0
            load_balancer_name = "random";
357
1.21k
        } else {
358
1.21k
            std::string ip;
359
1.21k
            uint16_t port;
360
1.21k
            Status s = get_meta_service_ip_and_port(&ip, &port);
361
1.21k
            if (!s.ok()) {
362
0
                LOG(WARNING) << "fail to get meta service ip and port: " << s;
363
0
                return s;
364
0
            }
365
366
1.21k
            endpoint = get_host_port(ip, port);
367
1.21k
        }
368
369
1.21k
        brpc::ChannelOptions options;
370
1.21k
        RETURN_IF_ERROR(doris::client::configure_brpc_channel_options(&options));
371
1.21k
        options.connection_group =
372
1.21k
                fmt::format("ms_{}", index.fetch_add(1, std::memory_order_relaxed));
373
1.21k
        if (channel->Init(endpoint.c_str(), load_balancer_name, &options) != 0) {
374
0
            return Status::InvalidArgument("failed to init brpc channel, endpoint: {}", endpoint);
375
0
        }
376
1.21k
        return Status::OK();
377
1.21k
    }
378
379
1.20k
    static Status get_meta_service_ip_and_port(std::string* ip, uint16_t* port) {
380
1.20k
        std::string parsed_host;
381
1.20k
        if (!parse_endpoint(config::meta_service_endpoint, &parsed_host, port)) {
382
0
            return Status::InvalidArgument("invalid meta service endpoint: {}",
383
0
                                           config::meta_service_endpoint);
384
0
        }
385
1.21k
        if (is_valid_ip(parsed_host)) {
386
1.21k
            *ip = std::move(parsed_host);
387
1.21k
            return Status::OK();
388
1.21k
        }
389
18.4E
        return hostname_to_ip(parsed_host, *ip);
390
1.20k
    }
391
392
1.48M
    bool is_idle_timeout(long now) {
393
1.48M
        auto idle_timeout_ms = config::meta_service_idle_connection_timeout_ms;
394
        // idle timeout only works without list endpoint.
395
1.48M
        return !is_meta_service_endpoint_list() && idle_timeout_ms > 0 &&
396
1.48M
               _last_access_at_ms.load(std::memory_order_relaxed) + idle_timeout_ms < now;
397
1.48M
    }
398
399
    std::shared_mutex _mutex;
400
    std::atomic<long> _last_access_at_ms {0};
401
    long _deadline_ms {0};
402
    std::shared_ptr<MetaService_Stub> _stub;
403
404
    std::queue<long> last_reconn_time_ms {std::deque<long> {0, 0, 0}};
405
    bool maybe_unhealthy = false;
406
};
407
408
template <typename T, typename... Ts>
409
struct is_any : std::disjunction<std::is_same<T, Ts>...> {};
410
411
template <typename T, typename... Ts>
412
constexpr bool is_any_v = is_any<T, Ts...>::value;
413
414
template <typename Request>
415
305
static std::string debug_info(const Request& req) {
416
305
    if constexpr (is_any_v<Request, CommitTxnRequest, AbortTxnRequest, PrecommitTxnRequest>) {
417
0
        return fmt::format(" txn_id={}", req.txn_id());
418
0
    } else if constexpr (is_any_v<Request, StartTabletJobRequest, FinishTabletJobRequest>) {
419
0
        return fmt::format(" tablet_id={}", req.job().idx().tablet_id());
420
0
    } else if constexpr (is_any_v<Request, UpdateDeleteBitmapRequest>) {
421
0
        return fmt::format(" tablet_id={}, lock_id={}", req.tablet_id(), req.lock_id());
422
305
    } else if constexpr (is_any_v<Request, GetDeleteBitmapUpdateLockRequest>) {
423
305
        return fmt::format(" table_id={}, lock_id={}", req.table_id(), req.lock_id());
424
305
    } else if constexpr (is_any_v<Request, GetTabletRequest>) {
425
0
        return fmt::format(" tablet_id={}", req.tablet_id());
426
    } else if constexpr (is_any_v<Request, GetObjStoreInfoRequest, ListSnapshotRequest,
427
0
                                  GetInstanceRequest, GetClusterStatusRequest>) {
428
0
        return "";
429
0
    } else if constexpr (is_any_v<Request, CreateRowsetRequest>) {
430
0
        return fmt::format(" tablet_id={}", req.rowset_meta().tablet_id());
431
    } else if constexpr (is_any_v<Request, RemoveDeleteBitmapRequest>) {
432
        return fmt::format(" tablet_id={}", req.tablet_id());
433
0
    } else if constexpr (is_any_v<Request, RemoveDeleteBitmapUpdateLockRequest>) {
434
0
        return fmt::format(" table_id={}, tablet_id={}, lock_id={}", req.table_id(),
435
0
                           req.tablet_id(), req.lock_id());
436
0
    } else if constexpr (is_any_v<Request, GetDeleteBitmapRequest>) {
437
0
        return fmt::format(" tablet_id={}", req.tablet_id());
438
    } else if constexpr (is_any_v<Request, GetSchemaDictRequest>) {
439
        return fmt::format(" index_id={}", req.index_id());
440
0
    } else if constexpr (is_any_v<Request, RestoreJobRequest>) {
441
0
        return fmt::format(" tablet_id={}", req.tablet_id());
442
0
    } else if constexpr (is_any_v<Request, UpdatePackedFileInfoRequest>) {
443
0
        return fmt::format(" packed_file_path={}", req.packed_file_path());
444
    } else {
445
        static_assert(!sizeof(Request));
446
    }
447
305
}
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_16GetTabletRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_22GetDeleteBitmapRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_19CreateRowsetRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_16CommitTxnRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_15AbortTxnRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_19PrecommitTxnRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_17RestoreJobRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_22GetObjStoreInfoRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_21StartTabletJobRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_22FinishTabletJobRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_25UpdateDeleteBitmapRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_32GetDeleteBitmapUpdateLockRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Line
Count
Source
415
305
static std::string debug_info(const Request& req) {
416
    if constexpr (is_any_v<Request, CommitTxnRequest, AbortTxnRequest, PrecommitTxnRequest>) {
417
        return fmt::format(" txn_id={}", req.txn_id());
418
    } else if constexpr (is_any_v<Request, StartTabletJobRequest, FinishTabletJobRequest>) {
419
        return fmt::format(" tablet_id={}", req.job().idx().tablet_id());
420
    } else if constexpr (is_any_v<Request, UpdateDeleteBitmapRequest>) {
421
        return fmt::format(" tablet_id={}, lock_id={}", req.tablet_id(), req.lock_id());
422
305
    } else if constexpr (is_any_v<Request, GetDeleteBitmapUpdateLockRequest>) {
423
305
        return fmt::format(" table_id={}, lock_id={}", req.table_id(), req.lock_id());
424
    } else if constexpr (is_any_v<Request, GetTabletRequest>) {
425
        return fmt::format(" tablet_id={}", req.tablet_id());
426
    } else if constexpr (is_any_v<Request, GetObjStoreInfoRequest, ListSnapshotRequest,
427
                                  GetInstanceRequest, GetClusterStatusRequest>) {
428
        return "";
429
    } else if constexpr (is_any_v<Request, CreateRowsetRequest>) {
430
        return fmt::format(" tablet_id={}", req.rowset_meta().tablet_id());
431
    } else if constexpr (is_any_v<Request, RemoveDeleteBitmapRequest>) {
432
        return fmt::format(" tablet_id={}", req.tablet_id());
433
    } else if constexpr (is_any_v<Request, RemoveDeleteBitmapUpdateLockRequest>) {
434
        return fmt::format(" table_id={}, tablet_id={}, lock_id={}", req.table_id(),
435
                           req.tablet_id(), req.lock_id());
436
    } else if constexpr (is_any_v<Request, GetDeleteBitmapRequest>) {
437
        return fmt::format(" tablet_id={}", req.tablet_id());
438
    } else if constexpr (is_any_v<Request, GetSchemaDictRequest>) {
439
        return fmt::format(" index_id={}", req.index_id());
440
    } else if constexpr (is_any_v<Request, RestoreJobRequest>) {
441
        return fmt::format(" tablet_id={}", req.tablet_id());
442
    } else if constexpr (is_any_v<Request, UpdatePackedFileInfoRequest>) {
443
        return fmt::format(" packed_file_path={}", req.packed_file_path());
444
    } else {
445
        static_assert(!sizeof(Request));
446
    }
447
305
}
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_35RemoveDeleteBitmapUpdateLockRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_19ListSnapshotRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_18GetInstanceRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_27UpdatePackedFileInfoRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_110debug_infoINS0_23GetClusterStatusRequestEEENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKT_
448
449
574k
inline std::default_random_engine make_random_engine() {
450
574k
    return std::default_random_engine(
451
574k
            static_cast<uint32_t>(std::chrono::steady_clock::now().time_since_epoch().count()));
452
574k
}
453
454
// Convert MetaServiceRPC to LoadRelatedRpc
455
// Returns LoadRelatedRpc::COUNT if the RPC is not a load-related RPC
456
351k
LoadRelatedRpc to_load_related_rpc(MetaServiceRPC rpc) {
457
351k
    switch (rpc) {
458
148k
    case MetaServiceRPC::PREPARE_ROWSET:
459
148k
        return LoadRelatedRpc::PREPARE_ROWSET;
460
147k
    case MetaServiceRPC::COMMIT_ROWSET:
461
147k
        return LoadRelatedRpc::COMMIT_ROWSET;
462
42
    case MetaServiceRPC::UPDATE_TMP_ROWSET:
463
42
        return LoadRelatedRpc::UPDATE_TMP_ROWSET;
464
0
    case MetaServiceRPC::UPDATE_PACKED_FILE_INFO:
465
0
        return LoadRelatedRpc::UPDATE_PACKED_FILE_INFO;
466
55.7k
    case MetaServiceRPC::UPDATE_DELETE_BITMAP:
467
55.7k
        return LoadRelatedRpc::UPDATE_DELETE_BITMAP;
468
0
    default:
469
0
        return LoadRelatedRpc::COUNT; // Not a load-related RPC
470
351k
    }
471
351k
}
472
473
template <typename Request, typename Response>
474
using MetaServiceMethod = void (MetaService_Stub::*)(::google::protobuf::RpcController*,
475
                                                     const Request*, Response*,
476
                                                     ::google::protobuf::Closure*);
477
478
template <typename Request, typename Response>
479
void call_ms(MetaService_Stub* stub, MetaServiceMethod<Request, Response> method,
480
737k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
737k
    (stub->*method)(cntl, &req, res, nullptr);
482
742k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
742k
        restore_actual_code(res->mutable_status());
485
742k
    }
486
737k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_16GetTabletRequestENS0_17GetTabletResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
318k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
318k
    (stub->*method)(cntl, &req, res, nullptr);
482
318k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
318k
        restore_actual_code(res->mutable_status());
485
318k
    }
486
318k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_16GetRowsetRequestENS0_17GetRowsetResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
168k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
168k
    (stub->*method)(cntl, &req, res, nullptr);
482
168k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
168k
        restore_actual_code(res->mutable_status());
485
168k
    }
486
168k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_22GetDeleteBitmapRequestENS0_23GetDeleteBitmapResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
26.3k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
26.3k
    (stub->*method)(cntl, &req, res, nullptr);
482
26.5k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
26.5k
        restore_actual_code(res->mutable_status());
485
26.5k
    }
486
26.3k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_19CreateRowsetRequestENS0_20CreateRowsetResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
144k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
144k
    (stub->*method)(cntl, &req, res, nullptr);
482
147k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
147k
        restore_actual_code(res->mutable_status());
485
147k
    }
486
144k
}
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_16CommitTxnRequestENS0_17CommitTxnResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_15AbortTxnRequestENS0_16AbortTxnResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
488
             brpc::Controller* cntl, const Request& req, Response* res) {
481
488
    (stub->*method)(cntl, &req, res, nullptr);
482
488
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
488
        restore_actual_code(res->mutable_status());
485
488
    }
486
488
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_19PrecommitTxnRequestENS0_20PrecommitTxnResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
33
             brpc::Controller* cntl, const Request& req, Response* res) {
481
33
    (stub->*method)(cntl, &req, res, nullptr);
482
33
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
33
        restore_actual_code(res->mutable_status());
485
33
    }
486
33
}
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_17RestoreJobRequestENS0_18RestoreJobResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_22GetObjStoreInfoRequestENS0_23GetObjStoreInfoResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
231
             brpc::Controller* cntl, const Request& req, Response* res) {
481
231
    (stub->*method)(cntl, &req, res, nullptr);
482
231
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
231
        restore_actual_code(res->mutable_status());
485
231
    }
486
231
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_21StartTabletJobRequestENS0_22StartTabletJobResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
19.0k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
19.0k
    (stub->*method)(cntl, &req, res, nullptr);
482
19.2k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
19.2k
        restore_actual_code(res->mutable_status());
485
19.2k
    }
486
19.0k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_22FinishTabletJobRequestENS0_23FinishTabletJobResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
17.5k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
17.5k
    (stub->*method)(cntl, &req, res, nullptr);
482
18.0k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
18.0k
        restore_actual_code(res->mutable_status());
485
18.0k
    }
486
17.5k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_25UpdateDeleteBitmapRequestENS0_26UpdateDeleteBitmapResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
26.8k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
26.8k
    (stub->*method)(cntl, &req, res, nullptr);
482
28.0k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
28.0k
        restore_actual_code(res->mutable_status());
485
28.0k
    }
486
26.8k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_32GetDeleteBitmapUpdateLockRequestENS0_33GetDeleteBitmapUpdateLockResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
4.54k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
4.54k
    (stub->*method)(cntl, &req, res, nullptr);
482
4.55k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
4.55k
        restore_actual_code(res->mutable_status());
485
4.55k
    }
486
4.54k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_35RemoveDeleteBitmapUpdateLockRequestENS0_36RemoveDeleteBitmapUpdateLockResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
23
             brpc::Controller* cntl, const Request& req, Response* res) {
481
23
    (stub->*method)(cntl, &req, res, nullptr);
482
23
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
23
        restore_actual_code(res->mutable_status());
485
23
    }
486
23
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_19ListSnapshotRequestENS0_20ListSnapshotResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
2
             brpc::Controller* cntl, const Request& req, Response* res) {
481
2
    (stub->*method)(cntl, &req, res, nullptr);
482
2
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
2
        restore_actual_code(res->mutable_status());
485
2
    }
486
2
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_18GetInstanceRequestENS0_19GetInstanceResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
1
             brpc::Controller* cntl, const Request& req, Response* res) {
481
1
    (stub->*method)(cntl, &req, res, nullptr);
482
1
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
1
        restore_actual_code(res->mutable_status());
485
1
    }
486
1
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_27UpdatePackedFileInfoRequestENS0_28UpdatePackedFileInfoResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
10.8k
             brpc::Controller* cntl, const Request& req, Response* res) {
481
10.8k
    (stub->*method)(cntl, &req, res, nullptr);
482
10.8k
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
10.8k
        restore_actual_code(res->mutable_status());
485
10.8k
    }
486
10.8k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_17call_msINS0_23GetClusterStatusRequestENS0_24GetClusterStatusResponseEEEvPNS0_16MetaService_StubEMS5_FvPN6google8protobuf13RpcControllerEPKT_PT0_PNS8_7ClosureEEPN4brpc10ControllerERSC_SF_
Line
Count
Source
480
49
             brpc::Controller* cntl, const Request& req, Response* res) {
481
49
    (stub->*method)(cntl, &req, res, nullptr);
482
49
    if (!cntl->Failed()) {
483
        // Meta Service may downgrade code for wire compatibility; restore the exact value.
484
49
        restore_actual_code(res->mutable_status());
485
49
    }
486
49
}
487
488
// Rate limiting context for retry_rpc
489
struct RpcRateLimitCtx {
490
    HostLevelMSRpcRateLimiters* host_limiters {nullptr};
491
    MSBackpressureHandler* backpressure_handler {nullptr};
492
    int64_t table_id {-1}; // For table-level backpressure, passed from caller
493
};
494
495
// Apply rate limiting before RPC (both host-level and table-level)
496
573k
void apply_rate_limit(MetaServiceRPC rpc, const RpcRateLimitCtx& ctx) {
497
    // Table-level rate limit (for load-related RPCs only)
498
574k
    if (ctx.backpressure_handler && ctx.table_id > 0) {
499
175k
        LoadRelatedRpc load_rpc = to_load_related_rpc(rpc);
500
175k
        if (load_rpc != LoadRelatedRpc::COUNT) {
501
174k
            auto wait_until = ctx.backpressure_handler->before_rpc(load_rpc, ctx.table_id);
502
174k
            auto now = std::chrono::steady_clock::now();
503
174k
            if (wait_until > now) {
504
0
                auto wait_us =
505
0
                        std::chrono::duration_cast<std::chrono::microseconds>(wait_until - now)
506
0
                                .count();
507
0
                if (wait_us > 0) {
508
0
                    if (auto* recorder = get_throttle_wait_recorder(load_rpc);
509
0
                        recorder != nullptr) {
510
0
                        *recorder << wait_us;
511
0
                    }
512
0
                    bthread_usleep(wait_us);
513
0
                }
514
0
            }
515
174k
        }
516
175k
    }
517
518
    // Host-level rate limit
519
574k
    if (ctx.host_limiters) {
520
574k
        ctx.host_limiters->limit(rpc);
521
574k
    }
522
573k
}
523
524
// Record RPC QPS statistics after RPC (for table-level tracking)
525
574k
void record_rpc_qps(MetaServiceRPC rpc, const RpcRateLimitCtx& ctx) {
526
575k
    if (ctx.backpressure_handler && ctx.table_id > 0) {
527
176k
        LoadRelatedRpc load_rpc = to_load_related_rpc(rpc);
528
176k
        if (load_rpc != LoadRelatedRpc::COUNT) {
529
176k
            ctx.backpressure_handler->after_rpc(load_rpc, ctx.table_id);
530
176k
        }
531
176k
    }
532
574k
}
533
534
template <typename Request, typename Response>
535
Status retry_rpc(MetaServiceRPC rpc, const Request& req, Response* res,
536
                 MetaServiceMethod<Request, Response> method,
537
571k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
571k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
571k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
571k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
571k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
571k
    int retry_times = 0;
547
571k
    uint32_t duration_ms = 0;
548
571k
    std::string error_msg;
549
571k
    std::default_random_engine rng = make_random_engine();
550
571k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
571k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
571k
    MetaServiceProxy* proxy;
553
571k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
573k
    while (true) {
556
573k
        std::shared_ptr<MetaService_Stub> stub;
557
573k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
573k
        apply_rate_limit(rpc, rate_limit_ctx);
561
573k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
573k
        brpc::Controller cntl;
564
573k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
573k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
54.2k
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
519k
        } else {
568
519k
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
519k
        }
570
573k
        cntl.set_max_retry(kBrpcRetryTimes);
571
573k
        res->Clear();
572
573k
        int error_code = 0;
573
573k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
573k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
573k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
573k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
573k
            return Status::OK();
584
573k
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
16
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
16
                                                                     res->status().msg());
587
55
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
687
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
687
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
687
                                                                   res->status().msg());
595
18.4E
        } else {
596
18.4E
            error_msg = res->status().msg();
597
18.4E
        }
598
599
18.4E
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
18.4E
        ++retry_times;
604
18.4E
        if (retry_times > config::meta_service_rpc_retry_times ||
605
18.4E
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
18.4E
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
18.4E
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
18.4E
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
18.4E
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
18.4E
        bthread_usleep(duration_ms * 1000);
616
18.4E
    }
617
18.4E
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
571k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_16GetTabletRequestENS0_17GetTabletResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
319k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
319k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
319k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
319k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
319k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
319k
    int retry_times = 0;
547
319k
    uint32_t duration_ms = 0;
548
319k
    std::string error_msg;
549
319k
    std::default_random_engine rng = make_random_engine();
550
319k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
319k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
319k
    MetaServiceProxy* proxy;
553
319k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
319k
    while (true) {
556
318k
        std::shared_ptr<MetaService_Stub> stub;
557
318k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
318k
        apply_rate_limit(rpc, rate_limit_ctx);
561
318k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
318k
        brpc::Controller cntl;
564
318k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
319k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
318k
        } else {
568
318k
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
318k
        }
570
318k
        cntl.set_max_retry(kBrpcRetryTimes);
571
318k
        res->Clear();
572
318k
        int error_code = 0;
573
318k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
318k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
318k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
318k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
318k
            return Status::OK();
584
318k
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
666
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
666
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
100
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
100
                                                                   res->status().msg());
595
566
        } else {
596
566
            error_msg = res->status().msg();
597
566
        }
598
599
566
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
566
        ++retry_times;
604
566
        if (retry_times > config::meta_service_rpc_retry_times ||
605
566
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
566
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
566
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
566
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
566
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
566
        bthread_usleep(duration_ms * 1000);
616
566
    }
617
614
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
319k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_22GetDeleteBitmapRequestENS0_23GetDeleteBitmapResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
26.4k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
26.4k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
26.4k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
26.4k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
26.4k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
26.4k
    int retry_times = 0;
547
26.4k
    uint32_t duration_ms = 0;
548
26.4k
    std::string error_msg;
549
26.4k
    std::default_random_engine rng = make_random_engine();
550
26.4k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
26.4k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
26.4k
    MetaServiceProxy* proxy;
553
26.4k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
26.4k
    while (true) {
556
26.4k
        std::shared_ptr<MetaService_Stub> stub;
557
26.4k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
26.4k
        apply_rate_limit(rpc, rate_limit_ctx);
561
26.4k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
26.4k
        brpc::Controller cntl;
564
26.4k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
26.4k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
26.4k
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
18.4E
        } else {
568
18.4E
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
18.4E
        }
570
26.4k
        cntl.set_max_retry(kBrpcRetryTimes);
571
26.4k
        res->Clear();
572
26.4k
        int error_code = 0;
573
26.4k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
26.4k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
26.4k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
26.5k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
26.5k
            return Status::OK();
584
18.4E
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
18.4E
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
18.4E
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
0
                                                                   res->status().msg());
595
18.4E
        } else {
596
18.4E
            error_msg = res->status().msg();
597
18.4E
        }
598
599
18.4E
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
18.4E
        ++retry_times;
604
18.4E
        if (retry_times > config::meta_service_rpc_retry_times ||
605
18.4E
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
18.4E
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
18.4E
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
18.4E
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
18.4E
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
18.4E
        bthread_usleep(duration_ms * 1000);
616
18.4E
    }
617
18.4E
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
26.4k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_19CreateRowsetRequestENS0_20CreateRowsetResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
146k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
146k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
146k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
146k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
146k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
146k
    int retry_times = 0;
547
146k
    uint32_t duration_ms = 0;
548
146k
    std::string error_msg;
549
146k
    std::default_random_engine rng = make_random_engine();
550
146k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
146k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
146k
    MetaServiceProxy* proxy;
553
146k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
147k
    while (true) {
556
147k
        std::shared_ptr<MetaService_Stub> stub;
557
147k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
147k
        apply_rate_limit(rpc, rate_limit_ctx);
561
147k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
147k
        brpc::Controller cntl;
564
147k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
147k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
147k
        } else {
568
147k
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
147k
        }
570
147k
        cntl.set_max_retry(kBrpcRetryTimes);
571
147k
        res->Clear();
572
147k
        int error_code = 0;
573
147k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
147k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
147k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
147k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
147k
            return Status::OK();
584
18.4E
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
2
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
2
                                                                     res->status().msg());
587
18.4E
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
18.4E
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
1
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
1
                                                                   res->status().msg());
595
18.4E
        } else {
596
18.4E
            error_msg = res->status().msg();
597
18.4E
        }
598
599
18.4E
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
18.4E
        ++retry_times;
604
18.4E
        if (retry_times > config::meta_service_rpc_retry_times ||
605
18.4E
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
18.4E
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
18.4E
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
18.4E
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
18.4E
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
18.4E
        bthread_usleep(duration_ms * 1000);
616
18.4E
    }
617
18.4E
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
146k
}
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_16CommitTxnRequestENS0_17CommitTxnResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_15AbortTxnRequestENS0_16AbortTxnResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
488
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
488
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
488
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
488
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
488
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
488
    int retry_times = 0;
547
488
    uint32_t duration_ms = 0;
548
488
    std::string error_msg;
549
488
    std::default_random_engine rng = make_random_engine();
550
488
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
488
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
488
    MetaServiceProxy* proxy;
553
488
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
488
    while (true) {
556
488
        std::shared_ptr<MetaService_Stub> stub;
557
488
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
488
        apply_rate_limit(rpc, rate_limit_ctx);
561
488
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
488
        brpc::Controller cntl;
564
488
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
488
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
488
        } else {
568
488
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
488
        }
570
488
        cntl.set_max_retry(kBrpcRetryTimes);
571
488
        res->Clear();
572
488
        int error_code = 0;
573
488
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
488
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
488
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
488
        } else if (res->status().code() == MetaServiceCode::OK) {
583
479
            return Status::OK();
584
479
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
9
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
9
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
9
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
9
                                                                   res->status().msg());
595
9
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
488
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_19PrecommitTxnRequestENS0_20PrecommitTxnResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
33
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
33
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
33
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
33
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
33
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
33
    int retry_times = 0;
547
33
    uint32_t duration_ms = 0;
548
33
    std::string error_msg;
549
33
    std::default_random_engine rng = make_random_engine();
550
33
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
33
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
33
    MetaServiceProxy* proxy;
553
33
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
33
    while (true) {
556
33
        std::shared_ptr<MetaService_Stub> stub;
557
33
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
33
        apply_rate_limit(rpc, rate_limit_ctx);
561
33
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
33
        brpc::Controller cntl;
564
33
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
33
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
33
        } else {
568
33
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
33
        }
570
33
        cntl.set_max_retry(kBrpcRetryTimes);
571
33
        res->Clear();
572
33
        int error_code = 0;
573
33
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
33
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
33
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
33
        } else if (res->status().code() == MetaServiceCode::OK) {
583
33
            return Status::OK();
584
33
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
0
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
0
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
0
                                                                   res->status().msg());
595
0
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
33
}
Unexecuted instantiation: cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_17RestoreJobRequestENS0_18RestoreJobResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_22GetObjStoreInfoRequestENS0_23GetObjStoreInfoResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
231
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
231
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
231
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
231
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
231
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
231
    int retry_times = 0;
547
231
    uint32_t duration_ms = 0;
548
231
    std::string error_msg;
549
231
    std::default_random_engine rng = make_random_engine();
550
231
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
231
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
231
    MetaServiceProxy* proxy;
553
231
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
231
    while (true) {
556
231
        std::shared_ptr<MetaService_Stub> stub;
557
231
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
231
        apply_rate_limit(rpc, rate_limit_ctx);
561
231
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
231
        brpc::Controller cntl;
564
231
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
231
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
231
        } else {
568
231
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
231
        }
570
231
        cntl.set_max_retry(kBrpcRetryTimes);
571
231
        res->Clear();
572
231
        int error_code = 0;
573
231
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
231
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
231
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
231
        } else if (res->status().code() == MetaServiceCode::OK) {
583
231
            return Status::OK();
584
231
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
0
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
0
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
0
                                                                   res->status().msg());
595
0
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
231
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_21StartTabletJobRequestENS0_22StartTabletJobResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
19.0k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
19.0k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
19.0k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
19.0k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
19.0k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
19.0k
    int retry_times = 0;
547
19.0k
    uint32_t duration_ms = 0;
548
19.0k
    std::string error_msg;
549
19.0k
    std::default_random_engine rng = make_random_engine();
550
19.0k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
19.0k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
19.0k
    MetaServiceProxy* proxy;
553
19.0k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
19.1k
    while (true) {
556
19.1k
        std::shared_ptr<MetaService_Stub> stub;
557
19.1k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
19.1k
        apply_rate_limit(rpc, rate_limit_ctx);
561
19.1k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
19.1k
        brpc::Controller cntl;
564
19.1k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
19.1k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
19.1k
        } else {
568
19.1k
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
19.1k
        }
570
19.1k
        cntl.set_max_retry(kBrpcRetryTimes);
571
19.1k
        res->Clear();
572
19.1k
        int error_code = 0;
573
19.1k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
19.1k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
19.1k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
19.1k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
19.0k
            return Status::OK();
584
19.0k
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
110
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
183
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
183
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
183
                                                                   res->status().msg());
595
18.4E
        } else {
596
18.4E
            error_msg = res->status().msg();
597
18.4E
        }
598
599
18.4E
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
18.4E
        ++retry_times;
604
18.4E
        if (retry_times > config::meta_service_rpc_retry_times ||
605
18.4E
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
18.4E
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
18.4E
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
18.4E
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
18.4E
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
18.4E
        bthread_usleep(duration_ms * 1000);
616
18.4E
    }
617
18.4E
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
19.0k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_22FinishTabletJobRequestENS0_23FinishTabletJobResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
17.2k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
17.2k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
17.2k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
17.2k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
17.2k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
17.2k
    int retry_times = 0;
547
17.2k
    uint32_t duration_ms = 0;
548
17.2k
    std::string error_msg;
549
17.2k
    std::default_random_engine rng = make_random_engine();
550
17.2k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
17.2k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
17.2k
    MetaServiceProxy* proxy;
553
17.2k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
17.9k
    while (true) {
556
17.9k
        std::shared_ptr<MetaService_Stub> stub;
557
17.9k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
17.9k
        apply_rate_limit(rpc, rate_limit_ctx);
561
17.9k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
17.9k
        brpc::Controller cntl;
564
17.9k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
17.9k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
17.9k
        } else {
568
17.9k
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
17.9k
        }
570
17.9k
        cntl.set_max_retry(kBrpcRetryTimes);
571
17.9k
        res->Clear();
572
17.9k
        int error_code = 0;
573
17.9k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
17.9k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
17.9k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
17.9k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
17.9k
            return Status::OK();
584
18.4E
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
14
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
14
                                                                     res->status().msg());
587
18.4E
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
18.4E
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
59
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
59
                                                                   res->status().msg());
595
18.4E
        } else {
596
18.4E
            error_msg = res->status().msg();
597
18.4E
        }
598
599
18.4E
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
18.4E
        ++retry_times;
604
18.4E
        if (retry_times > config::meta_service_rpc_retry_times ||
605
18.4E
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
18.4E
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
18.4E
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
18.4E
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
18.4E
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
18.4E
        bthread_usleep(duration_ms * 1000);
616
18.4E
    }
617
18.4E
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
17.2k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_25UpdateDeleteBitmapRequestENS0_26UpdateDeleteBitmapResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
27.1k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
27.1k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
27.1k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
27.1k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
27.1k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
27.1k
    int retry_times = 0;
547
27.1k
    uint32_t duration_ms = 0;
548
27.1k
    std::string error_msg;
549
27.1k
    std::default_random_engine rng = make_random_engine();
550
27.1k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
27.1k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
27.1k
    MetaServiceProxy* proxy;
553
27.1k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
27.6k
    while (true) {
556
27.6k
        std::shared_ptr<MetaService_Stub> stub;
557
27.6k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
27.6k
        apply_rate_limit(rpc, rate_limit_ctx);
561
27.6k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
27.6k
        brpc::Controller cntl;
564
27.6k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
27.7k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
27.7k
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
18.4E
        } else {
568
18.4E
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
18.4E
        }
570
27.6k
        cntl.set_max_retry(kBrpcRetryTimes);
571
27.6k
        res->Clear();
572
27.6k
        int error_code = 0;
573
27.6k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
27.6k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
27.6k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
28.0k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
28.0k
            return Status::OK();
584
18.4E
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
18.4E
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
18.4E
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
5
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
5
                                                                   res->status().msg());
595
18.4E
        } else {
596
18.4E
            error_msg = res->status().msg();
597
18.4E
        }
598
599
18.4E
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
18.4E
        ++retry_times;
604
18.4E
        if (retry_times > config::meta_service_rpc_retry_times ||
605
18.4E
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
18.4E
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
18.4E
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
18.4E
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
18.4E
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
18.4E
        bthread_usleep(duration_ms * 1000);
616
18.4E
    }
617
18.4E
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
27.1k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_32GetDeleteBitmapUpdateLockRequestENS0_33GetDeleteBitmapUpdateLockResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
4.55k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
4.55k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
4.55k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
4.55k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
4.55k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
4.55k
    int retry_times = 0;
547
4.55k
    uint32_t duration_ms = 0;
548
4.55k
    std::string error_msg;
549
4.55k
    std::default_random_engine rng = make_random_engine();
550
4.55k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
4.55k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
4.55k
    MetaServiceProxy* proxy;
553
4.55k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
4.55k
    while (true) {
556
4.55k
        std::shared_ptr<MetaService_Stub> stub;
557
4.55k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
4.55k
        apply_rate_limit(rpc, rate_limit_ctx);
561
4.55k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
4.55k
        brpc::Controller cntl;
564
4.55k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
4.55k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
4.55k
        } else {
568
4.55k
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
4.55k
        }
570
4.55k
        cntl.set_max_retry(kBrpcRetryTimes);
571
4.55k
        res->Clear();
572
4.55k
        int error_code = 0;
573
4.55k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
4.55k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
4.55k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
4.55k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
4.24k
            return Status::OK();
584
4.24k
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
303
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
305
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
305
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
305
                                                                   res->status().msg());
595
18.4E
        } else {
596
18.4E
            error_msg = res->status().msg();
597
18.4E
        }
598
599
18.4E
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
18.4E
        ++retry_times;
604
18.4E
        if (retry_times > config::meta_service_rpc_retry_times ||
605
18.4E
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
18.4E
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
18.4E
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
18.4E
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
18.4E
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
18.4E
        bthread_usleep(duration_ms * 1000);
616
18.4E
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
4.55k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_35RemoveDeleteBitmapUpdateLockRequestENS0_36RemoveDeleteBitmapUpdateLockResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
23
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
23
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
23
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
23
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
23
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
23
    int retry_times = 0;
547
23
    uint32_t duration_ms = 0;
548
23
    std::string error_msg;
549
23
    std::default_random_engine rng = make_random_engine();
550
23
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
23
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
23
    MetaServiceProxy* proxy;
553
23
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
23
    while (true) {
556
23
        std::shared_ptr<MetaService_Stub> stub;
557
23
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
23
        apply_rate_limit(rpc, rate_limit_ctx);
561
23
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
23
        brpc::Controller cntl;
564
23
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
23
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
23
        } else {
568
23
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
23
        }
570
23
        cntl.set_max_retry(kBrpcRetryTimes);
571
23
        res->Clear();
572
23
        int error_code = 0;
573
23
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
23
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
23
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
23
        } else if (res->status().code() == MetaServiceCode::OK) {
583
0
            return Status::OK();
584
23
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
23
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
23
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
23
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
23
                                                                   res->status().msg());
595
23
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
23
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_19ListSnapshotRequestENS0_20ListSnapshotResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
2
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
2
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
2
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
2
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
2
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
2
    int retry_times = 0;
547
2
    uint32_t duration_ms = 0;
548
2
    std::string error_msg;
549
2
    std::default_random_engine rng = make_random_engine();
550
2
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
2
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
2
    MetaServiceProxy* proxy;
553
2
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
2
    while (true) {
556
2
        std::shared_ptr<MetaService_Stub> stub;
557
2
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
2
        apply_rate_limit(rpc, rate_limit_ctx);
561
2
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
2
        brpc::Controller cntl;
564
2
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
2
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
2
        } else {
568
2
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
2
        }
570
2
        cntl.set_max_retry(kBrpcRetryTimes);
571
2
        res->Clear();
572
2
        int error_code = 0;
573
2
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
2
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
2
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
2
        } else if (res->status().code() == MetaServiceCode::OK) {
583
0
            return Status::OK();
584
2
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
2
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
2
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
2
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
2
                                                                   res->status().msg());
595
2
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
2
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_18GetInstanceRequestENS0_19GetInstanceResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
1
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
1
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
1
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
1
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
1
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
1
    int retry_times = 0;
547
1
    uint32_t duration_ms = 0;
548
1
    std::string error_msg;
549
1
    std::default_random_engine rng = make_random_engine();
550
1
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
1
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
1
    MetaServiceProxy* proxy;
553
1
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
1
    while (true) {
556
1
        std::shared_ptr<MetaService_Stub> stub;
557
1
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
1
        apply_rate_limit(rpc, rate_limit_ctx);
561
1
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
1
        brpc::Controller cntl;
564
1
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
1
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
1
        } else {
568
1
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
1
        }
570
1
        cntl.set_max_retry(kBrpcRetryTimes);
571
1
        res->Clear();
572
1
        int error_code = 0;
573
1
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
1
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
1
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
1
        } else if (res->status().code() == MetaServiceCode::OK) {
583
1
            return Status::OK();
584
1
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
0
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
0
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
0
                                                                   res->status().msg());
595
0
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
1
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_27UpdatePackedFileInfoRequestENS0_28UpdatePackedFileInfoResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
10.8k
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
10.8k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
10.8k
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
10.8k
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
10.8k
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
10.8k
    int retry_times = 0;
547
10.8k
    uint32_t duration_ms = 0;
548
10.8k
    std::string error_msg;
549
10.8k
    std::default_random_engine rng = make_random_engine();
550
10.8k
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
10.8k
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
10.8k
    MetaServiceProxy* proxy;
553
10.8k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
10.8k
    while (true) {
556
10.8k
        std::shared_ptr<MetaService_Stub> stub;
557
10.8k
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
10.8k
        apply_rate_limit(rpc, rate_limit_ctx);
561
10.8k
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
10.8k
        brpc::Controller cntl;
564
10.8k
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
10.8k
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
10.8k
        } else {
568
10.8k
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
10.8k
        }
570
10.8k
        cntl.set_max_retry(kBrpcRetryTimes);
571
10.8k
        res->Clear();
572
10.8k
        int error_code = 0;
573
10.8k
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
10.8k
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
10.8k
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
10.8k
        } else if (res->status().code() == MetaServiceCode::OK) {
583
10.8k
            return Status::OK();
584
10.8k
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
0
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
0
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
0
                                                                   res->status().msg());
595
0
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
10.8k
}
cloud_meta_mgr.cpp:_ZN5doris5cloud12_GLOBAL__N_19retry_rpcINS0_23GetClusterStatusRequestENS0_24GetClusterStatusResponseEEENS_6StatusENS0_14MetaServiceRPCERKT_PT0_MNS0_16MetaService_StubEFvPN6google8protobuf13RpcControllerEPS8_SB_PNSE_7ClosureEERKNS1_15RpcRateLimitCtxE
Line
Count
Source
537
49
                 const RpcRateLimitCtx& rate_limit_ctx = {}) {
538
49
    static_assert(std::is_base_of_v<::google::protobuf::Message, Request>);
539
49
    static_assert(std::is_base_of_v<::google::protobuf::Message, Response>);
540
541
49
    std::string_view op_name = meta_service_rpc_display_name(rpc);
542
543
    // Applies only to the current file, and all req are non-const, but passed as const types.
544
49
    const_cast<Request&>(req).set_request_ip(BackendOptions::get_be_endpoint());
545
546
49
    int retry_times = 0;
547
49
    uint32_t duration_ms = 0;
548
49
    std::string error_msg;
549
49
    std::default_random_engine rng = make_random_engine();
550
49
    std::uniform_int_distribution<uint32_t> u(20, 200);
551
49
    std::uniform_int_distribution<uint32_t> u2(500, 1000);
552
49
    MetaServiceProxy* proxy;
553
49
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
554
555
49
    while (true) {
556
49
        std::shared_ptr<MetaService_Stub> stub;
557
49
        RETURN_IF_ERROR(proxy->get(&stub));
558
559
        // Apply rate limiting (both host-level and table-level)
560
49
        apply_rate_limit(rpc, rate_limit_ctx);
561
49
        TEST_SYNC_POINT_CALLBACK("retry_rpc::after_rate_limit", &rpc);
562
563
49
        brpc::Controller cntl;
564
49
        if (rpc == MetaServiceRPC::GET_DELETE_BITMAP ||
565
49
            rpc == MetaServiceRPC::UPDATE_DELETE_BITMAP) {
566
0
            cntl.set_timeout_ms(3 * config::meta_service_brpc_timeout_ms);
567
49
        } else {
568
49
            cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
569
49
        }
570
49
        cntl.set_max_retry(kBrpcRetryTimes);
571
49
        res->Clear();
572
49
        int error_code = 0;
573
49
        call_ms(stub.get(), method, &cntl, req, res);
574
575
        // Record QPS statistics for all RPCs sent to MS (success or failure)
576
49
        record_rpc_qps(rpc, rate_limit_ctx);
577
578
49
        if (cntl.Failed()) [[unlikely]] {
579
0
            error_msg = cntl.ErrorText();
580
0
            error_code = cntl.ErrorCode();
581
0
            proxy->set_unhealthy();
582
49
        } else if (res->status().code() == MetaServiceCode::OK) {
583
49
            return Status::OK();
584
49
        } else if (res->status().code() == MetaServiceCode::INVALID_ARGUMENT) {
585
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT, false>("failed to {}: {}", op_name,
586
0
                                                                     res->status().msg());
587
0
        } else if (res->status().code() == MetaServiceCode::MS_TOO_BUSY) {
588
            // MS_BUSY should also be retried
589
0
            if (rate_limit_ctx.backpressure_handler) {
590
0
                rate_limit_ctx.backpressure_handler->on_ms_busy();
591
0
            }
592
0
        } else if (res->status().code() != MetaServiceCode::KV_TXN_CONFLICT) {
593
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to {}: {}", op_name,
594
0
                                                                   res->status().msg());
595
0
        } else {
596
0
            error_msg = res->status().msg();
597
0
        }
598
599
0
        if (error_code == brpc::ERPCTIMEDOUT) {
600
0
            g_cloud_meta_mgr_rpc_timeout_count << 1;
601
0
        }
602
603
0
        ++retry_times;
604
0
        if (retry_times > config::meta_service_rpc_retry_times ||
605
0
            (retry_times > config::meta_service_rpc_timeout_retry_times &&
606
0
             error_code == brpc::ERPCTIMEDOUT) ||
607
0
            (retry_times > config::meta_service_conflict_error_retry_times &&
608
0
             res->status().code() == MetaServiceCode::KV_TXN_CONFLICT)) {
609
0
            break;
610
0
        }
611
612
0
        duration_ms = retry_times <= 100 ? u(rng) : u2(rng);
613
0
        LOG(WARNING) << "failed to " << op_name << debug_info(req) << " retry_times=" << retry_times
614
0
                     << " sleep=" << duration_ms << "ms : " << cntl.ErrorText();
615
0
        bthread_usleep(duration_ms * 1000);
616
0
    }
617
0
    return Status::RpcError("failed to {}: rpc timeout, last msg={}", op_name, error_msg);
618
49
}
619
620
} // namespace
621
622
319k
Status CloudMetaMgr::get_tablet_meta(int64_t tablet_id, TabletMetaSharedPtr* tablet_meta) {
623
18.4E
    VLOG_DEBUG << "send GetTabletRequest, tablet_id: " << tablet_id;
624
319k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::get_tablet_meta", Status::OK(), tablet_id,
625
319k
                                      tablet_meta);
626
319k
    GetTabletRequest req;
627
319k
    GetTabletResponse resp;
628
319k
    req.set_cloud_unique_id(config::cloud_unique_id);
629
319k
    req.set_tablet_id(tablet_id);
630
319k
    Status st =
631
319k
            retry_rpc(MetaServiceRPC::GET_TABLET_META, req, &resp, &MetaService_Stub::get_tablet,
632
319k
                      {
633
319k
                              .host_limiters = host_level_ms_rpc_rate_limiters_,
634
319k
                              .backpressure_handler = ms_backpressure_handler_,
635
319k
                      });
636
319k
    if (!st.ok()) {
637
100
        if (resp.status().code() == MetaServiceCode::TABLET_NOT_FOUND) {
638
100
            return Status::NotFound("failed to get tablet meta: {}", resp.status().msg());
639
100
        }
640
0
        return st;
641
100
    }
642
643
319k
    *tablet_meta = std::make_shared<TabletMeta>();
644
319k
    (*tablet_meta)
645
319k
            ->init_from_pb(cloud_tablet_meta_to_doris(std::move(*resp.mutable_tablet_meta())));
646
319k
    VLOG_DEBUG << "get tablet meta, tablet_id: " << (*tablet_meta)->tablet_id();
647
319k
    return Status::OK();
648
319k
}
649
650
Status CloudMetaMgr::sync_tablet_rowsets(CloudTablet* tablet, const SyncOptions& options,
651
128k
                                         SyncRowsetStats* sync_stats) {
652
128k
    std::unique_lock lock {tablet->get_sync_meta_lock()};
653
128k
    return sync_tablet_rowsets_unlocked(tablet, lock, options, sync_stats);
654
128k
}
655
656
Status CloudMetaMgr::_log_mow_delete_bitmap(CloudTablet* tablet, GetRowsetResponse& resp,
657
                                            DeleteBitmap& delete_bitmap, int64_t old_max_version,
658
37.2k
                                            bool full_sync, int32_t read_version) {
659
37.2k
    if (config::enable_mow_verbose_log && !resp.rowset_meta().empty() &&
660
37.2k
        delete_bitmap.cardinality() > 0) {
661
0
        int64_t tablet_id = tablet->tablet_id();
662
0
        std::vector<std::string> new_rowset_msgs;
663
0
        std::vector<std::string> old_rowset_msgs;
664
0
        std::unordered_set<RowsetId> new_rowset_ids;
665
0
        int64_t new_max_version = resp.rowset_meta().rbegin()->end_version();
666
0
        for (const auto& rs : resp.rowset_meta()) {
667
0
            RowsetId rowset_id;
668
0
            rowset_id.init(rs.rowset_id_v2());
669
0
            new_rowset_ids.insert(rowset_id);
670
0
            DeleteBitmap rowset_dbm(tablet_id);
671
0
            delete_bitmap.subset({rowset_id, 0, 0},
672
0
                                 {rowset_id, std::numeric_limits<DeleteBitmap::SegmentId>::max(),
673
0
                                  std::numeric_limits<DeleteBitmap::Version>::max()},
674
0
                                 &rowset_dbm);
675
0
            size_t cardinality = rowset_dbm.cardinality();
676
0
            size_t count = rowset_dbm.get_delete_bitmap_count();
677
0
            if (cardinality > 0) {
678
0
                new_rowset_msgs.push_back(fmt::format("({}[{}-{}],{},{})", rs.rowset_id_v2(),
679
0
                                                      rs.start_version(), rs.end_version(), count,
680
0
                                                      cardinality));
681
0
            }
682
0
        }
683
684
0
        if (old_max_version > 0) {
685
0
            std::vector<RowsetSharedPtr> old_rowsets;
686
0
            RowsetIdUnorderedSet old_rowset_ids;
687
0
            {
688
0
                std::lock_guard rlock(tablet->get_header_lock());
689
0
                RETURN_IF_ERROR(tablet->get_all_rs_id_unlocked(old_max_version, &old_rowset_ids));
690
0
                old_rowsets = tablet->get_rowset_by_ids(&old_rowset_ids);
691
0
            }
692
0
            for (const auto& rs : old_rowsets) {
693
0
                if (!new_rowset_ids.contains(rs->rowset_id())) {
694
0
                    DeleteBitmap rowset_dbm(tablet_id);
695
0
                    delete_bitmap.subset(
696
0
                            {rs->rowset_id(), 0, 0},
697
0
                            {rs->rowset_id(), std::numeric_limits<DeleteBitmap::SegmentId>::max(),
698
0
                             std::numeric_limits<DeleteBitmap::Version>::max()},
699
0
                            &rowset_dbm);
700
0
                    size_t cardinality = rowset_dbm.cardinality();
701
0
                    size_t count = rowset_dbm.get_delete_bitmap_count();
702
0
                    if (cardinality > 0) {
703
0
                        old_rowset_msgs.push_back(
704
0
                                fmt::format("({}{},{},{})", rs->rowset_id().to_string(),
705
0
                                            rs->version().to_string(), count, cardinality));
706
0
                    }
707
0
                }
708
0
            }
709
0
        }
710
711
0
        std::string tablet_info = fmt::format(
712
0
                "tablet_id={} table_id={} index_id={} partition_id={}", tablet->tablet_id(),
713
0
                tablet->table_id(), tablet->index_id(), tablet->partition_id());
714
0
        LOG_INFO("[verbose] sync tablet delete bitmap " + tablet_info)
715
0
                .tag("full_sync", full_sync)
716
0
                .tag("read_version", read_version)
717
0
                .tag("old_max_version", old_max_version)
718
0
                .tag("new_max_version", new_max_version)
719
0
                .tag("cumu_compaction_cnt", resp.stats().cumulative_compaction_cnt())
720
0
                .tag("base_compaction_cnt", resp.stats().base_compaction_cnt())
721
0
                .tag("cumu_point", resp.stats().cumulative_point())
722
0
                .tag("rowset_num", resp.rowset_meta().size())
723
0
                .tag("delete_bitmap_cardinality", delete_bitmap.cardinality())
724
0
                .tag("old_rowsets(rowset,count,cardinality)",
725
0
                     fmt::format("[{}]", fmt::join(old_rowset_msgs, ", ")))
726
0
                .tag("new_rowsets(rowset,count,cardinality)",
727
0
                     fmt::format("[{}]", fmt::join(new_rowset_msgs, ", ")));
728
0
    }
729
37.2k
    return Status::OK();
730
37.2k
}
731
732
Status CloudMetaMgr::sync_tablet_rowsets_unlocked(CloudTablet* tablet,
733
                                                  std::unique_lock<bthread::Mutex>& lock,
734
                                                  const SyncOptions& options,
735
168k
                                                  SyncRowsetStats* sync_stats) {
736
168k
    using namespace std::chrono;
737
738
168k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::sync_tablet_rowsets", Status::OK(), tablet);
739
168k
    DBUG_EXECUTE_IF("CloudMetaMgr::sync_tablet_rowsets.before.inject_error", {
740
168k
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
741
168k
        auto target_table_id = dp->param<int64_t>("table_id", -1);
742
168k
        if (target_tablet_id == tablet->tablet_id() || target_table_id == tablet->table_id()) {
743
168k
            return Status::InternalError(
744
168k
                    "[sync_tablet_rowsets_unlocked] injected error for testing");
745
168k
        }
746
168k
    });
747
748
168k
    MetaServiceProxy* proxy;
749
168k
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
750
168k
    std::string tablet_info =
751
168k
            fmt::format("tablet_id={} table_id={} index_id={} partition_id={}", tablet->tablet_id(),
752
168k
                        tablet->table_id(), tablet->index_id(), tablet->partition_id());
753
168k
    int tried = 0;
754
168k
    while (true) {
755
167k
        std::shared_ptr<MetaService_Stub> stub;
756
167k
        RETURN_IF_ERROR(proxy->get(&stub));
757
167k
        brpc::Controller cntl;
758
167k
        cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
759
167k
        GetRowsetRequest req;
760
167k
        GetRowsetResponse resp;
761
762
167k
        int64_t tablet_id = tablet->tablet_id();
763
167k
        int64_t table_id = tablet->table_id();
764
167k
        int64_t index_id = tablet->index_id();
765
167k
        req.set_cloud_unique_id(config::cloud_unique_id);
766
167k
        auto* idx = req.mutable_idx();
767
167k
        idx->set_tablet_id(tablet_id);
768
167k
        idx->set_table_id(table_id);
769
167k
        idx->set_index_id(index_id);
770
167k
        idx->set_partition_id(tablet->partition_id());
771
167k
        {
772
167k
            auto lock_start = std::chrono::steady_clock::now();
773
167k
            std::shared_lock rlock(tablet->get_header_lock());
774
167k
            if (sync_stats) {
775
16.6k
                sync_stats->meta_lock_wait_ns +=
776
16.6k
                        std::chrono::duration_cast<std::chrono::nanoseconds>(
777
16.6k
                                std::chrono::steady_clock::now() - lock_start)
778
16.6k
                                .count();
779
16.6k
            }
780
167k
            if (options.full_sync) {
781
2
                req.set_start_version(0);
782
167k
            } else {
783
167k
                req.set_start_version(tablet->max_version_unlocked() + 1);
784
167k
            }
785
167k
            req.set_base_compaction_cnt(tablet->base_compaction_cnt());
786
167k
            req.set_cumulative_compaction_cnt(tablet->cumulative_compaction_cnt());
787
167k
            req.set_full_compaction_cnt(tablet->full_compaction_cnt());
788
167k
            req.set_cumulative_point(tablet->cumulative_layer_point());
789
167k
        }
790
167k
        req.set_end_version(-1);
791
18.4E
        VLOG_DEBUG << "send GetRowsetRequest: " << req.ShortDebugString();
792
793
        // Host-level rate limiting for get_rowset
794
167k
        if (host_level_ms_rpc_rate_limiters_) {
795
167k
            host_level_ms_rpc_rate_limiters_->limit(MetaServiceRPC::GET_ROWSET);
796
167k
        }
797
798
167k
        auto start = std::chrono::steady_clock::now();
799
167k
        call_ms(stub.get(), &MetaService_Stub::get_rowset, &cntl, req, &resp);
800
167k
        auto end = std::chrono::steady_clock::now();
801
167k
        int64_t latency = cntl.latency_us();
802
167k
        _get_rowset_latency << latency;
803
167k
        int retry_times = config::meta_service_rpc_retry_times;
804
167k
        if (cntl.Failed()) {
805
0
            proxy->set_unhealthy();
806
0
            if (tried++ < retry_times) {
807
0
                auto rng = make_random_engine();
808
0
                std::uniform_int_distribution<uint32_t> u(20, 200);
809
0
                std::uniform_int_distribution<uint32_t> u1(500, 1000);
810
0
                uint32_t duration_ms = tried >= 100 ? u(rng) : u1(rng);
811
0
                bthread_usleep(duration_ms * 1000);
812
0
                LOG_INFO("failed to get rowset meta, " + tablet_info)
813
0
                        .tag("reason", cntl.ErrorText())
814
0
                        .tag("tried", tried)
815
0
                        .tag("sleep", duration_ms);
816
0
                continue;
817
0
            }
818
0
            return Status::RpcError("failed to get rowset meta: {}", cntl.ErrorText());
819
0
        }
820
167k
        if (resp.status().code() == MetaServiceCode::TABLET_NOT_FOUND) {
821
0
            LOG(WARNING) << "failed to get rowset meta, err=" << resp.status().msg() << " "
822
0
                         << tablet_info;
823
0
            return Status::NotFound("failed to get rowset meta: {}, {}", resp.status().msg(),
824
0
                                    tablet_info);
825
0
        }
826
167k
        if (resp.status().code() == MetaServiceCode::MS_TOO_BUSY) {
827
            // MS_BUSY should also be retried
828
0
            if (ms_backpressure_handler_) {
829
0
                ms_backpressure_handler_->on_ms_busy();
830
0
            }
831
0
            if (tried++ < retry_times) {
832
0
                auto rng = make_random_engine();
833
0
                std::uniform_int_distribution<uint32_t> u(20, 200);
834
0
                std::uniform_int_distribution<uint32_t> u1(500, 1000);
835
0
                uint32_t duration_ms = tried >= 100 ? u(rng) : u1(rng);
836
0
                bthread_usleep(duration_ms * 1000);
837
0
                LOG_INFO("meta service is too busy when getting rowset meta, " + tablet_info)
838
0
                        .tag("reason", resp.status().msg())
839
0
                        .tag("tried", tried)
840
0
                        .tag("sleep", duration_ms);
841
0
                continue;
842
0
            }
843
0
            return Status::RpcError("failed to get rowset meta: {}", resp.status().msg());
844
0
        }
845
167k
        if (resp.status().code() != MetaServiceCode::OK) {
846
0
            LOG(WARNING) << " failed to get rowset meta, err=" << resp.status().msg() << " "
847
0
                         << tablet_info;
848
0
            return Status::InternalError("failed to get rowset meta: {}, {}", resp.status().msg(),
849
0
                                         tablet_info);
850
0
        }
851
167k
        if (latency > 100 * 1000) { // 100ms
852
26
            LOG(INFO) << "finish get_rowset rpc. rowset_meta.size()=" << resp.rowset_meta().size()
853
26
                      << ", latency=" << latency << "us"
854
26
                      << " " << tablet_info;
855
167k
        } else {
856
167k
            LOG_EVERY_N(INFO, 100)
857
1.67k
                    << "finish get_rowset rpc. rowset_meta.size()=" << resp.rowset_meta().size()
858
1.67k
                    << ", latency=" << latency << "us"
859
1.67k
                    << " " << tablet_info;
860
167k
        }
861
862
167k
        int64_t now = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
863
167k
        tablet->last_sync_time_s = now;
864
865
167k
        if (sync_stats) {
866
16.6k
            sync_stats->get_remote_rowsets_rpc_ns +=
867
16.6k
                    std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
868
16.6k
            sync_stats->get_remote_rowsets_num += resp.rowset_meta().size();
869
16.6k
        }
870
871
        // If is mow, the tablet has no delete bitmap in base rowsets.
872
        // So dont need to sync it.
873
168k
        if (options.sync_delete_bitmap && tablet->enable_unique_key_merge_on_write() &&
874
167k
            tablet->tablet_state() == TABLET_RUNNING) {
875
37.2k
            DBUG_EXECUTE_IF("CloudMetaMgr::sync_tablet_rowsets.sync_tablet_delete_bitmap.block",
876
37.2k
                            DBUG_BLOCK);
877
37.2k
            DeleteBitmap delete_bitmap(tablet_id);
878
37.2k
            int64_t old_max_version = req.start_version() - 1;
879
37.2k
            auto read_version = config::delete_bitmap_store_read_version;
880
37.2k
            auto st = sync_tablet_delete_bitmap(tablet, old_max_version, resp.rowset_meta(),
881
37.2k
                                                resp.stats(), req.idx(), &delete_bitmap,
882
37.2k
                                                options.full_sync, sync_stats, read_version, false);
883
37.2k
            if (st.is<ErrorCode::ROWSETS_EXPIRED>() && tried++ < retry_times) {
884
0
                LOG_INFO("rowset meta is expired, need to retry, " + tablet_info)
885
0
                        .tag("tried", tried)
886
0
                        .error(st);
887
0
                continue;
888
0
            }
889
37.2k
            if (!st.ok()) {
890
0
                LOG_WARNING("failed to get delete bitmap, " + tablet_info).error(st);
891
0
                return st;
892
0
            }
893
37.2k
            tablet->tablet_meta()->delete_bitmap().merge(delete_bitmap);
894
37.2k
            RETURN_IF_ERROR(_log_mow_delete_bitmap(tablet, resp, delete_bitmap, old_max_version,
895
37.2k
                                                   options.full_sync, read_version));
896
37.2k
            RETURN_IF_ERROR(
897
37.2k
                    _check_delete_bitmap_v2_correctness(tablet, req, resp, old_max_version));
898
37.2k
        }
899
167k
        DBUG_EXECUTE_IF("CloudMetaMgr::sync_tablet_rowsets.before.modify_tablet_meta", {
900
167k
            auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
901
167k
            if (target_tablet_id == tablet->tablet_id()) {
902
167k
                DBUG_BLOCK
903
167k
            }
904
167k
        });
905
167k
        {
906
167k
            const auto& stats = resp.stats();
907
167k
            auto lock_start = std::chrono::steady_clock::now();
908
167k
            std::unique_lock wlock(tablet->get_header_lock());
909
167k
            if (sync_stats) {
910
16.6k
                sync_stats->meta_lock_wait_ns +=
911
16.6k
                        std::chrono::duration_cast<std::chrono::nanoseconds>(
912
16.6k
                                std::chrono::steady_clock::now() - lock_start)
913
16.6k
                                .count();
914
16.6k
            }
915
916
            // ATTN: we are facing following data race
917
            //
918
            // resp_base_compaction_cnt=0|base_compaction_cnt=0|resp_cumulative_compaction_cnt=0|cumulative_compaction_cnt=1|resp_max_version=11|max_version=8
919
            //
920
            //   BE-compaction-thread                 meta-service                                     BE-query-thread
921
            //            |                                |                                                |
922
            //    local   |    commit cumu-compaction      |                                                |
923
            //   cc_cnt=0 |  --------------------------->  |     sync rowset (long rpc, local cc_cnt=0 )    |   local
924
            //            |                                |  <-----------------------------------------    |  cc_cnt=0
925
            //            |                                |  -.                                            |
926
            //    local   |       done cc_cnt=1            |    \                                           |
927
            //   cc_cnt=1 |  <---------------------------  |     \                                          |
928
            //            |                                |      \  returned with resp cc_cnt=0 (snapshot) |
929
            //            |                                |       '------------------------------------>   |   local
930
            //            |                                |                                                |  cc_cnt=1
931
            //            |                                |                                                |
932
            //            |                                |                                                |  CHECK FAIL
933
            //            |                                |                                                |  need retry
934
            // To get rid of just retry syncing tablet
935
167k
            if (stats.base_compaction_cnt() < tablet->base_compaction_cnt() ||
936
168k
                stats.cumulative_compaction_cnt() < tablet->cumulative_compaction_cnt())
937
0
                    [[unlikely]] {
938
                // stale request, ignore
939
0
                LOG_WARNING("stale get rowset meta request " + tablet_info)
940
0
                        .tag("resp_base_compaction_cnt", stats.base_compaction_cnt())
941
0
                        .tag("base_compaction_cnt", tablet->base_compaction_cnt())
942
0
                        .tag("resp_cumulative_compaction_cnt", stats.cumulative_compaction_cnt())
943
0
                        .tag("cumulative_compaction_cnt", tablet->cumulative_compaction_cnt())
944
0
                        .tag("tried", tried);
945
0
                if (tried++ < 10) continue;
946
0
                return Status::OK();
947
0
            }
948
167k
            std::vector<RowsetSharedPtr> rowsets;
949
167k
            rowsets.reserve(resp.rowset_meta().size());
950
167k
            for (const auto& cloud_rs_meta_pb : resp.rowset_meta()) {
951
127k
                VLOG_DEBUG << "get rowset meta, tablet_id=" << cloud_rs_meta_pb.tablet_id()
952
265
                           << ", version=[" << cloud_rs_meta_pb.start_version() << '-'
953
265
                           << cloud_rs_meta_pb.end_version() << ']';
954
127k
                auto existed_rowset = tablet->get_rowset_by_version(
955
127k
                        {cloud_rs_meta_pb.start_version(), cloud_rs_meta_pb.end_version()});
956
127k
                if (existed_rowset &&
957
127k
                    existed_rowset->rowset_id().to_string() == cloud_rs_meta_pb.rowset_id_v2()) {
958
0
                    continue; // Same rowset, skip it
959
0
                }
960
127k
                RowsetMetaPB meta_pb = cloud_rowset_meta_to_doris(cloud_rs_meta_pb);
961
127k
                auto rs_meta = std::make_shared<RowsetMeta>();
962
127k
                rs_meta->init_from_pb(meta_pb);
963
127k
                RowsetSharedPtr rowset;
964
                // schema is nullptr implies using RowsetMeta.tablet_schema
965
127k
                Status s = RowsetFactory::create_rowset(nullptr, "", rs_meta, &rowset);
966
127k
                if (!s.ok()) {
967
0
                    LOG_WARNING("create rowset").tag("status", s);
968
0
                    return s;
969
0
                }
970
127k
                rowsets.push_back(std::move(rowset));
971
127k
            }
972
167k
            if (!rowsets.empty()) {
973
                // `rowsets.empty()` could happen after doing EMPTY_CUMULATIVE compaction. e.g.:
974
                //   BE has [0-1][2-11][12-12], [12-12] is delete predicate, cp is 2;
975
                //   after doing EMPTY_CUMULATIVE compaction, MS cp is 13, get_rowset will return [2-11][12-12].
976
121k
                bool version_overlap =
977
121k
                        tablet->max_version_unlocked() >= rowsets.front()->start_version();
978
121k
                tablet->add_rowsets(std::move(rowsets), version_overlap, wlock,
979
121k
                                    options.warmup_delta_data ||
980
121k
                                            config::enable_warmup_immediately_on_new_rowset);
981
121k
            }
982
983
            // Fill version holes
984
167k
            int64_t partition_max_version =
985
167k
                    resp.has_partition_max_version() ? resp.partition_max_version() : -1;
986
167k
            RETURN_IF_ERROR(fill_version_holes(tablet, partition_max_version, wlock));
987
988
167k
            tablet->last_base_compaction_success_time_ms = stats.last_base_compaction_time_ms();
989
167k
            tablet->last_cumu_compaction_success_time_ms = stats.last_cumu_compaction_time_ms();
990
167k
            tablet->set_base_compaction_cnt(stats.base_compaction_cnt());
991
167k
            tablet->set_cumulative_compaction_cnt(stats.cumulative_compaction_cnt());
992
167k
            tablet->set_full_compaction_cnt(stats.full_compaction_cnt());
993
167k
            tablet->set_cumulative_layer_point(stats.cumulative_point());
994
167k
            tablet->reset_approximate_stats(stats.num_rowsets(), stats.num_segments(),
995
167k
                                            stats.num_rows(), stats.data_size());
996
997
            // Sync last active cluster info for compaction read-write separation
998
167k
            if (config::enable_compaction_rw_separation && stats.has_last_active_cluster_id()) {
999
12.0k
                tablet->set_last_active_cluster_info(stats.last_active_cluster_id(),
1000
12.0k
                                                     stats.last_active_time_ms());
1001
12.0k
            }
1002
167k
        }
1003
0
        return Status::OK();
1004
167k
    }
1005
168k
}
1006
1007
bool CloudMetaMgr::sync_tablet_delete_bitmap_by_cache(CloudTablet* tablet,
1008
                                                      std::ranges::range auto&& rs_metas,
1009
26.2k
                                                      DeleteBitmap* delete_bitmap) {
1010
26.2k
    std::set<int64_t> txn_processed;
1011
26.4k
    for (auto& rs_meta : rs_metas) {
1012
26.4k
        auto txn_id = rs_meta.txn_id();
1013
26.4k
        if (txn_processed.find(txn_id) != txn_processed.end()) {
1014
0
            continue;
1015
0
        }
1016
26.4k
        txn_processed.insert(txn_id);
1017
26.4k
        DeleteBitmapPtr tmp_delete_bitmap;
1018
26.4k
        std::shared_ptr<PublishStatus> publish_status =
1019
26.4k
                std::make_shared<PublishStatus>(PublishStatus::INIT);
1020
26.4k
        CloudStorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_cloud();
1021
26.4k
        Status status = engine.txn_delete_bitmap_cache().get_delete_bitmap(
1022
26.4k
                txn_id, tablet->tablet_id(), &tmp_delete_bitmap, nullptr, &publish_status);
1023
        // CloudMetaMgr::sync_tablet_delete_bitmap_by_cache() is called after we sync rowsets from meta services.
1024
        // If the control flows reaches here, it's gauranteed that the rowsets is commited in meta services, so we can
1025
        // use the delete bitmap from cache directly if *publish_status == PublishStatus::SUCCEED without checking other
1026
        // stats(version or compaction stats)
1027
26.4k
        if (status.ok() && *publish_status == PublishStatus::SUCCEED) {
1028
            // tmp_delete_bitmap contains sentinel marks, we should remove it before merge it to delete bitmap.
1029
            // Also, the version of delete bitmap key in tmp_delete_bitmap is DeleteBitmap::TEMP_VERSION_COMMON,
1030
            // we should replace it with the rowset's real version
1031
283
            DCHECK(rs_meta.start_version() == rs_meta.end_version());
1032
283
            int64_t rowset_version = rs_meta.start_version();
1033
1.91k
            for (const auto& [delete_bitmap_key, bitmap_value] : tmp_delete_bitmap->delete_bitmap) {
1034
                // skip sentinel mark, which is used for delete bitmap correctness check
1035
1.91k
                if (std::get<1>(delete_bitmap_key) != DeleteBitmap::INVALID_SEGMENT_ID) {
1036
188
                    delete_bitmap->merge({std::get<0>(delete_bitmap_key),
1037
188
                                          std::get<1>(delete_bitmap_key), rowset_version},
1038
188
                                         bitmap_value);
1039
188
                }
1040
1.91k
            }
1041
283
            engine.txn_delete_bitmap_cache().remove_unused_tablet_txn_info(txn_id,
1042
283
                                                                           tablet->tablet_id());
1043
26.1k
        } else {
1044
26.1k
            LOG_EVERY_N(INFO, 20)
1045
1.29k
                    << "delete bitmap not found in cache, will sync rowset to get. tablet_id= "
1046
1.29k
                    << tablet->tablet_id() << ", txn_id=" << txn_id << ", status=" << status;
1047
26.1k
            return false;
1048
26.1k
        }
1049
26.4k
    }
1050
122
    return true;
1051
26.2k
}
1052
1053
Status CloudMetaMgr::_get_delete_bitmap_from_ms(GetDeleteBitmapRequest& req,
1054
26.4k
                                                GetDeleteBitmapResponse& res) {
1055
18.4E
    VLOG_DEBUG << "send GetDeleteBitmapRequest: " << req.ShortDebugString();
1056
26.4k
    TEST_SYNC_POINT_CALLBACK("CloudMetaMgr::_get_delete_bitmap_from_ms", &req, &res);
1057
1058
26.4k
    auto st = retry_rpc(MetaServiceRPC::GET_DELETE_BITMAP, req, &res,
1059
26.4k
                        &MetaService_Stub::get_delete_bitmap,
1060
26.4k
                        {
1061
26.4k
                                .host_limiters = host_level_ms_rpc_rate_limiters_,
1062
26.4k
                                .backpressure_handler = ms_backpressure_handler_,
1063
26.4k
                        });
1064
26.4k
    if (st.code() == ErrorCode::THRIFT_RPC_ERROR) {
1065
0
        return st;
1066
0
    }
1067
1068
26.4k
    if (res.status().code() == MetaServiceCode::TABLET_NOT_FOUND) {
1069
1
        return Status::NotFound("failed to get delete bitmap: {}", res.status().msg());
1070
1
    }
1071
    // The delete bitmap of stale rowsets will be removed when commit compaction job,
1072
    // then delete bitmap of stale rowsets cannot be obtained. But the rowsets obtained
1073
    // by sync_tablet_rowsets may include these stale rowsets. When this case happend, the
1074
    // error code of ROWSETS_EXPIRED will be returned, we need to retry sync rowsets again.
1075
    //
1076
    // Be query thread             meta-service          Be compaction thread
1077
    //      |                            |                         |
1078
    //      |        get rowset          |                         |
1079
    //      |--------------------------->|                         |
1080
    //      |    return get rowset       |                         |
1081
    //      |<---------------------------|                         |
1082
    //      |                            |        commit job       |
1083
    //      |                            |<------------------------|
1084
    //      |                            |    return commit job    |
1085
    //      |                            |------------------------>|
1086
    //      |      get delete bitmap     |                         |
1087
    //      |--------------------------->|                         |
1088
    //      |  return get delete bitmap  |                         |
1089
    //      |<---------------------------|                         |
1090
    //      |                            |                         |
1091
26.4k
    if (res.status().code() == MetaServiceCode::ROWSETS_EXPIRED) {
1092
0
        return Status::Error<ErrorCode::ROWSETS_EXPIRED, false>("failed to get delete bitmap: {}",
1093
0
                                                                res.status().msg());
1094
0
    }
1095
26.4k
    if (res.status().code() != MetaServiceCode::OK) {
1096
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to get delete bitmap: {}",
1097
0
                                                               res.status().msg());
1098
0
    }
1099
26.4k
    return Status::OK();
1100
26.4k
}
1101
1102
Status CloudMetaMgr::_get_delete_bitmap_from_ms_by_batch(GetDeleteBitmapRequest& req,
1103
                                                         GetDeleteBitmapResponse& res,
1104
26.0k
                                                         int64_t bytes_threadhold) {
1105
26.0k
    std::unordered_set<std::string> finished_rowset_ids {};
1106
26.0k
    int count = 0;
1107
26.3k
    do {
1108
26.3k
        GetDeleteBitmapRequest cur_req;
1109
26.3k
        GetDeleteBitmapResponse cur_res;
1110
1111
26.3k
        cur_req.set_cloud_unique_id(config::cloud_unique_id);
1112
26.3k
        cur_req.set_tablet_id(req.tablet_id());
1113
26.3k
        cur_req.set_base_compaction_cnt(req.base_compaction_cnt());
1114
26.3k
        cur_req.set_cumulative_compaction_cnt(req.cumulative_compaction_cnt());
1115
26.3k
        cur_req.set_cumulative_point(req.cumulative_point());
1116
26.3k
        *(cur_req.mutable_idx()) = req.idx();
1117
26.3k
        cur_req.set_store_version(req.store_version());
1118
26.5k
        if (bytes_threadhold > 0) {
1119
26.5k
            cur_req.set_dbm_bytes_threshold(bytes_threadhold);
1120
26.5k
        }
1121
56.8k
        for (int i = 0; i < req.rowset_ids_size(); i++) {
1122
30.5k
            if (!finished_rowset_ids.contains(req.rowset_ids(i))) {
1123
29.5k
                cur_req.add_rowset_ids(req.rowset_ids(i));
1124
29.5k
                cur_req.add_begin_versions(req.begin_versions(i));
1125
29.5k
                cur_req.add_end_versions(req.end_versions(i));
1126
29.5k
            }
1127
30.5k
        }
1128
1129
26.3k
        RETURN_IF_ERROR(_get_delete_bitmap_from_ms(cur_req, cur_res));
1130
26.3k
        ++count;
1131
1132
        // v1 delete bitmap
1133
26.3k
        res.mutable_rowset_ids()->MergeFrom(cur_res.rowset_ids());
1134
26.3k
        res.mutable_segment_ids()->MergeFrom(cur_res.segment_ids());
1135
26.3k
        res.mutable_versions()->MergeFrom(cur_res.versions());
1136
26.3k
        res.mutable_segment_delete_bitmaps()->MergeFrom(cur_res.segment_delete_bitmaps());
1137
1138
        // v2 delete bitmap
1139
26.3k
        res.mutable_delta_rowset_ids()->MergeFrom(cur_res.delta_rowset_ids());
1140
26.3k
        res.mutable_delete_bitmap_storages()->MergeFrom(cur_res.delete_bitmap_storages());
1141
1142
28.7k
        for (const auto& rowset_id : cur_res.returned_rowset_ids()) {
1143
28.7k
            finished_rowset_ids.insert(rowset_id);
1144
28.7k
        }
1145
1146
26.3k
        bool has_more = cur_res.has_has_more() && cur_res.has_more();
1147
26.3k
        if (!has_more) {
1148
26.2k
            break;
1149
26.2k
        }
1150
86
        LOG_INFO("batch get delete bitmap, progress={}/{}", finished_rowset_ids.size(),
1151
86
                 req.rowset_ids_size())
1152
86
                .tag("tablet_id", req.tablet_id())
1153
86
                .tag("cur_returned_rowsets", cur_res.returned_rowset_ids_size())
1154
86
                .tag("rpc_count", count);
1155
86
    } while (finished_rowset_ids.size() < req.rowset_ids_size());
1156
25.9k
    return Status::OK();
1157
26.0k
}
1158
1159
Status CloudMetaMgr::sync_tablet_delete_bitmap(CloudTablet* tablet, int64_t old_max_version,
1160
                                               std::ranges::range auto&& rs_metas,
1161
                                               const TabletStatsPB& stats, const TabletIndexPB& idx,
1162
                                               DeleteBitmap* delete_bitmap, bool full_sync,
1163
                                               SyncRowsetStats* sync_stats, int32_t read_version,
1164
37.1k
                                               bool full_sync_v2) {
1165
37.1k
    if (rs_metas.empty()) {
1166
10.7k
        return Status::OK();
1167
10.7k
    }
1168
1169
26.3k
    if (!full_sync && config::enable_sync_tablet_delete_bitmap_by_cache &&
1170
26.3k
        sync_tablet_delete_bitmap_by_cache(tablet, rs_metas, delete_bitmap)) {
1171
248
        if (sync_stats) {
1172
70
            sync_stats->get_local_delete_bitmap_rowsets_num += rs_metas.size();
1173
70
        }
1174
248
        return Status::OK();
1175
26.0k
    } else {
1176
26.0k
        DeleteBitmapPtr new_delete_bitmap = std::make_shared<DeleteBitmap>(tablet->tablet_id());
1177
26.0k
        *delete_bitmap = *new_delete_bitmap;
1178
26.0k
    }
1179
1180
26.0k
    if (read_version == 2 && config::delete_bitmap_store_write_version == 1) {
1181
0
        return Status::InternalError(
1182
0
                "please set delete_bitmap_store_read_version to 1 or 3 because "
1183
0
                "delete_bitmap_store_write_version is 1");
1184
26.0k
    } else if (read_version == 1 && config::delete_bitmap_store_write_version == 2) {
1185
0
        return Status::InternalError(
1186
0
                "please set delete_bitmap_store_read_version to 2 or 3 because "
1187
0
                "delete_bitmap_store_write_version is 2");
1188
0
    }
1189
1190
26.0k
    int64_t new_max_version = std::max(old_max_version, rs_metas.rbegin()->end_version());
1191
    // When there are many delete bitmaps that need to be synchronized, it
1192
    // may take a longer time, especially when loading the tablet for the
1193
    // first time, so set a relatively long timeout time.
1194
26.0k
    GetDeleteBitmapRequest req;
1195
26.0k
    GetDeleteBitmapResponse res;
1196
26.0k
    req.set_cloud_unique_id(config::cloud_unique_id);
1197
26.0k
    req.set_tablet_id(tablet->tablet_id());
1198
26.0k
    req.set_base_compaction_cnt(stats.base_compaction_cnt());
1199
26.0k
    req.set_cumulative_compaction_cnt(stats.cumulative_compaction_cnt());
1200
26.0k
    req.set_cumulative_point(stats.cumulative_point());
1201
26.0k
    *(req.mutable_idx()) = idx;
1202
26.0k
    req.set_store_version(read_version);
1203
    // New rowset sync all versions of delete bitmap
1204
28.5k
    for (const auto& rs_meta : rs_metas) {
1205
28.5k
        req.add_rowset_ids(rs_meta.rowset_id_v2());
1206
28.5k
        req.add_begin_versions(0);
1207
28.5k
        req.add_end_versions(new_max_version);
1208
28.5k
    }
1209
1210
26.2k
    if (!full_sync_v2) {
1211
        // old rowset sync incremental versions of delete bitmap
1212
26.2k
        if (old_max_version > 0 && old_max_version < new_max_version) {
1213
12
            RowsetIdUnorderedSet all_rs_ids;
1214
12
            RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1215
168
            for (const auto& rs_id : all_rs_ids) {
1216
168
                req.add_rowset_ids(rs_id.to_string());
1217
168
                req.add_begin_versions(old_max_version + 1);
1218
168
                req.add_end_versions(new_max_version);
1219
168
            }
1220
12
        }
1221
18.4E
    } else {
1222
18.4E
        if (old_max_version > 0) {
1223
0
            RowsetIdUnorderedSet all_rs_ids;
1224
0
            RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1225
0
            for (const auto& rs_id : all_rs_ids) {
1226
0
                req.add_rowset_ids(rs_id.to_string());
1227
0
                req.add_begin_versions(0);
1228
0
                req.add_end_versions(new_max_version);
1229
0
            }
1230
0
        }
1231
18.4E
    }
1232
26.0k
    if (sync_stats) {
1233
8.41k
        sync_stats->get_remote_delete_bitmap_rowsets_num += req.rowset_ids_size();
1234
8.41k
    }
1235
1236
26.0k
    auto start = std::chrono::steady_clock::now();
1237
26.1k
    if (config::enable_batch_get_delete_bitmap) {
1238
26.1k
        RETURN_IF_ERROR(_get_delete_bitmap_from_ms_by_batch(
1239
26.1k
                req, res, config::get_delete_bitmap_bytes_threshold));
1240
18.4E
    } else {
1241
18.4E
        RETURN_IF_ERROR(_get_delete_bitmap_from_ms(req, res));
1242
18.4E
    }
1243
26.0k
    auto end = std::chrono::steady_clock::now();
1244
1245
    // v1 delete bitmap
1246
26.0k
    const auto& rowset_ids = res.rowset_ids();
1247
26.0k
    const auto& segment_ids = res.segment_ids();
1248
26.0k
    const auto& vers = res.versions();
1249
26.0k
    const auto& delete_bitmaps = res.segment_delete_bitmaps();
1250
26.2k
    if (rowset_ids.size() != segment_ids.size() || rowset_ids.size() != vers.size() ||
1251
26.2k
        rowset_ids.size() != delete_bitmaps.size()) {
1252
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
1253
0
                "get delete bitmap data wrong,"
1254
0
                "rowset_ids.size={},segment_ids.size={},vers.size={},delete_bitmaps.size={}",
1255
0
                rowset_ids.size(), segment_ids.size(), vers.size(), delete_bitmaps.size());
1256
0
    }
1257
26.4k
    for (int i = 0; i < rowset_ids.size(); i++) {
1258
355
        RowsetId rst_id;
1259
355
        rst_id.init(rowset_ids[i]);
1260
355
        delete_bitmap->merge(
1261
355
                {rst_id, segment_ids[i], vers[i]},
1262
355
                roaring::Roaring::readSafe(delete_bitmaps[i].data(), delete_bitmaps[i].length()));
1263
355
    }
1264
    // v2 delete bitmap
1265
26.0k
    const auto& delta_rowset_ids = res.delta_rowset_ids();
1266
26.0k
    const auto& delete_bitmap_storages = res.delete_bitmap_storages();
1267
26.0k
    if (delta_rowset_ids.size() != delete_bitmap_storages.size()) {
1268
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
1269
0
                "get delete bitmap data wrong, delta_rowset_ids.size={}, "
1270
0
                "delete_bitmap_storages.size={}",
1271
0
                delta_rowset_ids.size(), delete_bitmap_storages.size());
1272
0
    }
1273
26.0k
    int64_t remote_delete_bitmap_bytes = 0;
1274
26.0k
    RETURN_IF_ERROR(_read_tablet_delete_bitmap_v2(tablet, old_max_version, rs_metas, delete_bitmap,
1275
26.0k
                                                  res, remote_delete_bitmap_bytes, full_sync_v2));
1276
1277
26.0k
    if (sync_stats) {
1278
8.41k
        sync_stats->get_remote_delete_bitmap_rpc_ns +=
1279
8.41k
                std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
1280
8.41k
        sync_stats->get_remote_delete_bitmap_key_count +=
1281
8.41k
                delete_bitmaps.size() + delete_bitmap_storages.size();
1282
8.41k
        for (const auto& dbm : delete_bitmaps) {
1283
340
            sync_stats->get_remote_delete_bitmap_bytes += dbm.length();
1284
340
        }
1285
8.41k
        sync_stats->get_remote_delete_bitmap_bytes += remote_delete_bitmap_bytes;
1286
8.41k
    }
1287
26.0k
    int64_t latency = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1288
26.0k
    if (latency > 100 * 1000) { // 100ms
1289
7
        LOG(INFO) << "finish get_delete_bitmap rpcs. rowset_ids.size()=" << rowset_ids.size()
1290
7
                  << ", delete_bitmaps.size()=" << delete_bitmaps.size()
1291
7
                  << ", delta_delete_bitmaps.size()=" << delta_rowset_ids.size()
1292
7
                  << ", latency=" << latency << "us, read_version=" << read_version;
1293
26.0k
    } else {
1294
26.0k
        LOG_EVERY_N(INFO, 100) << "finish get_delete_bitmap rpcs. rowset_ids.size()="
1295
258
                               << rowset_ids.size()
1296
258
                               << ", delete_bitmaps.size()=" << delete_bitmaps.size()
1297
258
                               << ", delta_delete_bitmaps.size()=" << delta_rowset_ids.size()
1298
258
                               << ", latency=" << latency << "us, read_version=" << read_version;
1299
26.0k
    }
1300
26.0k
    return Status::OK();
1301
26.0k
}
1302
1303
Status CloudMetaMgr::_check_delete_bitmap_v2_correctness(CloudTablet* tablet, GetRowsetRequest& req,
1304
                                                         GetRowsetResponse& resp,
1305
37.2k
                                                         int64_t old_max_version) {
1306
37.2k
    if (!config::enable_delete_bitmap_store_v2_check_correctness ||
1307
37.2k
        config::delete_bitmap_store_write_version == 1 || resp.rowset_meta().empty()) {
1308
37.2k
        return Status::OK();
1309
37.2k
    }
1310
18.4E
    int64_t tablet_id = tablet->tablet_id();
1311
18.4E
    int64_t new_max_version = std::max(old_max_version, resp.rowset_meta().rbegin()->end_version());
1312
    // rowset_id, num_segments
1313
18.4E
    std::vector<std::pair<RowsetId, int64_t>> all_rowsets;
1314
18.4E
    std::map<std::string, std::string> rowset_to_resource;
1315
18.4E
    for (const auto& rs_meta : resp.rowset_meta()) {
1316
0
        RowsetId rowset_id;
1317
0
        rowset_id.init(rs_meta.rowset_id_v2());
1318
0
        all_rowsets.emplace_back(std::make_pair(rowset_id, rs_meta.num_segments()));
1319
0
        rowset_to_resource[rs_meta.rowset_id_v2()] = rs_meta.resource_id();
1320
0
    }
1321
18.4E
    if (old_max_version > 0) {
1322
0
        RowsetIdUnorderedSet all_rs_ids;
1323
0
        RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1324
0
        for (auto& rowset : tablet->get_rowset_by_ids(&all_rs_ids)) {
1325
0
            all_rowsets.emplace_back(std::make_pair(rowset->rowset_id(), rowset->num_segments()));
1326
0
            rowset_to_resource[rowset->rowset_id().to_string()] =
1327
0
                    rowset->rowset_meta()->resource_id();
1328
0
        }
1329
0
    }
1330
1331
18.4E
    auto compare_delete_bitmap = [&](DeleteBitmap* delete_bitmap, int version) {
1332
0
        bool success = true;
1333
0
        for (auto& [rs_id, num_segments] : all_rowsets) {
1334
0
            for (int seg_id = 0; seg_id < num_segments; ++seg_id) {
1335
0
                DeleteBitmap::BitmapKey key = {rs_id, seg_id, new_max_version};
1336
0
                auto dm1 = tablet->tablet_meta()->delete_bitmap().get_agg(key);
1337
0
                auto dm2 = delete_bitmap->get_agg_without_cache(key);
1338
0
                if (*dm1 != *dm2) {
1339
0
                    success = false;
1340
0
                    LOG(WARNING) << "failed to check delete bitmap correctness by v"
1341
0
                                 << std::to_string(version) << ", tablet_id=" << tablet->tablet_id()
1342
0
                                 << ", rowset_id=" << rs_id.to_string() << ", segment_id=" << seg_id
1343
0
                                 << ", max_version=" << new_max_version
1344
0
                                 << ". size1=" << dm1->cardinality()
1345
0
                                 << ", size2=" << dm2->cardinality();
1346
0
                }
1347
0
            }
1348
0
        }
1349
0
        if (success) {
1350
0
            LOG(INFO) << "succeed to check delete bitmap correctness by v"
1351
0
                      << std::to_string(version) << ", tablet_id=" << tablet->tablet_id()
1352
0
                      << ", max_version=" << new_max_version;
1353
0
        }
1354
0
    };
1355
1356
18.4E
    DeleteBitmap full_delete_bitmap(tablet_id);
1357
18.4E
    auto st = sync_tablet_delete_bitmap(tablet, old_max_version, resp.rowset_meta(), resp.stats(),
1358
18.4E
                                        req.idx(), &full_delete_bitmap, false, nullptr, 2, true);
1359
18.4E
    if (!st.ok()) {
1360
0
        LOG_WARNING("failed to check delete bitmap correctness by v2")
1361
0
                .tag("tablet", tablet->tablet_id())
1362
0
                .error(st);
1363
18.4E
    } else {
1364
18.4E
        compare_delete_bitmap(&full_delete_bitmap, 2);
1365
18.4E
    }
1366
18.4E
    return Status::OK();
1367
18.4E
}
1368
1369
Status CloudMetaMgr::_read_tablet_delete_bitmap_v2(CloudTablet* tablet, int64_t old_max_version,
1370
                                                   std::ranges::range auto&& rs_metas,
1371
                                                   DeleteBitmap* delete_bitmap,
1372
                                                   GetDeleteBitmapResponse& res,
1373
                                                   int64_t& remote_delete_bitmap_bytes,
1374
26.1k
                                                   bool full_sync_v2) {
1375
26.1k
    if (res.delta_rowset_ids().empty()) {
1376
26.1k
        return Status::OK();
1377
26.1k
    }
1378
18.4E
    const auto& rowset_ids = res.delta_rowset_ids();
1379
18.4E
    const auto& delete_bitmap_storages = res.delete_bitmap_storages();
1380
18.4E
    RowsetIdUnorderedSet all_rs_ids;
1381
18.4E
    std::map<std::string, std::string> rowset_to_resource;
1382
18.4E
    if (old_max_version > 0) {
1383
0
        RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1384
0
        if (full_sync_v2) {
1385
0
            for (auto& rowset : tablet->get_rowset_by_ids(&all_rs_ids)) {
1386
0
                rowset_to_resource[rowset->rowset_id().to_string()] =
1387
0
                        rowset->rowset_meta()->resource_id();
1388
0
            }
1389
0
        }
1390
0
    }
1391
18.4E
    for (const auto& rs_meta : rs_metas) {
1392
0
        RowsetId rs_id;
1393
0
        rs_id.init(rs_meta.rowset_id_v2());
1394
0
        all_rs_ids.emplace(rs_id);
1395
0
        rowset_to_resource[rs_meta.rowset_id_v2()] = rs_meta.resource_id();
1396
0
    }
1397
18.4E
    if (config::enable_mow_verbose_log) {
1398
0
        LOG(INFO) << "read delete bitmap for tablet_id=" << tablet->tablet_id()
1399
0
                  << ", old_max_version=" << old_max_version
1400
0
                  << ", new rowset num=" << rs_metas.size()
1401
0
                  << ", rowset has delete bitmap num=" << rowset_ids.size()
1402
0
                  << ". all rowset num=" << all_rs_ids.size();
1403
0
    }
1404
1405
18.4E
    std::mutex result_mtx;
1406
18.4E
    Status result;
1407
18.4E
    auto merge_delete_bitmap = [&](const std::string& rowset_id, DeleteBitmapPB& dbm) {
1408
0
        if (dbm.rowset_ids_size() != dbm.segment_ids_size() ||
1409
0
            dbm.rowset_ids_size() != dbm.versions_size() ||
1410
0
            dbm.rowset_ids_size() != dbm.segment_delete_bitmaps_size()) {
1411
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
1412
0
                    "get delete bitmap data wrong, rowset_id={}"
1413
0
                    "rowset_ids.size={},segment_ids.size={},vers.size={},delete_bitmaps.size={}",
1414
0
                    rowset_id, dbm.rowset_ids_size(), dbm.segment_ids_size(), dbm.versions_size(),
1415
0
                    dbm.segment_delete_bitmaps_size());
1416
0
        }
1417
0
        if (config::enable_mow_verbose_log) {
1418
0
            LOG(INFO) << "get delete bitmap for tablet_id=" << tablet->tablet_id()
1419
0
                      << ", rowset_id=" << rowset_id
1420
0
                      << ", delete_bitmap num=" << dbm.segment_delete_bitmaps_size();
1421
0
        }
1422
0
        std::lock_guard lock(result_mtx);
1423
0
        for (int j = 0; j < dbm.rowset_ids_size(); j++) {
1424
0
            RowsetId rst_id;
1425
0
            rst_id.init(dbm.rowset_ids(j));
1426
0
            if (!all_rs_ids.contains(rst_id)) {
1427
0
                LOG(INFO) << "skip merge delete bitmap for tablet_id=" << tablet->tablet_id()
1428
0
                          << ", rowset_id=" << rowset_id << ", unused rowset_id=" << rst_id;
1429
0
                continue;
1430
0
            }
1431
0
            delete_bitmap->merge(
1432
0
                    {rst_id, dbm.segment_ids(j), dbm.versions(j)},
1433
0
                    roaring::Roaring::readSafe(dbm.segment_delete_bitmaps(j).data(),
1434
0
                                               dbm.segment_delete_bitmaps(j).length()));
1435
0
            remote_delete_bitmap_bytes += dbm.segment_delete_bitmaps(j).length();
1436
0
        }
1437
0
        return Status::OK();
1438
0
    };
1439
18.4E
    auto get_delete_bitmap_from_file = [&](const std::string& rowset_id,
1440
18.4E
                                           const DeleteBitmapStoragePB& storage) {
1441
0
        if (config::enable_mow_verbose_log) {
1442
0
            LOG(INFO) << "get delete bitmap for tablet_id=" << tablet->tablet_id()
1443
0
                      << ", rowset_id=" << rowset_id << " from file"
1444
0
                      << ", is_packed=" << storage.has_packed_slice_location();
1445
0
        }
1446
0
        if (rowset_to_resource.find(rowset_id) == rowset_to_resource.end()) {
1447
0
            return Status::InternalError("vault id not found for tablet_id={}, rowset_id={}",
1448
0
                                         tablet->tablet_id(), rowset_id);
1449
0
        }
1450
0
        auto resource_id = rowset_to_resource[rowset_id];
1451
0
        CloudStorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_cloud();
1452
0
        auto storage_resource = engine.get_storage_resource(resource_id);
1453
0
        if (!storage_resource) {
1454
0
            return Status::InternalError("vault id not found, maybe not sync, vault id {}",
1455
0
                                         resource_id);
1456
0
        }
1457
1458
        // Use packed file reader if packed_slice_location is present
1459
0
        std::unique_ptr<DeleteBitmapFileReader> reader;
1460
0
        if (storage.has_packed_slice_location() &&
1461
0
            !storage.packed_slice_location().packed_file_path().empty()) {
1462
0
            reader = std::make_unique<DeleteBitmapFileReader>(tablet->tablet_id(), rowset_id,
1463
0
                                                              storage_resource,
1464
0
                                                              storage.packed_slice_location());
1465
0
        } else {
1466
0
            reader = std::make_unique<DeleteBitmapFileReader>(tablet->tablet_id(), rowset_id,
1467
0
                                                              storage_resource);
1468
0
        }
1469
1470
0
        RETURN_IF_ERROR(reader->init());
1471
0
        DeleteBitmapPB dbm;
1472
0
        RETURN_IF_ERROR(reader->read(dbm));
1473
0
        RETURN_IF_ERROR(reader->close());
1474
0
        return merge_delete_bitmap(rowset_id, dbm);
1475
0
    };
1476
18.4E
    CloudStorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_cloud();
1477
18.4E
    std::unique_ptr<ThreadPoolToken> token = engine.sync_delete_bitmap_thread_pool().new_token(
1478
18.4E
            ThreadPool::ExecutionMode::CONCURRENT);
1479
18.4E
    bthread::CountdownEvent wait {rowset_ids.size()};
1480
18.4E
    for (int i = 0; i < rowset_ids.size(); i++) {
1481
0
        auto& rowset_id = rowset_ids[i];
1482
0
        if (delete_bitmap_storages[i].store_in_fdb()) {
1483
0
            wait.signal();
1484
0
            DeleteBitmapPB dbm = delete_bitmap_storages[i].delete_bitmap();
1485
0
            RETURN_IF_ERROR(merge_delete_bitmap(rowset_id, dbm));
1486
0
        } else {
1487
0
            const auto& storage = delete_bitmap_storages[i];
1488
0
            auto submit_st = token->submit_func([&, rowset_id, storage]() {
1489
0
                auto status = get_delete_bitmap_from_file(rowset_id, storage);
1490
0
                if (!status.ok()) {
1491
0
                    LOG(WARNING) << "failed to get delete bitmap for tablet_id="
1492
0
                                 << tablet->tablet_id() << ", rowset_id=" << rowset_id
1493
0
                                 << " from file, st=" << status.to_string();
1494
0
                    std::lock_guard lock(result_mtx);
1495
0
                    if (result.ok()) {
1496
0
                        result = status;
1497
0
                    }
1498
0
                }
1499
0
                wait.signal();
1500
0
            });
1501
0
            RETURN_IF_ERROR(submit_st);
1502
0
        }
1503
0
    }
1504
    // wait for all finished
1505
18.4E
    wait.wait();
1506
18.4E
    token->wait();
1507
18.4E
    return result;
1508
18.4E
}
1509
1510
Status CloudMetaMgr::prepare_rowset(const RowsetMeta& rs_meta, const std::string& job_id,
1511
74.1k
                                    int64_t table_id, RowsetMetaSharedPtr* existed_rs_meta) {
1512
18.4E
    VLOG_DEBUG << "prepare rowset, tablet_id: " << rs_meta.tablet_id()
1513
18.4E
               << ", rowset_id: " << rs_meta.rowset_id() << " txn_id: " << rs_meta.txn_id();
1514
74.1k
    {
1515
74.1k
        Status ret_st;
1516
74.1k
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::prepare_rowset", ret_st);
1517
74.1k
    }
1518
74.1k
    CreateRowsetRequest req;
1519
74.1k
    CreateRowsetResponse resp;
1520
74.1k
    req.set_cloud_unique_id(config::cloud_unique_id);
1521
74.1k
    req.set_txn_id(rs_meta.txn_id());
1522
74.1k
    req.set_tablet_job_id(job_id);
1523
1524
74.1k
    RowsetMetaPB doris_rs_meta = rs_meta.get_rowset_pb(/*skip_schema=*/true);
1525
74.1k
    doris_rowset_meta_to_cloud(req.mutable_rowset_meta(), std::move(doris_rs_meta));
1526
1527
74.1k
    Status st =
1528
74.1k
            retry_rpc(MetaServiceRPC::PREPARE_ROWSET, req, &resp, &MetaService_Stub::prepare_rowset,
1529
74.1k
                      {
1530
74.1k
                              .host_limiters = host_level_ms_rpc_rate_limiters_,
1531
74.1k
                              .backpressure_handler = ms_backpressure_handler_,
1532
74.1k
                              .table_id = table_id,
1533
74.1k
                      });
1534
74.1k
    if (!st.ok() && resp.status().code() == MetaServiceCode::ALREADY_EXISTED) {
1535
1
        if (existed_rs_meta != nullptr && resp.has_existed_rowset_meta()) {
1536
1
            RowsetMetaPB doris_rs_meta_tmp =
1537
1
                    cloud_rowset_meta_to_doris(std::move(*resp.mutable_existed_rowset_meta()));
1538
1
            *existed_rs_meta = std::make_shared<RowsetMeta>();
1539
1
            (*existed_rs_meta)->init_from_pb(doris_rs_meta_tmp);
1540
1
        }
1541
1
        return Status::AlreadyExist("failed to prepare rowset: {}", resp.status().msg());
1542
1
    }
1543
74.1k
    return st;
1544
74.1k
}
1545
1546
Status CloudMetaMgr::commit_rowset(RowsetMeta& rs_meta, const std::string& job_id, int64_t table_id,
1547
73.9k
                                   RowsetMetaSharedPtr* existed_rs_meta) {
1548
18.4E
    VLOG_DEBUG << "commit rowset, tablet_id: " << rs_meta.tablet_id()
1549
18.4E
               << ", rowset_id: " << rs_meta.rowset_id() << " txn_id: " << rs_meta.txn_id();
1550
73.9k
    {
1551
73.9k
        Status ret_st;
1552
73.9k
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::commit_rowset", ret_st);
1553
73.9k
    }
1554
73.9k
    check_table_size_correctness(rs_meta);
1555
73.9k
    CreateRowsetRequest req;
1556
73.9k
    CreateRowsetResponse resp;
1557
73.9k
    req.set_cloud_unique_id(config::cloud_unique_id);
1558
73.9k
    req.set_txn_id(rs_meta.txn_id());
1559
73.9k
    req.set_tablet_job_id(job_id);
1560
1561
73.9k
    RowsetMetaPB rs_meta_pb = rs_meta.get_rowset_pb();
1562
73.9k
    doris_rowset_meta_to_cloud(req.mutable_rowset_meta(), std::move(rs_meta_pb));
1563
73.9k
    Status st =
1564
73.9k
            retry_rpc(MetaServiceRPC::COMMIT_ROWSET, req, &resp, &MetaService_Stub::commit_rowset,
1565
73.9k
                      {
1566
73.9k
                              .host_limiters = host_level_ms_rpc_rate_limiters_,
1567
73.9k
                              .backpressure_handler = ms_backpressure_handler_,
1568
73.9k
                              .table_id = table_id,
1569
73.9k
                      });
1570
73.9k
    if (!st.ok() && resp.status().code() == MetaServiceCode::ALREADY_EXISTED) {
1571
0
        if (existed_rs_meta != nullptr && resp.has_existed_rowset_meta()) {
1572
0
            RowsetMetaPB doris_rs_meta =
1573
0
                    cloud_rowset_meta_to_doris(std::move(*resp.mutable_existed_rowset_meta()));
1574
0
            *existed_rs_meta = std::make_shared<RowsetMeta>();
1575
0
            (*existed_rs_meta)->init_from_pb(doris_rs_meta);
1576
0
        }
1577
0
        return Status::AlreadyExist("failed to commit rowset: {}", resp.status().msg());
1578
0
    }
1579
73.9k
    int64_t timeout_ms = -1;
1580
    // if the `job_id` is not empty, it means this rowset was produced by a compaction job.
1581
73.9k
    if (config::enable_compaction_delay_commit_for_warm_up && !job_id.empty()) {
1582
        // 1. assume the download speed is 100MB/s
1583
        // 2. we double the download time as timeout for safety
1584
        // 3. for small rowsets, the timeout we calculate maybe quite small, so we need a min_time_out
1585
0
        const double speed_mbps = 100.0; // 100MB/s
1586
0
        const double safety_factor = 2.0;
1587
0
        timeout_ms = std::min(
1588
0
                std::max(static_cast<int64_t>(static_cast<double>(rs_meta.total_disk_size()) /
1589
0
                                              (speed_mbps * 1024 * 1024) * safety_factor * 1000),
1590
0
                         config::warm_up_rowset_sync_wait_min_timeout_ms),
1591
0
                config::warm_up_rowset_sync_wait_max_timeout_ms);
1592
0
        LOG(INFO) << "warm up rowset: " << rs_meta.version() << ", job_id: " << job_id
1593
0
                  << ", with timeout: " << timeout_ms << " ms";
1594
0
    }
1595
73.9k
    auto& manager = ExecEnv::GetInstance()->storage_engine().to_cloud().cloud_warm_up_manager();
1596
73.9k
    manager.warm_up_rowset(rs_meta, table_id, timeout_ms);
1597
73.9k
    return st;
1598
73.9k
}
1599
1600
36.7k
void CloudMetaMgr::cache_committed_rowset(RowsetMetaSharedPtr rs_meta, int64_t expiration_time) {
1601
    // For load-generated rowsets (job_id is empty), add to pending rowset manager
1602
    // so FE can notify BE to promote them later
1603
1604
    // TODO(bobhan1): copy rs_meta?
1605
36.7k
    int64_t txn_id = rs_meta->txn_id();
1606
36.7k
    int64_t tablet_id = rs_meta->tablet_id();
1607
36.7k
    ExecEnv::GetInstance()->storage_engine().to_cloud().committed_rs_mgr().add_committed_rowset(
1608
36.7k
            txn_id, tablet_id, std::move(rs_meta), expiration_time);
1609
36.7k
}
1610
1611
21
Status CloudMetaMgr::update_tmp_rowset(const RowsetMeta& rs_meta, int64_t table_id) {
1612
21
    VLOG_DEBUG << "update committed rowset, tablet_id: " << rs_meta.tablet_id()
1613
0
               << ", rowset_id: " << rs_meta.rowset_id();
1614
21
    CreateRowsetRequest req;
1615
21
    CreateRowsetResponse resp;
1616
21
    req.set_cloud_unique_id(config::cloud_unique_id);
1617
1618
    // Variant schema maybe updated, so we need to update the schema as well.
1619
    // The updated rowset meta after `rowset->merge_rowset_meta` in `BaseTablet::update_delete_bitmap`
1620
    // will be lost in `update_tmp_rowset` if skip_schema.So in order to keep the latest schema we should keep schema in update_tmp_rowset
1621
    // for variant type
1622
21
    bool skip_schema = rs_meta.tablet_schema()->num_variant_columns() == 0;
1623
21
    RowsetMetaPB rs_meta_pb = rs_meta.get_rowset_pb(skip_schema);
1624
21
    doris_rowset_meta_to_cloud(req.mutable_rowset_meta(), std::move(rs_meta_pb));
1625
21
    Status st = retry_rpc(MetaServiceRPC::UPDATE_TMP_ROWSET, req, &resp,
1626
21
                          &MetaService_Stub::update_tmp_rowset,
1627
21
                          {
1628
21
                                  .host_limiters = host_level_ms_rpc_rate_limiters_,
1629
21
                                  .backpressure_handler = ms_backpressure_handler_,
1630
21
                                  .table_id = table_id,
1631
21
                          });
1632
21
    if (!st.ok() && resp.status().code() == MetaServiceCode::ROWSET_META_NOT_FOUND) {
1633
0
        return Status::InternalError("failed to update committed rowset: {}", resp.status().msg());
1634
0
    }
1635
21
    return st;
1636
21
}
1637
1638
// async send TableStats(in res) to FE coz we are in streamload ctx, response to the user ASAP
1639
static void send_stats_to_fe_async(const int64_t db_id, const int64_t txn_id,
1640
                                   const std::string& label, CommitTxnResponse& res,
1641
6.91k
                                   const std::vector<int64_t>& tablet_ids) {
1642
6.91k
    std::string protobufBytes;
1643
6.91k
    if (txn_id != -1) {
1644
0
        res.SerializeToString(&protobufBytes);
1645
0
    }
1646
6.91k
    auto st = ExecEnv::GetInstance()->send_table_stats_thread_pool()->submit_func(
1647
6.92k
            [db_id, txn_id, label, protobufBytes, tablet_ids]() -> Status {
1648
6.92k
                TReportCommitTxnResultRequest request;
1649
6.92k
                TStatus result;
1650
1651
6.92k
                if (txn_id != -1 && protobufBytes.length() <= 0) {
1652
0
                    LOG(WARNING) << "protobufBytes: " << protobufBytes.length();
1653
0
                    return Status::OK(); // nobody cares the return status
1654
0
                }
1655
1656
6.92k
                request.__set_dbId(db_id);
1657
6.92k
                request.__set_txnId(txn_id);
1658
6.92k
                request.__set_label(label);
1659
6.92k
                request.__set_payload(protobufBytes);
1660
6.92k
                request.__set_tabletIds(tablet_ids);
1661
1662
6.92k
                Status status;
1663
6.92k
                int64_t duration_ns = 0;
1664
6.92k
                TNetworkAddress master_addr =
1665
6.92k
                        ExecEnv::GetInstance()->cluster_info()->master_fe_addr;
1666
6.92k
                if (master_addr.hostname.empty() || master_addr.port == 0) {
1667
0
                    status = Status::Error<SERVICE_UNAVAILABLE>(
1668
0
                            "Have not get FE Master heartbeat yet");
1669
6.92k
                } else {
1670
6.92k
                    SCOPED_RAW_TIMER(&duration_ns);
1671
1672
6.92k
                    RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
1673
6.92k
                            master_addr.hostname, master_addr.port,
1674
6.92k
                            [&request, &result](FrontendServiceConnection& client) {
1675
6.92k
                                client->reportCommitTxnResult(result, request);
1676
6.92k
                            }));
1677
1678
6.92k
                    status = Status::create<false>(result);
1679
6.92k
                }
1680
6.92k
                g_cloud_commit_txn_resp_redirect_latency << duration_ns / 1000;
1681
1682
6.92k
                if (!status.ok()) {
1683
0
                    LOG(WARNING) << "TableStats report RPC to FE failed, errmsg=" << status
1684
0
                                 << " dbId=" << db_id << " txnId=" << txn_id << " label=" << label;
1685
0
                    return Status::OK(); // nobody cares the return status
1686
6.92k
                } else {
1687
6.92k
                    LOG(INFO) << "TableStats report RPC to FE success, msg=" << status
1688
6.92k
                              << " dbId=" << db_id << " txnId=" << txn_id << " label=" << label;
1689
6.92k
                    return Status::OK();
1690
6.92k
                }
1691
6.92k
            });
1692
6.91k
    if (!st.ok()) {
1693
0
        LOG(WARNING) << "TableStats report to FE task submission failed: " << st.to_string();
1694
0
    }
1695
6.91k
}
1696
1697
0
Status CloudMetaMgr::commit_txn(const StreamLoadContext& ctx, bool is_2pc) {
1698
0
    VLOG_DEBUG << "commit txn, db_id: " << ctx.db_id << ", txn_id: " << ctx.txn_id
1699
0
               << ", label: " << ctx.label << ", is_2pc: " << is_2pc;
1700
0
    {
1701
0
        Status ret_st;
1702
0
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::commit_txn", ret_st);
1703
0
    }
1704
0
    CommitTxnRequest req;
1705
0
    CommitTxnResponse res;
1706
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1707
0
    req.set_db_id(ctx.db_id);
1708
0
    req.set_txn_id(ctx.txn_id);
1709
0
    req.set_is_2pc(is_2pc);
1710
0
    req.set_enable_txn_lazy_commit(config::enable_cloud_txn_lazy_commit);
1711
0
    auto st = retry_rpc(MetaServiceRPC::COMMIT_TXN, req, &res, &MetaService_Stub::commit_txn,
1712
0
                        {
1713
0
                                .host_limiters = host_level_ms_rpc_rate_limiters_,
1714
0
                                .backpressure_handler = ms_backpressure_handler_,
1715
0
                        });
1716
1717
0
    if (st.ok()) {
1718
0
        VLOG_DEBUG << "commit txn succeeded, db_id: " << ctx.db_id << ", txn_id: " << ctx.txn_id
1719
0
                   << ", label: " << ctx.label << ", is_lazy_commit: " << res.is_lazy_commit()
1720
0
                   << ", is_lazy_commit_incomplete: " << res.is_lazy_commit_incomplete();
1721
0
        std::vector<int64_t> tablet_ids;
1722
0
        for (auto& commit_info : ctx.commit_infos) {
1723
0
            tablet_ids.emplace_back(commit_info.tabletId);
1724
0
        }
1725
0
        send_stats_to_fe_async(ctx.db_id, ctx.txn_id, ctx.label, res, tablet_ids);
1726
0
    }
1727
1728
0
    return st;
1729
0
}
1730
1731
487
Status CloudMetaMgr::abort_txn(const StreamLoadContext& ctx) {
1732
18.4E
    VLOG_DEBUG << "abort txn, db_id: " << ctx.db_id << ", txn_id: " << ctx.txn_id
1733
18.4E
               << ", label: " << ctx.label;
1734
487
    {
1735
487
        Status ret_st;
1736
487
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::abort_txn", ret_st);
1737
487
    }
1738
487
    AbortTxnRequest req;
1739
487
    AbortTxnResponse res;
1740
487
    req.set_cloud_unique_id(config::cloud_unique_id);
1741
487
    req.set_reason(std::string(ctx.status.msg().substr(0, 1024)));
1742
488
    if (ctx.txn_id > 0) {
1743
488
        req.set_txn_id(ctx.txn_id);
1744
18.4E
    } else if (ctx.db_id > 0 && !ctx.label.empty()) {
1745
0
        req.set_db_id(ctx.db_id);
1746
0
        req.set_label(ctx.label);
1747
18.4E
    } else {
1748
18.4E
        LOG(WARNING) << "failed abort txn, with illegal input, db_id=" << ctx.db_id
1749
18.4E
                     << " txn_id=" << ctx.txn_id << " label=" << ctx.label;
1750
18.4E
        return Status::InternalError<false>("failed to abort txn");
1751
18.4E
    }
1752
488
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::abort_txn.before_rpc", Status::OK(), &req);
1753
488
    return retry_rpc(MetaServiceRPC::ABORT_TXN, req, &res, &MetaService_Stub::abort_txn,
1754
488
                     {
1755
488
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1756
488
                             .backpressure_handler = ms_backpressure_handler_,
1757
488
                     });
1758
487
}
1759
1760
33
Status CloudMetaMgr::precommit_txn(const StreamLoadContext& ctx) {
1761
33
    VLOG_DEBUG << "precommit txn, db_id: " << ctx.db_id << ", txn_id: " << ctx.txn_id
1762
0
               << ", label: " << ctx.label;
1763
33
    {
1764
33
        Status ret_st;
1765
33
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::precommit_txn", ret_st);
1766
33
    }
1767
33
    PrecommitTxnRequest req;
1768
33
    PrecommitTxnResponse res;
1769
33
    req.set_cloud_unique_id(config::cloud_unique_id);
1770
33
    req.set_db_id(ctx.db_id);
1771
33
    req.set_txn_id(ctx.txn_id);
1772
33
    return retry_rpc(MetaServiceRPC::PRECOMMIT_TXN, req, &res, &MetaService_Stub::precommit_txn,
1773
33
                     {
1774
33
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1775
33
                             .backpressure_handler = ms_backpressure_handler_,
1776
33
                     });
1777
33
}
1778
1779
0
Status CloudMetaMgr::prepare_restore_job(const TabletMetaPB& tablet_meta) {
1780
0
    VLOG_DEBUG << "prepare restore job, tablet_id: " << tablet_meta.tablet_id();
1781
0
    RestoreJobRequest req;
1782
0
    RestoreJobResponse resp;
1783
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1784
0
    req.set_tablet_id(tablet_meta.tablet_id());
1785
0
    req.set_expiration(config::snapshot_expire_time_sec);
1786
0
    req.set_action(RestoreJobRequest::PREPARE);
1787
1788
0
    doris_tablet_meta_to_cloud(req.mutable_tablet_meta(), std::move(tablet_meta));
1789
0
    return retry_rpc(MetaServiceRPC::PREPARE_RESTORE_JOB, req, &resp,
1790
0
                     &MetaService_Stub::prepare_restore_job,
1791
0
                     {
1792
0
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1793
0
                             .backpressure_handler = ms_backpressure_handler_,
1794
0
                     });
1795
0
}
1796
1797
0
Status CloudMetaMgr::commit_restore_job(const int64_t tablet_id) {
1798
0
    VLOG_DEBUG << "commit restore job, tablet_id: " << tablet_id;
1799
0
    RestoreJobRequest req;
1800
0
    RestoreJobResponse resp;
1801
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1802
0
    req.set_tablet_id(tablet_id);
1803
0
    req.set_action(RestoreJobRequest::COMMIT);
1804
0
    req.set_store_version(config::delete_bitmap_store_write_version);
1805
1806
0
    return retry_rpc(MetaServiceRPC::COMMIT_RESTORE_JOB, req, &resp,
1807
0
                     &MetaService_Stub::commit_restore_job,
1808
0
                     {
1809
0
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1810
0
                             .backpressure_handler = ms_backpressure_handler_,
1811
0
                     });
1812
0
}
1813
1814
0
Status CloudMetaMgr::finish_restore_job(const int64_t tablet_id, bool is_completed) {
1815
0
    VLOG_DEBUG << "finish restore job, tablet_id: " << tablet_id
1816
0
               << ", is_completed: " << is_completed;
1817
0
    RestoreJobRequest req;
1818
0
    RestoreJobResponse resp;
1819
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1820
0
    req.set_tablet_id(tablet_id);
1821
0
    req.set_action(is_completed ? RestoreJobRequest::COMPLETE : RestoreJobRequest::ABORT);
1822
1823
0
    return retry_rpc(MetaServiceRPC::FINISH_RESTORE_JOB, req, &resp,
1824
0
                     &MetaService_Stub::finish_restore_job,
1825
0
                     {
1826
0
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1827
0
                             .backpressure_handler = ms_backpressure_handler_,
1828
0
                     });
1829
0
}
1830
1831
231
Status CloudMetaMgr::get_storage_vault_info(StorageVaultInfos* vault_infos, bool* is_vault_mode) {
1832
231
    GetObjStoreInfoRequest req;
1833
231
    GetObjStoreInfoResponse resp;
1834
231
    req.set_cloud_unique_id(config::cloud_unique_id);
1835
231
    Status s = retry_rpc(MetaServiceRPC::GET_OBJ_STORE_INFO, req, &resp,
1836
231
                         &MetaService_Stub::get_obj_store_info,
1837
231
                         {
1838
231
                                 .host_limiters = host_level_ms_rpc_rate_limiters_,
1839
231
                                 .backpressure_handler = ms_backpressure_handler_,
1840
231
                         });
1841
231
    if (!s.ok()) {
1842
0
        return s;
1843
0
    }
1844
1845
231
    *is_vault_mode = resp.enable_storage_vault();
1846
1847
231
    auto add_obj_store = [&vault_infos](const auto& obj_store) {
1848
231
        vault_infos->emplace_back(obj_store.id(), S3Conf::get_s3_conf(obj_store),
1849
231
                                  StorageVaultPB_PathFormat {});
1850
231
    };
1851
1852
231
    std::ranges::for_each(resp.obj_info(), add_obj_store);
1853
231
    std::ranges::for_each(resp.storage_vault(), [&](const auto& vault) {
1854
0
        if (vault.has_hdfs_info()) {
1855
0
            vault_infos->emplace_back(vault.id(), vault.hdfs_info(), vault.path_format());
1856
0
        }
1857
0
        if (vault.has_obj_info()) {
1858
0
            add_obj_store(vault.obj_info());
1859
0
        }
1860
0
    });
1861
1862
    // desensitization, hide secret
1863
462
    for (int i = 0; i < resp.obj_info_size(); ++i) {
1864
231
        resp.mutable_obj_info(i)->set_sk(resp.obj_info(i).sk().substr(0, 2) + "xxx");
1865
231
    }
1866
231
    for (int i = 0; i < resp.storage_vault_size(); ++i) {
1867
0
        auto* j = resp.mutable_storage_vault(i);
1868
0
        if (!j->has_obj_info()) continue;
1869
0
        j->mutable_obj_info()->set_sk(j->obj_info().sk().substr(0, 2) + "xxx");
1870
0
    }
1871
1872
462
    for (int i = 0; i < resp.obj_info_size(); ++i) {
1873
231
        resp.mutable_obj_info(i)->set_ak(hide_access_key(resp.obj_info(i).sk()));
1874
231
    }
1875
231
    for (int i = 0; i < resp.storage_vault_size(); ++i) {
1876
0
        auto* j = resp.mutable_storage_vault(i);
1877
0
        if (!j->has_obj_info()) continue;
1878
0
        j->mutable_obj_info()->set_sk(hide_access_key(j->obj_info().sk()));
1879
0
    }
1880
1881
231
    LOG(INFO) << "get storage vault, enable_storage_vault=" << *is_vault_mode
1882
231
              << " response=" << resp.ShortDebugString();
1883
231
    return Status::OK();
1884
231
}
1885
1886
19.1k
Status CloudMetaMgr::prepare_tablet_job(const TabletJobInfoPB& job, StartTabletJobResponse* res) {
1887
18.4E
    VLOG_DEBUG << "prepare_tablet_job: " << job.ShortDebugString();
1888
19.1k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::prepare_tablet_job", Status::OK(), job, res);
1889
1890
19.1k
    StartTabletJobRequest req;
1891
19.1k
    req.mutable_job()->CopyFrom(job);
1892
19.1k
    req.set_cloud_unique_id(config::cloud_unique_id);
1893
19.1k
    return retry_rpc(MetaServiceRPC::START_TABLET_JOB, req, res,
1894
19.1k
                     &MetaService_Stub::start_tablet_job,
1895
19.1k
                     {
1896
19.1k
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1897
19.1k
                             .backpressure_handler = ms_backpressure_handler_,
1898
19.1k
                     });
1899
19.1k
}
1900
1901
17.4k
Status CloudMetaMgr::commit_tablet_job(const TabletJobInfoPB& job, FinishTabletJobResponse* res) {
1902
18.4E
    VLOG_DEBUG << "commit_tablet_job: " << job.ShortDebugString();
1903
17.4k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::commit_tablet_job", Status::OK(), job, res);
1904
17.4k
    DBUG_EXECUTE_IF("CloudMetaMgr::commit_tablet_job.fail", {
1905
17.4k
        return Status::InternalError<false>("inject CloudMetaMgr::commit_tablet_job.fail");
1906
17.4k
    });
1907
1908
17.4k
    FinishTabletJobRequest req;
1909
17.4k
    req.mutable_job()->CopyFrom(job);
1910
17.4k
    req.set_action(FinishTabletJobRequest::COMMIT);
1911
17.4k
    req.set_cloud_unique_id(config::cloud_unique_id);
1912
17.4k
    auto st = retry_rpc(MetaServiceRPC::FINISH_TABLET_JOB, req, res,
1913
17.4k
                        &MetaService_Stub::finish_tablet_job,
1914
17.4k
                        {
1915
17.4k
                                .host_limiters = host_level_ms_rpc_rate_limiters_,
1916
17.4k
                                .backpressure_handler = ms_backpressure_handler_,
1917
17.4k
                        });
1918
17.4k
    if (res->status().code() == MetaServiceCode::KV_TXN_CONFLICT_RETRY_EXCEEDED_MAX_TIMES) {
1919
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
1920
0
                "txn conflict when commit tablet job {}", job.ShortDebugString());
1921
0
    }
1922
1923
17.7k
    if (st.ok() && !job.compaction().empty() && job.has_idx()) {
1924
6.92k
        CommitTxnResponse commit_txn_resp;
1925
6.92k
        std::vector<int64_t> tablet_ids = {job.idx().tablet_id()};
1926
6.92k
        send_stats_to_fe_async(-1, -1, "", commit_txn_resp, tablet_ids);
1927
6.92k
    }
1928
1929
17.4k
    return st;
1930
17.4k
}
1931
1932
54
Status CloudMetaMgr::abort_tablet_job(const TabletJobInfoPB& job) {
1933
54
    VLOG_DEBUG << "abort_tablet_job: " << job.ShortDebugString();
1934
54
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::abort_tablet_job", Status::OK(), job);
1935
54
    FinishTabletJobRequest req;
1936
54
    FinishTabletJobResponse res;
1937
54
    req.mutable_job()->CopyFrom(job);
1938
54
    req.set_action(FinishTabletJobRequest::ABORT);
1939
54
    req.set_cloud_unique_id(config::cloud_unique_id);
1940
54
    return retry_rpc(MetaServiceRPC::FINISH_TABLET_JOB, req, &res,
1941
54
                     &MetaService_Stub::finish_tablet_job,
1942
54
                     {
1943
54
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1944
54
                             .backpressure_handler = ms_backpressure_handler_,
1945
54
                     });
1946
54
}
1947
1948
159
Status CloudMetaMgr::lease_tablet_job(const TabletJobInfoPB& job) {
1949
159
    VLOG_DEBUG << "lease_tablet_job: " << job.ShortDebugString();
1950
159
    FinishTabletJobRequest req;
1951
159
    FinishTabletJobResponse res;
1952
159
    req.mutable_job()->CopyFrom(job);
1953
159
    req.set_action(FinishTabletJobRequest::LEASE);
1954
159
    req.set_cloud_unique_id(config::cloud_unique_id);
1955
159
    return retry_rpc(MetaServiceRPC::FINISH_TABLET_JOB, req, &res,
1956
159
                     &MetaService_Stub::finish_tablet_job,
1957
159
                     {
1958
159
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
1959
159
                             .backpressure_handler = ms_backpressure_handler_,
1960
159
                     });
1961
159
}
1962
1963
static void add_delete_bitmap(DeleteBitmapPB& delete_bitmap_pb, const DeleteBitmap::BitmapKey& key,
1964
0
                              roaring::Roaring& bitmap) {
1965
0
    delete_bitmap_pb.add_rowset_ids(std::get<0>(key).to_string());
1966
0
    delete_bitmap_pb.add_segment_ids(std::get<1>(key));
1967
0
    delete_bitmap_pb.add_versions(std::get<2>(key));
1968
    // To save space, convert array and bitmap containers to run containers
1969
0
    bitmap.runOptimize();
1970
0
    std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
1971
0
    bitmap.write(bitmap_data.data());
1972
0
    *(delete_bitmap_pb.add_segment_delete_bitmaps()) = std::move(bitmap_data);
1973
0
}
1974
1975
static Status store_delete_bitmap(std::string& rowset_id, DeleteBitmapPB& delete_bitmap_pb,
1976
                                  int64_t tablet_id,
1977
                                  std::optional<StorageResource> storage_resource,
1978
0
                                  UpdateDeleteBitmapRequest& req, int64_t txn_id) {
1979
0
    if (config::enable_mow_verbose_log) {
1980
0
        std::stringstream ss;
1981
0
        for (int i = 0; i < delete_bitmap_pb.rowset_ids_size(); i++) {
1982
0
            ss << "{rid=" << delete_bitmap_pb.rowset_ids(i)
1983
0
               << ", sid=" << delete_bitmap_pb.segment_ids(i)
1984
0
               << ", ver=" << delete_bitmap_pb.versions(i) << "}, ";
1985
0
        }
1986
0
        LOG(INFO) << "handle one rowset delete bitmap for tablet_id: " << tablet_id
1987
0
                  << ", rowset_id: " << rowset_id
1988
0
                  << ", delete_bitmap num: " << delete_bitmap_pb.rowset_ids_size()
1989
0
                  << ",  size: " << delete_bitmap_pb.ByteSizeLong() << ", keys=[" << ss.str()
1990
0
                  << "]";
1991
0
    }
1992
0
    if (delete_bitmap_pb.rowset_ids_size() == 0) {
1993
0
        return Status::OK();
1994
0
    }
1995
0
    DeleteBitmapStoragePB delete_bitmap_storage;
1996
0
    if (config::delete_bitmap_store_v2_max_bytes_in_fdb >= 0 &&
1997
0
        delete_bitmap_pb.ByteSizeLong() > config::delete_bitmap_store_v2_max_bytes_in_fdb) {
1998
        // Enable packed file only for load (txn_id > 0)
1999
0
        bool enable_packed = config::enable_packed_file && txn_id > 0;
2000
0
        DeleteBitmapFileWriter file_writer(tablet_id, rowset_id, storage_resource, enable_packed,
2001
0
                                           txn_id);
2002
0
        RETURN_IF_ERROR(file_writer.init());
2003
0
        RETURN_IF_ERROR(file_writer.write(delete_bitmap_pb));
2004
0
        RETURN_IF_ERROR(file_writer.close());
2005
0
        delete_bitmap_pb.Clear();
2006
0
        delete_bitmap_storage.set_store_in_fdb(false);
2007
2008
        // Store packed slice location if file was written to packed file
2009
0
        if (file_writer.is_packed()) {
2010
0
            io::PackedSliceLocation loc;
2011
0
            RETURN_IF_ERROR(file_writer.get_packed_slice_location(&loc));
2012
0
            auto* packed_loc = delete_bitmap_storage.mutable_packed_slice_location();
2013
0
            packed_loc->set_packed_file_path(loc.packed_file_path);
2014
0
            packed_loc->set_offset(loc.offset);
2015
0
            packed_loc->set_size(loc.size);
2016
0
            packed_loc->set_packed_file_size(loc.packed_file_size);
2017
0
        }
2018
0
    } else {
2019
0
        delete_bitmap_storage.set_store_in_fdb(true);
2020
0
        *(delete_bitmap_storage.mutable_delete_bitmap()) = std::move(delete_bitmap_pb);
2021
0
    }
2022
0
    req.add_delta_rowset_ids(rowset_id);
2023
0
    *(req.add_delete_bitmap_storages()) = std::move(delete_bitmap_storage);
2024
0
    return Status::OK();
2025
0
}
2026
2027
Status CloudMetaMgr::update_delete_bitmap(const CloudTablet& tablet, int64_t lock_id,
2028
                                          int64_t initiator, DeleteBitmap* delete_bitmap,
2029
                                          DeleteBitmap* delete_bitmap_v2, std::string rowset_id,
2030
                                          std::optional<StorageResource> storage_resource,
2031
                                          int64_t store_version, int64_t table_id, int64_t txn_id,
2032
24.8k
                                          bool is_explicit_txn, int64_t next_visible_version) {
2033
18.4E
    VLOG_DEBUG << "update_delete_bitmap , tablet_id: " << tablet.tablet_id();
2034
24.8k
    if (config::enable_mow_verbose_log) {
2035
0
        std::stringstream ss;
2036
0
        ss << "start update delete bitmap for tablet_id: " << tablet.tablet_id()
2037
0
           << ", rowset_id: " << rowset_id
2038
0
           << ", delete_bitmap num: " << delete_bitmap->delete_bitmap.size()
2039
0
           << ", store_version: " << store_version << ", lock_id=" << lock_id
2040
0
           << ", initiator=" << initiator;
2041
0
        if (store_version == 2 || store_version == 3) {
2042
0
            ss << ", delete_bitmap v2 num: " << delete_bitmap_v2->delete_bitmap.size();
2043
0
        }
2044
0
        LOG(INFO) << ss.str();
2045
0
    }
2046
24.8k
    UpdateDeleteBitmapRequest req;
2047
24.8k
    UpdateDeleteBitmapResponse res;
2048
24.8k
    req.set_cloud_unique_id(config::cloud_unique_id);
2049
24.8k
    req.set_table_id(tablet.table_id());
2050
24.8k
    req.set_partition_id(tablet.partition_id());
2051
24.8k
    req.set_tablet_id(tablet.tablet_id());
2052
24.8k
    req.set_lock_id(lock_id);
2053
24.8k
    req.set_initiator(initiator);
2054
24.8k
    req.set_is_explicit_txn(is_explicit_txn);
2055
24.8k
    if (txn_id > 0) {
2056
20.1k
        req.set_txn_id(txn_id);
2057
20.1k
    }
2058
24.8k
    if (next_visible_version > 0) {
2059
20.2k
        req.set_next_visible_version(next_visible_version);
2060
20.2k
    }
2061
24.8k
    req.set_store_version(store_version);
2062
2063
24.8k
    bool write_v1 = store_version == 1 || store_version == 3;
2064
24.8k
    bool write_v2 = store_version == 2 || store_version == 3;
2065
    // write v1 kvs
2066
24.8k
    if (write_v1) {
2067
24.5k
        for (auto& [key, bitmap] : delete_bitmap->delete_bitmap) {
2068
8.49k
            req.add_rowset_ids(std::get<0>(key).to_string());
2069
8.49k
            req.add_segment_ids(std::get<1>(key));
2070
8.49k
            req.add_versions(std::get<2>(key));
2071
            // To save space, convert array and bitmap containers to run containers
2072
8.49k
            bitmap.runOptimize();
2073
8.49k
            std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
2074
8.49k
            bitmap.write(bitmap_data.data());
2075
8.49k
            *(req.add_segment_delete_bitmaps()) = std::move(bitmap_data);
2076
8.49k
        }
2077
24.5k
    }
2078
2079
    // write v2 kvs
2080
24.8k
    if (write_v2) {
2081
0
        if (config::enable_mow_verbose_log) {
2082
0
            LOG(INFO) << "update delete bitmap for tablet_id: " << tablet.tablet_id()
2083
0
                      << ", rowset_id: " << rowset_id
2084
0
                      << ", delete_bitmap num: " << delete_bitmap_v2->delete_bitmap.size()
2085
0
                      << ", lock_id=" << lock_id << ", initiator=" << initiator;
2086
0
        }
2087
0
        if (rowset_id.empty()) {
2088
0
            std::string pre_rowset_id = "";
2089
0
            std::string cur_rowset_id = "";
2090
0
            DeleteBitmapPB delete_bitmap_pb;
2091
0
            for (auto it = delete_bitmap_v2->delete_bitmap.begin();
2092
0
                 it != delete_bitmap_v2->delete_bitmap.end(); ++it) {
2093
0
                auto& key = it->first;
2094
0
                auto& bitmap = it->second;
2095
0
                cur_rowset_id = std::get<0>(key).to_string();
2096
0
                if (cur_rowset_id != pre_rowset_id) {
2097
0
                    if (!pre_rowset_id.empty() && delete_bitmap_pb.rowset_ids_size() > 0) {
2098
0
                        RETURN_IF_ERROR(store_delete_bitmap(pre_rowset_id, delete_bitmap_pb,
2099
0
                                                            tablet.tablet_id(), storage_resource,
2100
0
                                                            req, txn_id));
2101
0
                    }
2102
0
                    pre_rowset_id = cur_rowset_id;
2103
0
                    DCHECK_EQ(delete_bitmap_pb.rowset_ids_size(), 0);
2104
0
                    DCHECK_EQ(delete_bitmap_pb.segment_ids_size(), 0);
2105
0
                    DCHECK_EQ(delete_bitmap_pb.versions_size(), 0);
2106
0
                    DCHECK_EQ(delete_bitmap_pb.segment_delete_bitmaps_size(), 0);
2107
0
                }
2108
0
                add_delete_bitmap(delete_bitmap_pb, key, bitmap);
2109
0
            }
2110
0
            if (delete_bitmap_pb.rowset_ids_size() > 0) {
2111
0
                DCHECK(!cur_rowset_id.empty());
2112
0
                RETURN_IF_ERROR(store_delete_bitmap(cur_rowset_id, delete_bitmap_pb,
2113
0
                                                    tablet.tablet_id(), storage_resource, req,
2114
0
                                                    txn_id));
2115
0
            }
2116
0
        } else {
2117
0
            DeleteBitmapPB delete_bitmap_pb;
2118
0
            for (auto& [key, bitmap] : delete_bitmap_v2->delete_bitmap) {
2119
0
                add_delete_bitmap(delete_bitmap_pb, key, bitmap);
2120
0
            }
2121
0
            RETURN_IF_ERROR(store_delete_bitmap(rowset_id, delete_bitmap_pb, tablet.tablet_id(),
2122
0
                                                storage_resource, req, txn_id));
2123
0
        }
2124
0
        DCHECK_EQ(req.delta_rowset_ids_size(), req.delete_bitmap_storages_size());
2125
0
    }
2126
24.8k
    DBUG_EXECUTE_IF("CloudMetaMgr::test_update_big_delete_bitmap", {
2127
24.8k
        LOG(INFO) << "test_update_big_delete_bitmap for tablet " << tablet.tablet_id();
2128
24.8k
        auto count = dp->param<int>("count", 30000);
2129
24.8k
        if (!delete_bitmap->delete_bitmap.empty()) {
2130
24.8k
            auto& key = delete_bitmap->delete_bitmap.begin()->first;
2131
24.8k
            auto& bitmap = delete_bitmap->delete_bitmap.begin()->second;
2132
24.8k
            for (int i = 1000; i < (1000 + count); i++) {
2133
24.8k
                req.add_rowset_ids(std::get<0>(key).to_string());
2134
24.8k
                req.add_segment_ids(std::get<1>(key));
2135
24.8k
                req.add_versions(i);
2136
                // To save space, convert array and bitmap containers to run containers
2137
24.8k
                bitmap.runOptimize();
2138
24.8k
                std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
2139
24.8k
                bitmap.write(bitmap_data.data());
2140
24.8k
                *(req.add_segment_delete_bitmaps()) = std::move(bitmap_data);
2141
24.8k
            }
2142
24.8k
        }
2143
24.8k
    });
2144
24.8k
    DBUG_EXECUTE_IF("CloudMetaMgr::test_update_delete_bitmap_fail", {
2145
24.8k
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR>(
2146
24.8k
                "test update delete bitmap failed, tablet_id: {}, lock_id: {}", tablet.tablet_id(),
2147
24.8k
                lock_id);
2148
24.8k
    });
2149
24.8k
    auto st = retry_rpc(MetaServiceRPC::UPDATE_DELETE_BITMAP, req, &res,
2150
24.8k
                        &MetaService_Stub::update_delete_bitmap,
2151
24.8k
                        {
2152
24.8k
                                .host_limiters = host_level_ms_rpc_rate_limiters_,
2153
24.8k
                                .backpressure_handler = ms_backpressure_handler_,
2154
24.8k
                                .table_id = table_id,
2155
24.8k
                        });
2156
24.8k
    if (config::enable_update_delete_bitmap_kv_check_core &&
2157
24.8k
        res.status().code() == MetaServiceCode::UPDATE_OVERRIDE_EXISTING_KV) {
2158
0
        auto& msg = res.status().msg();
2159
0
        LOG_WARNING(msg);
2160
0
        CHECK(false) << msg;
2161
0
    }
2162
24.8k
    if (res.status().code() == MetaServiceCode::LOCK_EXPIRED) {
2163
5
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
2164
5
                "lock expired when update delete bitmap, tablet_id: {}, lock_id: {}, initiator: "
2165
5
                "{}, error_msg: {}",
2166
5
                tablet.tablet_id(), lock_id, initiator, res.status().msg());
2167
5
    }
2168
24.8k
    return st;
2169
24.8k
}
2170
2171
Status CloudMetaMgr::cloud_update_delete_bitmap_without_lock(
2172
        const CloudTablet& tablet, DeleteBitmap* delete_bitmap,
2173
        std::map<std::string, int64_t>& rowset_to_versions, int64_t table_id,
2174
2.99k
        int64_t pre_rowset_agg_start_version, int64_t pre_rowset_agg_end_version) {
2175
2.99k
    if (config::delete_bitmap_store_write_version == 2) {
2176
0
        VLOG_DEBUG << "no need to agg delete bitmap v1 in ms because use v2";
2177
0
        return Status::OK();
2178
0
    }
2179
2.99k
    LOG(INFO) << "cloud_update_delete_bitmap_without_lock, tablet_id: " << tablet.tablet_id()
2180
2.99k
              << ", delete_bitmap size: " << delete_bitmap->delete_bitmap.size();
2181
2.99k
    UpdateDeleteBitmapRequest req;
2182
2.99k
    UpdateDeleteBitmapResponse res;
2183
2.99k
    req.set_cloud_unique_id(config::cloud_unique_id);
2184
2.99k
    req.set_table_id(tablet.table_id());
2185
2.99k
    req.set_partition_id(tablet.partition_id());
2186
2.99k
    req.set_tablet_id(tablet.tablet_id());
2187
    // use a fake lock id to resolve compatibility issues
2188
2.99k
    req.set_lock_id(-3);
2189
2.99k
    req.set_without_lock(true);
2190
2.99k
    for (auto& [key, bitmap] : delete_bitmap->delete_bitmap) {
2191
983
        req.add_rowset_ids(std::get<0>(key).to_string());
2192
983
        req.add_segment_ids(std::get<1>(key));
2193
983
        req.add_versions(std::get<2>(key));
2194
983
        if (pre_rowset_agg_end_version > 0) {
2195
983
            DCHECK(rowset_to_versions.find(std::get<0>(key).to_string()) !=
2196
0
                   rowset_to_versions.end())
2197
0
                    << "rowset_to_versions not found for key=" << std::get<0>(key).to_string();
2198
983
            req.add_pre_rowset_versions(rowset_to_versions[std::get<0>(key).to_string()]);
2199
983
        }
2200
983
        DCHECK(pre_rowset_agg_end_version <= 0 || pre_rowset_agg_end_version == std::get<2>(key))
2201
0
                << "pre_rowset_agg_end_version=" << pre_rowset_agg_end_version
2202
0
                << " not equal to version=" << std::get<2>(key);
2203
        // To save space, convert array and bitmap containers to run containers
2204
983
        bitmap.runOptimize();
2205
983
        std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
2206
983
        bitmap.write(bitmap_data.data());
2207
983
        *(req.add_segment_delete_bitmaps()) = std::move(bitmap_data);
2208
983
    }
2209
2.99k
    if (pre_rowset_agg_start_version > 0 && pre_rowset_agg_end_version > 0) {
2210
2.99k
        req.set_pre_rowset_agg_start_version(pre_rowset_agg_start_version);
2211
2.99k
        req.set_pre_rowset_agg_end_version(pre_rowset_agg_end_version);
2212
2.99k
    }
2213
2.99k
    return retry_rpc(MetaServiceRPC::UPDATE_DELETE_BITMAP, req, &res,
2214
2.99k
                     &MetaService_Stub::update_delete_bitmap,
2215
2.99k
                     {
2216
2.99k
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
2217
2.99k
                             .backpressure_handler = ms_backpressure_handler_,
2218
2.99k
                             .table_id = table_id,
2219
2.99k
                     });
2220
2.99k
}
2221
2222
Status CloudMetaMgr::get_delete_bitmap_update_lock(const CloudTablet& tablet, int64_t lock_id,
2223
4.24k
                                                   int64_t initiator) {
2224
4.24k
    DBUG_EXECUTE_IF("get_delete_bitmap_update_lock.inject_fail", {
2225
4.24k
        auto p = dp->param("percent", 0.01);
2226
4.24k
        std::mt19937 gen {std::random_device {}()};
2227
4.24k
        std::bernoulli_distribution inject_fault {p};
2228
4.24k
        if (inject_fault(gen)) {
2229
4.24k
            return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR>(
2230
4.24k
                    "injection error when get get_delete_bitmap_update_lock, "
2231
4.24k
                    "tablet_id={}, lock_id={}, initiator={}",
2232
4.24k
                    tablet.tablet_id(), lock_id, initiator);
2233
4.24k
        }
2234
4.24k
    });
2235
4.24k
    VLOG_DEBUG << "get_delete_bitmap_update_lock , tablet_id: " << tablet.tablet_id()
2236
0
               << ",lock_id:" << lock_id;
2237
4.24k
    GetDeleteBitmapUpdateLockRequest req;
2238
4.24k
    GetDeleteBitmapUpdateLockResponse res;
2239
4.24k
    req.set_cloud_unique_id(config::cloud_unique_id);
2240
4.24k
    req.set_table_id(tablet.table_id());
2241
4.24k
    req.set_lock_id(lock_id);
2242
4.24k
    req.set_initiator(initiator);
2243
    // set expiration time for compaction and schema_change
2244
4.24k
    req.set_expiration(config::delete_bitmap_lock_expiration_seconds);
2245
4.24k
    int retry_times = 0;
2246
4.24k
    Status st;
2247
4.24k
    std::default_random_engine rng = make_random_engine();
2248
4.24k
    std::uniform_int_distribution<uint32_t> u(500, 2000);
2249
4.24k
    uint64_t backoff_sleep_time_ms {0};
2250
4.55k
    do {
2251
4.55k
        bool test_conflict = false;
2252
4.55k
        st = retry_rpc(MetaServiceRPC::GET_DELETE_BITMAP_UPDATE_LOCK, req, &res,
2253
4.55k
                       &MetaService_Stub::get_delete_bitmap_update_lock,
2254
4.55k
                       {
2255
4.55k
                               .host_limiters = host_level_ms_rpc_rate_limiters_,
2256
4.55k
                               .backpressure_handler = ms_backpressure_handler_,
2257
4.55k
                       });
2258
4.55k
        DBUG_EXECUTE_IF("CloudMetaMgr::test_get_delete_bitmap_update_lock_conflict",
2259
4.55k
                        { test_conflict = true; });
2260
4.55k
        if (!test_conflict && res.status().code() != MetaServiceCode::LOCK_CONFLICT) {
2261
4.24k
            break;
2262
4.24k
        }
2263
2264
305
        uint32_t duration_ms = u(rng);
2265
305
        LOG(WARNING) << "get delete bitmap lock conflict. " << debug_info(req)
2266
305
                     << " retry_times=" << retry_times << " sleep=" << duration_ms
2267
305
                     << "ms : " << res.status().msg();
2268
305
        auto start = std::chrono::steady_clock::now();
2269
305
        bthread_usleep(duration_ms * 1000);
2270
305
        auto end = std::chrono::steady_clock::now();
2271
305
        backoff_sleep_time_ms += duration_cast<std::chrono::milliseconds>(end - start).count();
2272
305
    } while (++retry_times <= config::get_delete_bitmap_lock_max_retry_times);
2273
0
    g_cloud_be_mow_get_dbm_lock_backoff_sleep_time << backoff_sleep_time_ms;
2274
4.24k
    DBUG_EXECUTE_IF("CloudMetaMgr.get_delete_bitmap_update_lock.inject_sleep", {
2275
4.24k
        auto p = dp->param("percent", 0.01);
2276
        // 100s > Config.calculate_delete_bitmap_task_timeout_seconds = 60s
2277
4.24k
        auto sleep_time = dp->param("sleep", 15);
2278
4.24k
        std::mt19937 gen {std::random_device {}()};
2279
4.24k
        std::bernoulli_distribution inject_fault {p};
2280
4.24k
        if (inject_fault(gen)) {
2281
4.24k
            LOG_INFO("injection sleep for {} seconds, tablet_id={}", sleep_time,
2282
4.24k
                     tablet.tablet_id());
2283
4.24k
            std::this_thread::sleep_for(std::chrono::seconds(sleep_time));
2284
4.24k
        }
2285
4.24k
    });
2286
4.24k
    if (res.status().code() == MetaServiceCode::KV_TXN_CONFLICT_RETRY_EXCEEDED_MAX_TIMES) {
2287
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
2288
0
                "txn conflict when get delete bitmap update lock, table_id {}, lock_id {}, "
2289
0
                "initiator {}",
2290
0
                tablet.table_id(), lock_id, initiator);
2291
4.24k
    } else if (res.status().code() == MetaServiceCode::LOCK_CONFLICT) {
2292
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
2293
0
                "lock conflict when get delete bitmap update lock, table_id {}, lock_id {}, "
2294
0
                "initiator {}",
2295
0
                tablet.table_id(), lock_id, initiator);
2296
0
    }
2297
4.24k
    return st;
2298
4.24k
}
2299
2300
void CloudMetaMgr::remove_delete_bitmap_update_lock(int64_t table_id, int64_t lock_id,
2301
23
                                                    int64_t initiator, int64_t tablet_id) {
2302
23
    LOG(INFO) << "remove_delete_bitmap_update_lock ,table_id: " << table_id
2303
23
              << ",lock_id:" << lock_id << ",initiator:" << initiator << ",tablet_id:" << tablet_id;
2304
23
    RemoveDeleteBitmapUpdateLockRequest req;
2305
23
    RemoveDeleteBitmapUpdateLockResponse res;
2306
23
    req.set_cloud_unique_id(config::cloud_unique_id);
2307
23
    req.set_table_id(table_id);
2308
23
    req.set_tablet_id(tablet_id);
2309
23
    req.set_lock_id(lock_id);
2310
23
    req.set_initiator(initiator);
2311
23
    auto st = retry_rpc(MetaServiceRPC::REMOVE_DELETE_BITMAP_UPDATE_LOCK, req, &res,
2312
23
                        &MetaService_Stub::remove_delete_bitmap_update_lock,
2313
23
                        {
2314
23
                                .host_limiters = host_level_ms_rpc_rate_limiters_,
2315
23
                                .backpressure_handler = ms_backpressure_handler_,
2316
23
                        });
2317
23
    if (!st.ok()) {
2318
23
        LOG(WARNING) << "remove delete bitmap update lock fail,table_id=" << table_id
2319
23
                     << ",tablet_id=" << tablet_id << ",lock_id=" << lock_id
2320
23
                     << ",st=" << st.to_string();
2321
23
    }
2322
23
}
2323
2324
73.2k
void CloudMetaMgr::check_table_size_correctness(RowsetMeta& rs_meta) {
2325
73.8k
    if (!config::enable_table_size_correctness_check) {
2326
73.8k
        return;
2327
73.8k
    }
2328
18.4E
    int64_t total_segment_size = get_segment_file_size(rs_meta);
2329
18.4E
    int64_t total_inverted_index_size = get_inverted_index_file_size(rs_meta);
2330
18.4E
    if (rs_meta.data_disk_size() != total_segment_size ||
2331
18.4E
        rs_meta.index_disk_size() != total_inverted_index_size ||
2332
18.4E
        rs_meta.data_disk_size() + rs_meta.index_disk_size() != rs_meta.total_disk_size()) {
2333
0
        LOG(WARNING) << "[Cloud table table size check failed]:"
2334
0
                     << " tablet id: " << rs_meta.tablet_id()
2335
0
                     << ", rowset id:" << rs_meta.rowset_id()
2336
0
                     << ", rowset data disk size:" << rs_meta.data_disk_size()
2337
0
                     << ", rowset real data disk size:" << total_segment_size
2338
0
                     << ", rowset index disk size:" << rs_meta.index_disk_size()
2339
0
                     << ", rowset real index disk size:" << total_inverted_index_size
2340
0
                     << ", rowset total disk size:" << rs_meta.total_disk_size()
2341
0
                     << ", rowset segment path:"
2342
0
                     << StorageResource().remote_segment_path(rs_meta.tablet_id(),
2343
0
                                                              rs_meta.rowset_id().to_string(), 0);
2344
0
        DCHECK(false);
2345
0
    }
2346
18.4E
}
2347
2348
0
int64_t CloudMetaMgr::get_segment_file_size(RowsetMeta& rs_meta) {
2349
0
    int64_t total_segment_size = 0;
2350
0
    const auto fs = rs_meta.fs();
2351
0
    if (!fs) {
2352
0
        LOG(WARNING) << "get fs failed, resource_id={}" << rs_meta.resource_id();
2353
0
    }
2354
0
    for (int64_t seg_id = 0; seg_id < rs_meta.num_segments(); seg_id++) {
2355
0
        std::string segment_path = StorageResource().remote_segment_path(
2356
0
                rs_meta.tablet_id(), rs_meta.rowset_id().to_string(), seg_id);
2357
0
        int64_t segment_file_size = 0;
2358
0
        auto st = fs->file_size(segment_path, &segment_file_size);
2359
0
        if (!st.ok()) {
2360
0
            segment_file_size = 0;
2361
0
            if (st.is<NOT_FOUND>()) {
2362
0
                LOG(INFO) << "cloud table size correctness check get segment size 0 because "
2363
0
                             "file not exist! msg:"
2364
0
                          << st.msg() << ", segment path:" << segment_path;
2365
0
            } else {
2366
0
                LOG(WARNING) << "cloud table size correctness check get segment size failed! msg:"
2367
0
                             << st.msg() << ", segment path:" << segment_path;
2368
0
            }
2369
0
        }
2370
0
        total_segment_size += segment_file_size;
2371
0
    }
2372
0
    return total_segment_size;
2373
0
}
2374
2375
0
int64_t CloudMetaMgr::get_inverted_index_file_size(RowsetMeta& rs_meta) {
2376
0
    int64_t total_inverted_index_size = 0;
2377
0
    const auto fs = rs_meta.fs();
2378
0
    if (!fs) {
2379
0
        LOG(WARNING) << "get fs failed, resource_id={}" << rs_meta.resource_id();
2380
0
    }
2381
0
    if (rs_meta.tablet_schema()->get_inverted_index_storage_format() ==
2382
0
        InvertedIndexStorageFormatPB::V1) {
2383
0
        const auto& indices = rs_meta.tablet_schema()->inverted_indexes();
2384
0
        for (auto& index : indices) {
2385
0
            for (int seg_id = 0; seg_id < rs_meta.num_segments(); ++seg_id) {
2386
0
                std::string segment_path = StorageResource().remote_segment_path(
2387
0
                        rs_meta.tablet_id(), rs_meta.rowset_id().to_string(), seg_id);
2388
0
                int64_t file_size = 0;
2389
2390
0
                std::string inverted_index_file_path =
2391
0
                        InvertedIndexDescriptor::get_index_file_path_v1(
2392
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(segment_path),
2393
0
                                index->index_id(), index->get_index_suffix());
2394
0
                auto st = fs->file_size(inverted_index_file_path, &file_size);
2395
0
                if (!st.ok()) {
2396
0
                    file_size = 0;
2397
0
                    if (st.is<NOT_FOUND>()) {
2398
0
                        LOG(INFO) << "cloud table size correctness check get inverted index v1 "
2399
0
                                     "0 because file not exist! msg:"
2400
0
                                  << st.msg()
2401
0
                                  << ", inverted index path:" << inverted_index_file_path;
2402
0
                    } else {
2403
0
                        LOG(WARNING)
2404
0
                                << "cloud table size correctness check get inverted index v1 "
2405
0
                                   "size failed! msg:"
2406
0
                                << st.msg() << ", inverted index path:" << inverted_index_file_path;
2407
0
                    }
2408
0
                }
2409
0
                total_inverted_index_size += file_size;
2410
0
            }
2411
0
        }
2412
0
    } else {
2413
0
        for (int seg_id = 0; seg_id < rs_meta.num_segments(); ++seg_id) {
2414
0
            int64_t file_size = 0;
2415
0
            std::string segment_path = StorageResource().remote_segment_path(
2416
0
                    rs_meta.tablet_id(), rs_meta.rowset_id().to_string(), seg_id);
2417
2418
0
            std::string inverted_index_file_path = InvertedIndexDescriptor::get_index_file_path_v2(
2419
0
                    InvertedIndexDescriptor::get_index_file_path_prefix(segment_path));
2420
0
            auto st = fs->file_size(inverted_index_file_path, &file_size);
2421
0
            if (!st.ok()) {
2422
0
                file_size = 0;
2423
0
                if (st.is<NOT_FOUND>()) {
2424
0
                    LOG(INFO) << "cloud table size correctness check get inverted index v2 "
2425
0
                                 "0 because file not exist! msg:"
2426
0
                              << st.msg() << ", inverted index path:" << inverted_index_file_path;
2427
0
                } else {
2428
0
                    LOG(WARNING) << "cloud table size correctness check get inverted index v2 "
2429
0
                                    "size failed! msg:"
2430
0
                                 << st.msg()
2431
0
                                 << ", inverted index path:" << inverted_index_file_path;
2432
0
                }
2433
0
            }
2434
0
            total_inverted_index_size += file_size;
2435
0
        }
2436
0
    }
2437
0
    return total_inverted_index_size;
2438
0
}
2439
2440
Status CloudMetaMgr::fill_version_holes(CloudTablet* tablet, int64_t max_version,
2441
176k
                                        std::unique_lock<BthreadSharedMutex>& wlock) {
2442
176k
    if (max_version <= 0) {
2443
116k
        return Status::OK();
2444
116k
    }
2445
2446
60.3k
    Versions existing_versions;
2447
211k
    for (const auto& [_, rs] : tablet->tablet_meta()->all_rs_metas()) {
2448
211k
        existing_versions.emplace_back(rs->version());
2449
211k
    }
2450
2451
    // If there are no existing versions, it may be a new tablet for restore, so skip filling holes.
2452
60.3k
    if (existing_versions.empty()) {
2453
1
        return Status::OK();
2454
1
    }
2455
2456
60.3k
    std::vector<RowsetSharedPtr> hole_rowsets;
2457
    // sort the existing versions in ascending order
2458
60.3k
    std::sort(existing_versions.begin(), existing_versions.end(),
2459
458k
              [](const Version& a, const Version& b) {
2460
                  // simple because 2 versions are certainly not overlapping
2461
458k
                  return a.first < b.first;
2462
458k
              });
2463
2464
    // During schema change, get_tablet operations on new tablets trigger sync_tablet_rowsets which calls
2465
    // fill_version_holes. For schema change tablets (TABLET_NOTREADY state), we selectively skip hole
2466
    // filling for versions <= alter_version to prevent:
2467
    // 1. Abnormal compaction score calculations for schema change tablets
2468
    // 2. Unexpected -235 errors during load operations
2469
    // This allows schema change to proceed normally while still permitting hole filling for versions
2470
    // beyond the alter_version threshold.
2471
60.3k
    bool is_schema_change_tablet = tablet->tablet_state() == TABLET_NOTREADY;
2472
60.3k
    if (is_schema_change_tablet && tablet->alter_version() <= 1) {
2473
10.7k
        LOG(INFO) << "Skip version hole filling for new schema change tablet "
2474
10.7k
                  << tablet->tablet_id() << " with alter_version " << tablet->alter_version();
2475
10.7k
        return Status::OK();
2476
10.7k
    }
2477
2478
49.5k
    int64_t last_version = -1;
2479
200k
    for (const Version& version : existing_versions) {
2480
18.4E
        VLOG_NOTICE << "Existing version for tablet " << tablet->tablet_id() << ": ["
2481
18.4E
                    << version.first << ", " << version.second << "]";
2482
        // missing versions are those that are not in the existing_versions
2483
200k
        if (version.first > last_version + 1) {
2484
            // there is a hole between versions
2485
242
            auto prev_non_hole_rowset = tablet->get_rowset_by_version(version);
2486
1.83k
            for (int64_t ver = last_version + 1; ver < version.first; ++ver) {
2487
                // Skip hole filling for versions <= alter_version during schema change
2488
1.59k
                if (is_schema_change_tablet && ver <= tablet->alter_version()) {
2489
1.16k
                    continue;
2490
1.16k
                }
2491
427
                RowsetSharedPtr hole_rowset;
2492
427
                RETURN_IF_ERROR(create_empty_rowset_for_hole(
2493
427
                        tablet, ver, prev_non_hole_rowset->rowset_meta(), &hole_rowset));
2494
427
                hole_rowsets.push_back(hole_rowset);
2495
427
            }
2496
242
            LOG(INFO) << "Created empty rowset for version hole, from " << last_version + 1
2497
242
                      << " to " << version.first - 1 << " for tablet " << tablet->tablet_id()
2498
242
                      << (is_schema_change_tablet
2499
242
                                  ? (", schema change tablet skipped filling versions <= " +
2500
56
                                     std::to_string(tablet->alter_version()))
2501
242
                                  : "");
2502
242
        }
2503
200k
        last_version = version.second;
2504
200k
    }
2505
2506
49.5k
    if (last_version + 1 <= max_version) {
2507
12.3k
        LOG(INFO) << "Created empty rowset for version hole, from " << last_version + 1 << " to "
2508
12.3k
                  << max_version << " for tablet " << tablet->tablet_id()
2509
12.3k
                  << (is_schema_change_tablet
2510
12.3k
                              ? (", schema change tablet skipped filling versions <= " +
2511
5.34k
                                 std::to_string(tablet->alter_version()))
2512
12.3k
                              : "");
2513
        // there is a hole after the last existing version
2514
33.1k
        for (; last_version + 1 <= max_version; ++last_version) {
2515
            // Skip hole filling for versions <= alter_version during schema change
2516
20.7k
            if (is_schema_change_tablet && last_version + 1 <= tablet->alter_version()) {
2517
11.7k
                continue;
2518
11.7k
            }
2519
9.06k
            RowsetSharedPtr hole_rowset;
2520
9.06k
            auto prev_non_hole_rowset = tablet->get_rowset_by_version(existing_versions.back());
2521
9.06k
            RETURN_IF_ERROR(create_empty_rowset_for_hole(
2522
9.06k
                    tablet, last_version + 1, prev_non_hole_rowset->rowset_meta(), &hole_rowset));
2523
9.06k
            hole_rowsets.push_back(hole_rowset);
2524
9.06k
        }
2525
12.3k
    }
2526
2527
49.5k
    if (!hole_rowsets.empty()) {
2528
7.16k
        size_t hole_count = hole_rowsets.size();
2529
7.16k
        tablet->add_rowsets(std::move(hole_rowsets), false, wlock, false);
2530
7.16k
        g_cloud_version_hole_filled_count << hole_count;
2531
7.16k
    }
2532
49.5k
    return Status::OK();
2533
49.5k
}
2534
2535
Status CloudMetaMgr::create_empty_rowset_for_hole(CloudTablet* tablet, int64_t version,
2536
                                                  RowsetMetaSharedPtr prev_rowset_meta,
2537
126k
                                                  RowsetSharedPtr* rowset) {
2538
    // Create a RowsetMeta for the empty rowset
2539
126k
    auto rs_meta = std::make_shared<RowsetMeta>();
2540
2541
    // Generate a deterministic rowset ID for the hole (same tablet_id + version = same rowset_id)
2542
126k
    RowsetId hole_rowset_id;
2543
126k
    hole_rowset_id.init(2, 0, tablet->tablet_id(), version);
2544
126k
    rs_meta->set_rowset_id(hole_rowset_id);
2545
2546
    // Generate a deterministic load_id for the hole rowset (same tablet_id + version = same load_id)
2547
126k
    PUniqueId load_id;
2548
126k
    load_id.set_hi(tablet->tablet_id());
2549
126k
    load_id.set_lo(version);
2550
126k
    rs_meta->set_load_id(load_id);
2551
2552
    // Copy schema and other metadata from template
2553
126k
    rs_meta->set_tablet_schema(prev_rowset_meta->tablet_schema());
2554
126k
    rs_meta->set_rowset_type(prev_rowset_meta->rowset_type());
2555
126k
    rs_meta->set_tablet_schema_hash(prev_rowset_meta->tablet_schema_hash());
2556
126k
    rs_meta->set_resource_id(prev_rowset_meta->resource_id());
2557
2558
    // Basic tablet information
2559
126k
    rs_meta->set_tablet_id(tablet->tablet_id());
2560
126k
    rs_meta->set_index_id(tablet->index_id());
2561
126k
    rs_meta->set_partition_id(tablet->partition_id());
2562
126k
    rs_meta->set_tablet_uid(tablet->tablet_uid());
2563
126k
    rs_meta->set_version(Version(version, version));
2564
126k
    rs_meta->set_txn_id(version);
2565
2566
126k
    rs_meta->set_num_rows(0);
2567
126k
    rs_meta->set_total_disk_size(0);
2568
126k
    rs_meta->set_data_disk_size(0);
2569
126k
    rs_meta->set_index_disk_size(0);
2570
126k
    rs_meta->set_empty(true);
2571
126k
    rs_meta->set_num_segments(0);
2572
126k
    rs_meta->set_segments_overlap(NONOVERLAPPING);
2573
126k
    rs_meta->set_rowset_state(VISIBLE);
2574
126k
    rs_meta->set_creation_time(UnixSeconds());
2575
126k
    rs_meta->set_newest_write_timestamp(UnixSeconds());
2576
2577
126k
    Status s = RowsetFactory::create_rowset(nullptr, "", rs_meta, rowset);
2578
126k
    if (!s.ok()) {
2579
0
        LOG_WARNING("Failed to create empty rowset for hole")
2580
0
                .tag("tablet_id", tablet->tablet_id())
2581
0
                .tag("version", version)
2582
0
                .error(s);
2583
0
        return s;
2584
0
    }
2585
126k
    (*rowset)->set_hole_rowset(true);
2586
2587
126k
    return Status::OK();
2588
126k
}
2589
2590
2
Status CloudMetaMgr::list_snapshot(std::vector<SnapshotInfoPB>& snapshots) {
2591
2
    ListSnapshotRequest req;
2592
2
    ListSnapshotResponse res;
2593
2
    req.set_cloud_unique_id(config::cloud_unique_id);
2594
2
    req.set_include_aborted(true);
2595
2
    RETURN_IF_ERROR(retry_rpc(MetaServiceRPC::LIST_SNAPSHOTS, req, &res,
2596
2
                              &MetaService_Stub::list_snapshot,
2597
2
                              {
2598
2
                                      .host_limiters = host_level_ms_rpc_rate_limiters_,
2599
2
                                      .backpressure_handler = ms_backpressure_handler_,
2600
2
                              }));
2601
0
    for (auto& snapshot : res.snapshots()) {
2602
0
        snapshots.emplace_back(snapshot);
2603
0
    }
2604
0
    return Status::OK();
2605
2
}
2606
2607
Status CloudMetaMgr::get_snapshot_properties(SnapshotSwitchStatus& switch_status,
2608
                                             int64_t& max_reserved_snapshots,
2609
1
                                             int64_t& snapshot_interval_seconds) {
2610
1
    GetInstanceRequest req;
2611
1
    GetInstanceResponse res;
2612
1
    req.set_cloud_unique_id(config::cloud_unique_id);
2613
1
    RETURN_IF_ERROR(retry_rpc(MetaServiceRPC::GET_INSTANCE, req, &res,
2614
1
                              &MetaService_Stub::get_instance,
2615
1
                              {
2616
1
                                      .host_limiters = host_level_ms_rpc_rate_limiters_,
2617
1
                                      .backpressure_handler = ms_backpressure_handler_,
2618
1
                              }));
2619
1
    switch_status = res.instance().has_snapshot_switch_status()
2620
1
                            ? res.instance().snapshot_switch_status()
2621
1
                            : SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
2622
1
    max_reserved_snapshots =
2623
1
            res.instance().has_max_reserved_snapshot() ? res.instance().max_reserved_snapshot() : 0;
2624
1
    snapshot_interval_seconds = res.instance().has_snapshot_interval_seconds()
2625
1
                                        ? res.instance().snapshot_interval_seconds()
2626
1
                                        : 3600;
2627
1
    return Status::OK();
2628
1
}
2629
2630
Status CloudMetaMgr::update_packed_file_info(const std::string& packed_file_path,
2631
                                             const cloud::PackedFileInfoPB& packed_file_info,
2632
10.8k
                                             int64_t table_id) {
2633
10.8k
    VLOG_DEBUG << "Updating meta service for packed file: " << packed_file_path << " with "
2634
0
               << packed_file_info.total_slice_num() << " small files"
2635
0
               << ", total bytes: " << packed_file_info.total_slice_bytes();
2636
2637
    // Create request
2638
10.8k
    cloud::UpdatePackedFileInfoRequest req;
2639
10.8k
    cloud::UpdatePackedFileInfoResponse resp;
2640
2641
    // Set required fields
2642
10.8k
    req.set_cloud_unique_id(config::cloud_unique_id);
2643
10.8k
    req.set_packed_file_path(packed_file_path);
2644
10.8k
    *req.mutable_packed_file_info() = packed_file_info;
2645
2646
    // Make RPC call using retry pattern
2647
10.8k
    return retry_rpc(MetaServiceRPC::UPDATE_PACKED_FILE_INFO, req, &resp,
2648
10.8k
                     &cloud::MetaService_Stub::update_packed_file_info,
2649
10.8k
                     {
2650
10.8k
                             .host_limiters = host_level_ms_rpc_rate_limiters_,
2651
10.8k
                             .backpressure_handler = ms_backpressure_handler_,
2652
10.8k
                             .table_id = table_id,
2653
10.8k
                     });
2654
10.8k
}
2655
2656
Status CloudMetaMgr::get_cluster_status(
2657
        std::unordered_map<std::string, std::pair<int32_t, int64_t>>* result,
2658
49
        std::string* my_cluster_id) {
2659
49
    GetClusterStatusRequest req;
2660
49
    GetClusterStatusResponse resp;
2661
49
    req.add_cloud_unique_ids(config::cloud_unique_id);
2662
2663
49
    Status s = retry_rpc(MetaServiceRPC::GET_CLUSTER_STATUS, req, &resp,
2664
49
                         &MetaService_Stub::get_cluster_status,
2665
49
                         {.host_limiters = host_level_ms_rpc_rate_limiters_});
2666
49
    if (!s.ok()) {
2667
0
        return s;
2668
0
    }
2669
2670
49
    result->clear();
2671
49
    for (const auto& detail : resp.details()) {
2672
49
        for (const auto& cluster : detail.clusters()) {
2673
            // Store cluster status and mtime (mtime is in seconds from MS, convert to ms).
2674
            // If mtime is not set, use current time as a conservative default
2675
            // to avoid immediate takeover due to elapsed being huge.
2676
49
            int64_t mtime_ms = cluster.has_mtime() ? cluster.mtime() * 1000 : UnixMillis();
2677
49
            (*result)[cluster.cluster_id()] = {static_cast<int32_t>(cluster.cluster_status()),
2678
49
                                               mtime_ms};
2679
49
        }
2680
49
    }
2681
2682
49
    if (my_cluster_id && resp.has_requester_cluster_id()) {
2683
1
        *my_cluster_id = resp.requester_cluster_id();
2684
1
    }
2685
2686
49
    return Status::OK();
2687
49
}
2688
2689
} // namespace doris::cloud