Coverage Report

Created: 2026-08-03 08:20

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