Coverage Report

Created: 2026-08-06 09:23

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