Coverage Report

Created: 2026-08-10 11:21

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