Coverage Report

Created: 2026-03-15 22:14

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