Coverage Report

Created: 2026-03-18 19:58

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
21
void* run_bthread_work(void* arg) {
75
21
    auto* f = reinterpret_cast<std::function<void()>*>(arg);
76
21
    (*f)();
77
21
    delete f;
78
21
    return nullptr;
79
21
}
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
26
            while (status.ok() && count >= concurrency) {
96
4
                cond.wait(lk);
97
4
            }
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
20
        auto* fn = new std::function<void()>([&, &task = task] {
108
20
            auto st = task();
109
20
            {
110
20
                std::lock_guard lk(lock);
111
20
                --count;
112
20
                if (!st.ok()) {
113
2
                    std::swap(st, status);
114
2
                }
115
20
                cond.notify_one();
116
20
            }
117
20
        });
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
8
        while (count > 0) {
129
4
            cond.wait(lk);
130
4
        }
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
0
    DBUG_EXECUTE_IF("CloudMetaMgr::sync_tablet_rowsets.before.inject_error", {
569
0
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
570
0
        auto target_table_id = dp->param<int64_t>("table_id", -1);
571
0
        if (target_tablet_id == tablet->tablet_id() || target_table_id == tablet->table_id()) {
572
0
            return Status::InternalError(
573
0
                    "[sync_tablet_rowsets_unlocked] injected error for testing");
574
0
        }
575
0
    });
576
577
0
    MetaServiceProxy* proxy;
578
0
    RETURN_IF_ERROR(MetaServiceProxy::get_proxy(&proxy));
579
0
    std::string tablet_info =
580
0
            fmt::format("tablet_id={} table_id={} index_id={} partition_id={}", tablet->tablet_id(),
581
0
                        tablet->table_id(), tablet->index_id(), tablet->partition_id());
582
0
    int tried = 0;
583
0
    while (true) {
584
0
        std::shared_ptr<MetaService_Stub> stub;
585
0
        RETURN_IF_ERROR(proxy->get(&stub));
586
0
        brpc::Controller cntl;
587
0
        cntl.set_timeout_ms(config::meta_service_brpc_timeout_ms);
588
0
        GetRowsetRequest req;
589
0
        GetRowsetResponse resp;
590
591
0
        int64_t tablet_id = tablet->tablet_id();
592
0
        int64_t table_id = tablet->table_id();
593
0
        int64_t index_id = tablet->index_id();
594
0
        req.set_cloud_unique_id(config::cloud_unique_id);
595
0
        auto* idx = req.mutable_idx();
596
0
        idx->set_tablet_id(tablet_id);
597
0
        idx->set_table_id(table_id);
598
0
        idx->set_index_id(index_id);
599
0
        idx->set_partition_id(tablet->partition_id());
600
0
        {
601
0
            auto lock_start = std::chrono::steady_clock::now();
602
0
            std::shared_lock rlock(tablet->get_header_lock());
603
0
            if (sync_stats) {
604
0
                sync_stats->meta_lock_wait_ns +=
605
0
                        std::chrono::duration_cast<std::chrono::nanoseconds>(
606
0
                                std::chrono::steady_clock::now() - lock_start)
607
0
                                .count();
608
0
            }
609
0
            if (options.full_sync) {
610
0
                req.set_start_version(0);
611
0
            } else {
612
0
                req.set_start_version(tablet->max_version_unlocked() + 1);
613
0
            }
614
0
            req.set_base_compaction_cnt(tablet->base_compaction_cnt());
615
0
            req.set_cumulative_compaction_cnt(tablet->cumulative_compaction_cnt());
616
0
            req.set_full_compaction_cnt(tablet->full_compaction_cnt());
617
0
            req.set_cumulative_point(tablet->cumulative_layer_point());
618
0
        }
619
0
        req.set_end_version(-1);
620
0
        VLOG_DEBUG << "send GetRowsetRequest: " << req.ShortDebugString();
621
0
        auto start = std::chrono::steady_clock::now();
622
0
        stub->get_rowset(&cntl, &req, &resp, nullptr);
623
0
        auto end = std::chrono::steady_clock::now();
624
0
        int64_t latency = cntl.latency_us();
625
0
        _get_rowset_latency << latency;
626
0
        int retry_times = config::meta_service_rpc_retry_times;
627
0
        if (cntl.Failed()) {
628
0
            proxy->set_unhealthy();
629
0
            if (tried++ < retry_times) {
630
0
                auto rng = make_random_engine();
631
0
                std::uniform_int_distribution<uint32_t> u(20, 200);
632
0
                std::uniform_int_distribution<uint32_t> u1(500, 1000);
633
0
                uint32_t duration_ms = tried >= 100 ? u(rng) : u1(rng);
634
0
                bthread_usleep(duration_ms * 1000);
635
0
                LOG_INFO("failed to get rowset meta, " + tablet_info)
636
0
                        .tag("reason", cntl.ErrorText())
637
0
                        .tag("tried", tried)
638
0
                        .tag("sleep", duration_ms);
639
0
                continue;
640
0
            }
641
0
            return Status::RpcError("failed to get rowset meta: {}", cntl.ErrorText());
642
0
        }
643
0
        if (resp.status().code() == MetaServiceCode::TABLET_NOT_FOUND) {
644
0
            LOG(WARNING) << "failed to get rowset meta, err=" << resp.status().msg() << " "
645
0
                         << tablet_info;
646
0
            return Status::NotFound("failed to get rowset meta: {}, {}", resp.status().msg(),
647
0
                                    tablet_info);
648
0
        }
649
0
        if (resp.status().code() != MetaServiceCode::OK) {
650
0
            LOG(WARNING) << " failed to get rowset meta, err=" << resp.status().msg() << " "
651
0
                         << tablet_info;
652
0
            return Status::InternalError("failed to get rowset meta: {}, {}", resp.status().msg(),
653
0
                                         tablet_info);
654
0
        }
655
0
        if (latency > 100 * 1000) { // 100ms
656
0
            LOG(INFO) << "finish get_rowset rpc. rowset_meta.size()=" << resp.rowset_meta().size()
657
0
                      << ", latency=" << latency << "us"
658
0
                      << " " << tablet_info;
659
0
        } else {
660
0
            LOG_EVERY_N(INFO, 100)
661
0
                    << "finish get_rowset rpc. rowset_meta.size()=" << resp.rowset_meta().size()
662
0
                    << ", latency=" << latency << "us"
663
0
                    << " " << tablet_info;
664
0
        }
665
666
0
        int64_t now = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
667
0
        tablet->last_sync_time_s = now;
668
669
0
        if (sync_stats) {
670
0
            sync_stats->get_remote_rowsets_rpc_ns +=
671
0
                    std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
672
0
            sync_stats->get_remote_rowsets_num += resp.rowset_meta().size();
673
0
        }
674
675
        // If is mow, the tablet has no delete bitmap in base rowsets.
676
        // So dont need to sync it.
677
0
        if (options.sync_delete_bitmap && tablet->enable_unique_key_merge_on_write() &&
678
0
            tablet->tablet_state() == TABLET_RUNNING) {
679
0
            DBUG_EXECUTE_IF("CloudMetaMgr::sync_tablet_rowsets.sync_tablet_delete_bitmap.block",
680
0
                            DBUG_BLOCK);
681
0
            DeleteBitmap delete_bitmap(tablet_id);
682
0
            int64_t old_max_version = req.start_version() - 1;
683
0
            auto read_version = config::delete_bitmap_store_read_version;
684
0
            auto st = sync_tablet_delete_bitmap(tablet, old_max_version, resp.rowset_meta(),
685
0
                                                resp.stats(), req.idx(), &delete_bitmap,
686
0
                                                options.full_sync, sync_stats, read_version, false);
687
0
            if (st.is<ErrorCode::ROWSETS_EXPIRED>() && tried++ < retry_times) {
688
0
                LOG_INFO("rowset meta is expired, need to retry, " + tablet_info)
689
0
                        .tag("tried", tried)
690
0
                        .error(st);
691
0
                continue;
692
0
            }
693
0
            if (!st.ok()) {
694
0
                LOG_WARNING("failed to get delete bitmap, " + tablet_info).error(st);
695
0
                return st;
696
0
            }
697
0
            tablet->tablet_meta()->delete_bitmap().merge(delete_bitmap);
698
0
            RETURN_IF_ERROR(_log_mow_delete_bitmap(tablet, resp, delete_bitmap, old_max_version,
699
0
                                                   options.full_sync, read_version));
700
0
            RETURN_IF_ERROR(
701
0
                    _check_delete_bitmap_v2_correctness(tablet, req, resp, old_max_version));
702
0
        }
703
0
        DBUG_EXECUTE_IF("CloudMetaMgr::sync_tablet_rowsets.before.modify_tablet_meta", {
704
0
            auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
705
0
            if (target_tablet_id == tablet->tablet_id()) {
706
0
                DBUG_BLOCK
707
0
            }
708
0
        });
709
0
        {
710
0
            const auto& stats = resp.stats();
711
0
            auto lock_start = std::chrono::steady_clock::now();
712
0
            std::unique_lock wlock(tablet->get_header_lock());
713
0
            if (sync_stats) {
714
0
                sync_stats->meta_lock_wait_ns +=
715
0
                        std::chrono::duration_cast<std::chrono::nanoseconds>(
716
0
                                std::chrono::steady_clock::now() - lock_start)
717
0
                                .count();
718
0
            }
719
720
            // ATTN: we are facing following data race
721
            //
722
            // 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
723
            //
724
            //   BE-compaction-thread                 meta-service                                     BE-query-thread
725
            //            |                                |                                                |
726
            //    local   |    commit cumu-compaction      |                                                |
727
            //   cc_cnt=0 |  --------------------------->  |     sync rowset (long rpc, local cc_cnt=0 )    |   local
728
            //            |                                |  <-----------------------------------------    |  cc_cnt=0
729
            //            |                                |  -.                                            |
730
            //    local   |       done cc_cnt=1            |    \                                           |
731
            //   cc_cnt=1 |  <---------------------------  |     \                                          |
732
            //            |                                |      \  returned with resp cc_cnt=0 (snapshot) |
733
            //            |                                |       '------------------------------------>   |   local
734
            //            |                                |                                                |  cc_cnt=1
735
            //            |                                |                                                |
736
            //            |                                |                                                |  CHECK FAIL
737
            //            |                                |                                                |  need retry
738
            // To get rid of just retry syncing tablet
739
0
            if (stats.base_compaction_cnt() < tablet->base_compaction_cnt() ||
740
0
                stats.cumulative_compaction_cnt() < tablet->cumulative_compaction_cnt())
741
0
                    [[unlikely]] {
742
                // stale request, ignore
743
0
                LOG_WARNING("stale get rowset meta request " + tablet_info)
744
0
                        .tag("resp_base_compaction_cnt", stats.base_compaction_cnt())
745
0
                        .tag("base_compaction_cnt", tablet->base_compaction_cnt())
746
0
                        .tag("resp_cumulative_compaction_cnt", stats.cumulative_compaction_cnt())
747
0
                        .tag("cumulative_compaction_cnt", tablet->cumulative_compaction_cnt())
748
0
                        .tag("tried", tried);
749
0
                if (tried++ < 10) continue;
750
0
                return Status::OK();
751
0
            }
752
0
            std::vector<RowsetSharedPtr> rowsets;
753
0
            rowsets.reserve(resp.rowset_meta().size());
754
0
            for (const auto& cloud_rs_meta_pb : resp.rowset_meta()) {
755
0
                VLOG_DEBUG << "get rowset meta, tablet_id=" << cloud_rs_meta_pb.tablet_id()
756
0
                           << ", version=[" << cloud_rs_meta_pb.start_version() << '-'
757
0
                           << cloud_rs_meta_pb.end_version() << ']';
758
0
                auto existed_rowset = tablet->get_rowset_by_version(
759
0
                        {cloud_rs_meta_pb.start_version(), cloud_rs_meta_pb.end_version()});
760
0
                if (existed_rowset &&
761
0
                    existed_rowset->rowset_id().to_string() == cloud_rs_meta_pb.rowset_id_v2()) {
762
0
                    continue; // Same rowset, skip it
763
0
                }
764
0
                RowsetMetaPB meta_pb = cloud_rowset_meta_to_doris(cloud_rs_meta_pb);
765
0
                auto rs_meta = std::make_shared<RowsetMeta>();
766
0
                rs_meta->init_from_pb(meta_pb);
767
0
                RowsetSharedPtr rowset;
768
                // schema is nullptr implies using RowsetMeta.tablet_schema
769
0
                Status s = RowsetFactory::create_rowset(nullptr, "", rs_meta, &rowset);
770
0
                if (!s.ok()) {
771
0
                    LOG_WARNING("create rowset").tag("status", s);
772
0
                    return s;
773
0
                }
774
0
                rowsets.push_back(std::move(rowset));
775
0
            }
776
0
            if (!rowsets.empty()) {
777
                // `rowsets.empty()` could happen after doing EMPTY_CUMULATIVE compaction. e.g.:
778
                //   BE has [0-1][2-11][12-12], [12-12] is delete predicate, cp is 2;
779
                //   after doing EMPTY_CUMULATIVE compaction, MS cp is 13, get_rowset will return [2-11][12-12].
780
0
                bool version_overlap =
781
0
                        tablet->max_version_unlocked() >= rowsets.front()->start_version();
782
0
                tablet->add_rowsets(std::move(rowsets), version_overlap, wlock,
783
0
                                    options.warmup_delta_data ||
784
0
                                            config::enable_warmup_immediately_on_new_rowset);
785
0
            }
786
787
            // Fill version holes
788
0
            int64_t partition_max_version =
789
0
                    resp.has_partition_max_version() ? resp.partition_max_version() : -1;
790
0
            RETURN_IF_ERROR(fill_version_holes(tablet, partition_max_version, wlock));
791
792
0
            tablet->last_base_compaction_success_time_ms = stats.last_base_compaction_time_ms();
793
0
            tablet->last_cumu_compaction_success_time_ms = stats.last_cumu_compaction_time_ms();
794
0
            tablet->set_base_compaction_cnt(stats.base_compaction_cnt());
795
0
            tablet->set_cumulative_compaction_cnt(stats.cumulative_compaction_cnt());
796
0
            tablet->set_full_compaction_cnt(stats.full_compaction_cnt());
797
0
            tablet->set_cumulative_layer_point(stats.cumulative_point());
798
0
            tablet->reset_approximate_stats(stats.num_rowsets(), stats.num_segments(),
799
0
                                            stats.num_rows(), stats.data_size());
800
801
            // Sync last active cluster info for compaction read-write separation
802
0
            if (config::enable_compaction_rw_separation && stats.has_last_active_cluster_id()) {
803
0
                tablet->set_last_active_cluster_info(stats.last_active_cluster_id(),
804
0
                                                     stats.last_active_time_ms());
805
0
            }
806
0
        }
807
0
        return Status::OK();
808
0
    }
809
0
}
810
811
bool CloudMetaMgr::sync_tablet_delete_bitmap_by_cache(CloudTablet* tablet,
812
                                                      std::ranges::range auto&& rs_metas,
813
0
                                                      DeleteBitmap* delete_bitmap) {
814
0
    std::set<int64_t> txn_processed;
815
0
    for (auto& rs_meta : rs_metas) {
816
0
        auto txn_id = rs_meta.txn_id();
817
0
        if (txn_processed.find(txn_id) != txn_processed.end()) {
818
0
            continue;
819
0
        }
820
0
        txn_processed.insert(txn_id);
821
0
        DeleteBitmapPtr tmp_delete_bitmap;
822
0
        std::shared_ptr<PublishStatus> publish_status =
823
0
                std::make_shared<PublishStatus>(PublishStatus::INIT);
824
0
        CloudStorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_cloud();
825
0
        Status status = engine.txn_delete_bitmap_cache().get_delete_bitmap(
826
0
                txn_id, tablet->tablet_id(), &tmp_delete_bitmap, nullptr, &publish_status);
827
        // CloudMetaMgr::sync_tablet_delete_bitmap_by_cache() is called after we sync rowsets from meta services.
828
        // If the control flows reaches here, it's gauranteed that the rowsets is commited in meta services, so we can
829
        // use the delete bitmap from cache directly if *publish_status == PublishStatus::SUCCEED without checking other
830
        // stats(version or compaction stats)
831
0
        if (status.ok() && *publish_status == PublishStatus::SUCCEED) {
832
            // tmp_delete_bitmap contains sentinel marks, we should remove it before merge it to delete bitmap.
833
            // Also, the version of delete bitmap key in tmp_delete_bitmap is DeleteBitmap::TEMP_VERSION_COMMON,
834
            // we should replace it with the rowset's real version
835
0
            DCHECK(rs_meta.start_version() == rs_meta.end_version());
836
0
            int64_t rowset_version = rs_meta.start_version();
837
0
            for (const auto& [delete_bitmap_key, bitmap_value] : tmp_delete_bitmap->delete_bitmap) {
838
                // skip sentinel mark, which is used for delete bitmap correctness check
839
0
                if (std::get<1>(delete_bitmap_key) != DeleteBitmap::INVALID_SEGMENT_ID) {
840
0
                    delete_bitmap->merge({std::get<0>(delete_bitmap_key),
841
0
                                          std::get<1>(delete_bitmap_key), rowset_version},
842
0
                                         bitmap_value);
843
0
                }
844
0
            }
845
0
            engine.txn_delete_bitmap_cache().remove_unused_tablet_txn_info(txn_id,
846
0
                                                                           tablet->tablet_id());
847
0
        } else {
848
0
            LOG_EVERY_N(INFO, 20)
849
0
                    << "delete bitmap not found in cache, will sync rowset to get. tablet_id= "
850
0
                    << tablet->tablet_id() << ", txn_id=" << txn_id << ", status=" << status;
851
0
            return false;
852
0
        }
853
0
    }
854
0
    return true;
855
0
}
856
857
Status CloudMetaMgr::_get_delete_bitmap_from_ms(GetDeleteBitmapRequest& req,
858
11
                                                GetDeleteBitmapResponse& res) {
859
11
    VLOG_DEBUG << "send GetDeleteBitmapRequest: " << req.ShortDebugString();
860
11
    TEST_SYNC_POINT_CALLBACK("CloudMetaMgr::_get_delete_bitmap_from_ms", &req, &res);
861
862
11
    auto st = retry_rpc("get delete bitmap", req, &res, &MetaService_Stub::get_delete_bitmap);
863
11
    if (st.code() == ErrorCode::THRIFT_RPC_ERROR) {
864
0
        return st;
865
0
    }
866
867
11
    if (res.status().code() == MetaServiceCode::TABLET_NOT_FOUND) {
868
1
        return Status::NotFound("failed to get delete bitmap: {}", res.status().msg());
869
1
    }
870
    // The delete bitmap of stale rowsets will be removed when commit compaction job,
871
    // then delete bitmap of stale rowsets cannot be obtained. But the rowsets obtained
872
    // by sync_tablet_rowsets may include these stale rowsets. When this case happend, the
873
    // error code of ROWSETS_EXPIRED will be returned, we need to retry sync rowsets again.
874
    //
875
    // Be query thread             meta-service          Be compaction thread
876
    //      |                            |                         |
877
    //      |        get rowset          |                         |
878
    //      |--------------------------->|                         |
879
    //      |    return get rowset       |                         |
880
    //      |<---------------------------|                         |
881
    //      |                            |        commit job       |
882
    //      |                            |<------------------------|
883
    //      |                            |    return commit job    |
884
    //      |                            |------------------------>|
885
    //      |      get delete bitmap     |                         |
886
    //      |--------------------------->|                         |
887
    //      |  return get delete bitmap  |                         |
888
    //      |<---------------------------|                         |
889
    //      |                            |                         |
890
10
    if (res.status().code() == MetaServiceCode::ROWSETS_EXPIRED) {
891
0
        return Status::Error<ErrorCode::ROWSETS_EXPIRED, false>("failed to get delete bitmap: {}",
892
0
                                                                res.status().msg());
893
0
    }
894
10
    if (res.status().code() != MetaServiceCode::OK) {
895
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>("failed to get delete bitmap: {}",
896
0
                                                               res.status().msg());
897
0
    }
898
10
    return Status::OK();
899
10
}
900
901
Status CloudMetaMgr::_get_delete_bitmap_from_ms_by_batch(GetDeleteBitmapRequest& req,
902
                                                         GetDeleteBitmapResponse& res,
903
6
                                                         int64_t bytes_threadhold) {
904
6
    std::unordered_set<std::string> finished_rowset_ids {};
905
6
    int count = 0;
906
11
    do {
907
11
        GetDeleteBitmapRequest cur_req;
908
11
        GetDeleteBitmapResponse cur_res;
909
910
11
        cur_req.set_cloud_unique_id(config::cloud_unique_id);
911
11
        cur_req.set_tablet_id(req.tablet_id());
912
11
        cur_req.set_base_compaction_cnt(req.base_compaction_cnt());
913
11
        cur_req.set_cumulative_compaction_cnt(req.cumulative_compaction_cnt());
914
11
        cur_req.set_cumulative_point(req.cumulative_point());
915
11
        *(cur_req.mutable_idx()) = req.idx();
916
11
        cur_req.set_store_version(req.store_version());
917
11
        if (bytes_threadhold > 0) {
918
11
            cur_req.set_dbm_bytes_threshold(bytes_threadhold);
919
11
        }
920
45
        for (int i = 0; i < req.rowset_ids_size(); i++) {
921
34
            if (!finished_rowset_ids.contains(req.rowset_ids(i))) {
922
25
                cur_req.add_rowset_ids(req.rowset_ids(i));
923
25
                cur_req.add_begin_versions(req.begin_versions(i));
924
25
                cur_req.add_end_versions(req.end_versions(i));
925
25
            }
926
34
        }
927
928
11
        RETURN_IF_ERROR(_get_delete_bitmap_from_ms(cur_req, cur_res));
929
10
        ++count;
930
931
        // v1 delete bitmap
932
10
        res.mutable_rowset_ids()->MergeFrom(cur_res.rowset_ids());
933
10
        res.mutable_segment_ids()->MergeFrom(cur_res.segment_ids());
934
10
        res.mutable_versions()->MergeFrom(cur_res.versions());
935
10
        res.mutable_segment_delete_bitmaps()->MergeFrom(cur_res.segment_delete_bitmaps());
936
937
        // v2 delete bitmap
938
10
        res.mutable_delta_rowset_ids()->MergeFrom(cur_res.delta_rowset_ids());
939
10
        res.mutable_delete_bitmap_storages()->MergeFrom(cur_res.delete_bitmap_storages());
940
941
15
        for (const auto& rowset_id : cur_res.returned_rowset_ids()) {
942
15
            finished_rowset_ids.insert(rowset_id);
943
15
        }
944
945
10
        bool has_more = cur_res.has_has_more() && cur_res.has_more();
946
10
        if (!has_more) {
947
5
            break;
948
5
        }
949
5
        LOG_INFO("batch get delete bitmap, progress={}/{}", finished_rowset_ids.size(),
950
5
                 req.rowset_ids_size())
951
5
                .tag("tablet_id", req.tablet_id())
952
5
                .tag("cur_returned_rowsets", cur_res.returned_rowset_ids_size())
953
5
                .tag("rpc_count", count);
954
5
    } while (finished_rowset_ids.size() < req.rowset_ids_size());
955
5
    return Status::OK();
956
6
}
957
958
Status CloudMetaMgr::sync_tablet_delete_bitmap(CloudTablet* tablet, int64_t old_max_version,
959
                                               std::ranges::range auto&& rs_metas,
960
                                               const TabletStatsPB& stats, const TabletIndexPB& idx,
961
                                               DeleteBitmap* delete_bitmap, bool full_sync,
962
                                               SyncRowsetStats* sync_stats, int32_t read_version,
963
0
                                               bool full_sync_v2) {
964
0
    if (rs_metas.empty()) {
965
0
        return Status::OK();
966
0
    }
967
968
0
    if (!full_sync && config::enable_sync_tablet_delete_bitmap_by_cache &&
969
0
        sync_tablet_delete_bitmap_by_cache(tablet, rs_metas, delete_bitmap)) {
970
0
        if (sync_stats) {
971
0
            sync_stats->get_local_delete_bitmap_rowsets_num += rs_metas.size();
972
0
        }
973
0
        return Status::OK();
974
0
    } else {
975
0
        DeleteBitmapPtr new_delete_bitmap = std::make_shared<DeleteBitmap>(tablet->tablet_id());
976
0
        *delete_bitmap = *new_delete_bitmap;
977
0
    }
978
979
0
    if (read_version == 2 && config::delete_bitmap_store_write_version == 1) {
980
0
        return Status::InternalError(
981
0
                "please set delete_bitmap_store_read_version to 1 or 3 because "
982
0
                "delete_bitmap_store_write_version is 1");
983
0
    } else if (read_version == 1 && config::delete_bitmap_store_write_version == 2) {
984
0
        return Status::InternalError(
985
0
                "please set delete_bitmap_store_read_version to 2 or 3 because "
986
0
                "delete_bitmap_store_write_version is 2");
987
0
    }
988
989
0
    int64_t new_max_version = std::max(old_max_version, rs_metas.rbegin()->end_version());
990
    // When there are many delete bitmaps that need to be synchronized, it
991
    // may take a longer time, especially when loading the tablet for the
992
    // first time, so set a relatively long timeout time.
993
0
    GetDeleteBitmapRequest req;
994
0
    GetDeleteBitmapResponse res;
995
0
    req.set_cloud_unique_id(config::cloud_unique_id);
996
0
    req.set_tablet_id(tablet->tablet_id());
997
0
    req.set_base_compaction_cnt(stats.base_compaction_cnt());
998
0
    req.set_cumulative_compaction_cnt(stats.cumulative_compaction_cnt());
999
0
    req.set_cumulative_point(stats.cumulative_point());
1000
0
    *(req.mutable_idx()) = idx;
1001
0
    req.set_store_version(read_version);
1002
    // New rowset sync all versions of delete bitmap
1003
0
    for (const auto& rs_meta : rs_metas) {
1004
0
        req.add_rowset_ids(rs_meta.rowset_id_v2());
1005
0
        req.add_begin_versions(0);
1006
0
        req.add_end_versions(new_max_version);
1007
0
    }
1008
1009
0
    if (!full_sync_v2) {
1010
        // old rowset sync incremental versions of delete bitmap
1011
0
        if (old_max_version > 0 && old_max_version < new_max_version) {
1012
0
            RowsetIdUnorderedSet all_rs_ids;
1013
0
            RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1014
0
            for (const auto& rs_id : all_rs_ids) {
1015
0
                req.add_rowset_ids(rs_id.to_string());
1016
0
                req.add_begin_versions(old_max_version + 1);
1017
0
                req.add_end_versions(new_max_version);
1018
0
            }
1019
0
        }
1020
0
    } else {
1021
0
        if (old_max_version > 0) {
1022
0
            RowsetIdUnorderedSet all_rs_ids;
1023
0
            RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1024
0
            for (const auto& rs_id : all_rs_ids) {
1025
0
                req.add_rowset_ids(rs_id.to_string());
1026
0
                req.add_begin_versions(0);
1027
0
                req.add_end_versions(new_max_version);
1028
0
            }
1029
0
        }
1030
0
    }
1031
0
    if (sync_stats) {
1032
0
        sync_stats->get_remote_delete_bitmap_rowsets_num += req.rowset_ids_size();
1033
0
    }
1034
1035
0
    auto start = std::chrono::steady_clock::now();
1036
0
    if (config::enable_batch_get_delete_bitmap) {
1037
0
        RETURN_IF_ERROR(_get_delete_bitmap_from_ms_by_batch(
1038
0
                req, res, config::get_delete_bitmap_bytes_threshold));
1039
0
    } else {
1040
0
        RETURN_IF_ERROR(_get_delete_bitmap_from_ms(req, res));
1041
0
    }
1042
0
    auto end = std::chrono::steady_clock::now();
1043
1044
    // v1 delete bitmap
1045
0
    const auto& rowset_ids = res.rowset_ids();
1046
0
    const auto& segment_ids = res.segment_ids();
1047
0
    const auto& vers = res.versions();
1048
0
    const auto& delete_bitmaps = res.segment_delete_bitmaps();
1049
0
    if (rowset_ids.size() != segment_ids.size() || rowset_ids.size() != vers.size() ||
1050
0
        rowset_ids.size() != delete_bitmaps.size()) {
1051
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
1052
0
                "get delete bitmap data wrong,"
1053
0
                "rowset_ids.size={},segment_ids.size={},vers.size={},delete_bitmaps.size={}",
1054
0
                rowset_ids.size(), segment_ids.size(), vers.size(), delete_bitmaps.size());
1055
0
    }
1056
0
    for (int i = 0; i < rowset_ids.size(); i++) {
1057
0
        RowsetId rst_id;
1058
0
        rst_id.init(rowset_ids[i]);
1059
0
        delete_bitmap->merge(
1060
0
                {rst_id, segment_ids[i], vers[i]},
1061
0
                roaring::Roaring::readSafe(delete_bitmaps[i].data(), delete_bitmaps[i].length()));
1062
0
    }
1063
    // v2 delete bitmap
1064
0
    const auto& delta_rowset_ids = res.delta_rowset_ids();
1065
0
    const auto& delete_bitmap_storages = res.delete_bitmap_storages();
1066
0
    if (delta_rowset_ids.size() != delete_bitmap_storages.size()) {
1067
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
1068
0
                "get delete bitmap data wrong, delta_rowset_ids.size={}, "
1069
0
                "delete_bitmap_storages.size={}",
1070
0
                delta_rowset_ids.size(), delete_bitmap_storages.size());
1071
0
    }
1072
0
    int64_t remote_delete_bitmap_bytes = 0;
1073
0
    RETURN_IF_ERROR(_read_tablet_delete_bitmap_v2(tablet, old_max_version, rs_metas, delete_bitmap,
1074
0
                                                  res, remote_delete_bitmap_bytes, full_sync_v2));
1075
1076
0
    if (sync_stats) {
1077
0
        sync_stats->get_remote_delete_bitmap_rpc_ns +=
1078
0
                std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
1079
0
        sync_stats->get_remote_delete_bitmap_key_count +=
1080
0
                delete_bitmaps.size() + delete_bitmap_storages.size();
1081
0
        for (const auto& dbm : delete_bitmaps) {
1082
0
            sync_stats->get_remote_delete_bitmap_bytes += dbm.length();
1083
0
        }
1084
0
        sync_stats->get_remote_delete_bitmap_bytes += remote_delete_bitmap_bytes;
1085
0
    }
1086
0
    int64_t latency = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1087
0
    if (latency > 100 * 1000) { // 100ms
1088
0
        LOG(INFO) << "finish get_delete_bitmap rpcs. rowset_ids.size()=" << rowset_ids.size()
1089
0
                  << ", delete_bitmaps.size()=" << delete_bitmaps.size()
1090
0
                  << ", delta_delete_bitmaps.size()=" << delta_rowset_ids.size()
1091
0
                  << ", latency=" << latency << "us, read_version=" << read_version;
1092
0
    } else {
1093
0
        LOG_EVERY_N(INFO, 100) << "finish get_delete_bitmap rpcs. rowset_ids.size()="
1094
0
                               << rowset_ids.size()
1095
0
                               << ", delete_bitmaps.size()=" << delete_bitmaps.size()
1096
0
                               << ", delta_delete_bitmaps.size()=" << delta_rowset_ids.size()
1097
0
                               << ", latency=" << latency << "us, read_version=" << read_version;
1098
0
    }
1099
0
    return Status::OK();
1100
0
}
1101
1102
Status CloudMetaMgr::_check_delete_bitmap_v2_correctness(CloudTablet* tablet, GetRowsetRequest& req,
1103
                                                         GetRowsetResponse& resp,
1104
0
                                                         int64_t old_max_version) {
1105
0
    if (!config::enable_delete_bitmap_store_v2_check_correctness ||
1106
0
        config::delete_bitmap_store_write_version == 1 || resp.rowset_meta().empty()) {
1107
0
        return Status::OK();
1108
0
    }
1109
0
    int64_t tablet_id = tablet->tablet_id();
1110
0
    int64_t new_max_version = std::max(old_max_version, resp.rowset_meta().rbegin()->end_version());
1111
    // rowset_id, num_segments
1112
0
    std::vector<std::pair<RowsetId, int64_t>> all_rowsets;
1113
0
    std::map<std::string, std::string> rowset_to_resource;
1114
0
    for (const auto& rs_meta : resp.rowset_meta()) {
1115
0
        RowsetId rowset_id;
1116
0
        rowset_id.init(rs_meta.rowset_id_v2());
1117
0
        all_rowsets.emplace_back(std::make_pair(rowset_id, rs_meta.num_segments()));
1118
0
        rowset_to_resource[rs_meta.rowset_id_v2()] = rs_meta.resource_id();
1119
0
    }
1120
0
    if (old_max_version > 0) {
1121
0
        RowsetIdUnorderedSet all_rs_ids;
1122
0
        RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1123
0
        for (auto& rowset : tablet->get_rowset_by_ids(&all_rs_ids)) {
1124
0
            all_rowsets.emplace_back(std::make_pair(rowset->rowset_id(), rowset->num_segments()));
1125
0
            rowset_to_resource[rowset->rowset_id().to_string()] =
1126
0
                    rowset->rowset_meta()->resource_id();
1127
0
        }
1128
0
    }
1129
1130
0
    auto compare_delete_bitmap = [&](DeleteBitmap* delete_bitmap, int version) {
1131
0
        bool success = true;
1132
0
        for (auto& [rs_id, num_segments] : all_rowsets) {
1133
0
            for (int seg_id = 0; seg_id < num_segments; ++seg_id) {
1134
0
                DeleteBitmap::BitmapKey key = {rs_id, seg_id, new_max_version};
1135
0
                auto dm1 = tablet->tablet_meta()->delete_bitmap().get_agg(key);
1136
0
                auto dm2 = delete_bitmap->get_agg_without_cache(key);
1137
0
                if (*dm1 != *dm2) {
1138
0
                    success = false;
1139
0
                    LOG(WARNING) << "failed to check delete bitmap correctness by v"
1140
0
                                 << std::to_string(version) << ", tablet_id=" << tablet->tablet_id()
1141
0
                                 << ", rowset_id=" << rs_id.to_string() << ", segment_id=" << seg_id
1142
0
                                 << ", max_version=" << new_max_version
1143
0
                                 << ". size1=" << dm1->cardinality()
1144
0
                                 << ", size2=" << dm2->cardinality();
1145
0
                }
1146
0
            }
1147
0
        }
1148
0
        if (success) {
1149
0
            LOG(INFO) << "succeed to check delete bitmap correctness by v"
1150
0
                      << std::to_string(version) << ", tablet_id=" << tablet->tablet_id()
1151
0
                      << ", max_version=" << new_max_version;
1152
0
        }
1153
0
    };
1154
1155
0
    DeleteBitmap full_delete_bitmap(tablet_id);
1156
0
    auto st = sync_tablet_delete_bitmap(tablet, old_max_version, resp.rowset_meta(), resp.stats(),
1157
0
                                        req.idx(), &full_delete_bitmap, false, nullptr, 2, true);
1158
0
    if (!st.ok()) {
1159
0
        LOG_WARNING("failed to check delete bitmap correctness by v2")
1160
0
                .tag("tablet", tablet->tablet_id())
1161
0
                .error(st);
1162
0
    } else {
1163
0
        compare_delete_bitmap(&full_delete_bitmap, 2);
1164
0
    }
1165
0
    return Status::OK();
1166
0
}
1167
1168
Status CloudMetaMgr::_read_tablet_delete_bitmap_v2(CloudTablet* tablet, int64_t old_max_version,
1169
                                                   std::ranges::range auto&& rs_metas,
1170
                                                   DeleteBitmap* delete_bitmap,
1171
                                                   GetDeleteBitmapResponse& res,
1172
                                                   int64_t& remote_delete_bitmap_bytes,
1173
0
                                                   bool full_sync_v2) {
1174
0
    if (res.delta_rowset_ids().empty()) {
1175
0
        return Status::OK();
1176
0
    }
1177
0
    const auto& rowset_ids = res.delta_rowset_ids();
1178
0
    const auto& delete_bitmap_storages = res.delete_bitmap_storages();
1179
0
    RowsetIdUnorderedSet all_rs_ids;
1180
0
    std::map<std::string, std::string> rowset_to_resource;
1181
0
    if (old_max_version > 0) {
1182
0
        RETURN_IF_ERROR(tablet->get_all_rs_id(old_max_version, &all_rs_ids));
1183
0
        if (full_sync_v2) {
1184
0
            for (auto& rowset : tablet->get_rowset_by_ids(&all_rs_ids)) {
1185
0
                rowset_to_resource[rowset->rowset_id().to_string()] =
1186
0
                        rowset->rowset_meta()->resource_id();
1187
0
            }
1188
0
        }
1189
0
    }
1190
0
    for (const auto& rs_meta : rs_metas) {
1191
0
        RowsetId rs_id;
1192
0
        rs_id.init(rs_meta.rowset_id_v2());
1193
0
        all_rs_ids.emplace(rs_id);
1194
0
        rowset_to_resource[rs_meta.rowset_id_v2()] = rs_meta.resource_id();
1195
0
    }
1196
0
    if (config::enable_mow_verbose_log) {
1197
0
        LOG(INFO) << "read delete bitmap for tablet_id=" << tablet->tablet_id()
1198
0
                  << ", old_max_version=" << old_max_version
1199
0
                  << ", new rowset num=" << rs_metas.size()
1200
0
                  << ", rowset has delete bitmap num=" << rowset_ids.size()
1201
0
                  << ". all rowset num=" << all_rs_ids.size();
1202
0
    }
1203
1204
0
    std::mutex result_mtx;
1205
0
    Status result;
1206
0
    auto merge_delete_bitmap = [&](const std::string& rowset_id, DeleteBitmapPB& dbm) {
1207
0
        if (dbm.rowset_ids_size() != dbm.segment_ids_size() ||
1208
0
            dbm.rowset_ids_size() != dbm.versions_size() ||
1209
0
            dbm.rowset_ids_size() != dbm.segment_delete_bitmaps_size()) {
1210
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
1211
0
                    "get delete bitmap data wrong, rowset_id={}"
1212
0
                    "rowset_ids.size={},segment_ids.size={},vers.size={},delete_bitmaps.size={}",
1213
0
                    rowset_id, dbm.rowset_ids_size(), dbm.segment_ids_size(), dbm.versions_size(),
1214
0
                    dbm.segment_delete_bitmaps_size());
1215
0
        }
1216
0
        if (config::enable_mow_verbose_log) {
1217
0
            LOG(INFO) << "get delete bitmap for tablet_id=" << tablet->tablet_id()
1218
0
                      << ", rowset_id=" << rowset_id
1219
0
                      << ", delete_bitmap num=" << dbm.segment_delete_bitmaps_size();
1220
0
        }
1221
0
        std::lock_guard lock(result_mtx);
1222
0
        for (int j = 0; j < dbm.rowset_ids_size(); j++) {
1223
0
            RowsetId rst_id;
1224
0
            rst_id.init(dbm.rowset_ids(j));
1225
0
            if (!all_rs_ids.contains(rst_id)) {
1226
0
                LOG(INFO) << "skip merge delete bitmap for tablet_id=" << tablet->tablet_id()
1227
0
                          << ", rowset_id=" << rowset_id << ", unused rowset_id=" << rst_id;
1228
0
                continue;
1229
0
            }
1230
0
            delete_bitmap->merge(
1231
0
                    {rst_id, dbm.segment_ids(j), dbm.versions(j)},
1232
0
                    roaring::Roaring::readSafe(dbm.segment_delete_bitmaps(j).data(),
1233
0
                                               dbm.segment_delete_bitmaps(j).length()));
1234
0
            remote_delete_bitmap_bytes += dbm.segment_delete_bitmaps(j).length();
1235
0
        }
1236
0
        return Status::OK();
1237
0
    };
1238
0
    auto get_delete_bitmap_from_file = [&](const std::string& rowset_id,
1239
0
                                           const DeleteBitmapStoragePB& storage) {
1240
0
        if (config::enable_mow_verbose_log) {
1241
0
            LOG(INFO) << "get delete bitmap for tablet_id=" << tablet->tablet_id()
1242
0
                      << ", rowset_id=" << rowset_id << " from file"
1243
0
                      << ", is_packed=" << storage.has_packed_slice_location();
1244
0
        }
1245
0
        if (rowset_to_resource.find(rowset_id) == rowset_to_resource.end()) {
1246
0
            return Status::InternalError("vault id not found for tablet_id={}, rowset_id={}",
1247
0
                                         tablet->tablet_id(), rowset_id);
1248
0
        }
1249
0
        auto resource_id = rowset_to_resource[rowset_id];
1250
0
        CloudStorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_cloud();
1251
0
        auto storage_resource = engine.get_storage_resource(resource_id);
1252
0
        if (!storage_resource) {
1253
0
            return Status::InternalError("vault id not found, maybe not sync, vault id {}",
1254
0
                                         resource_id);
1255
0
        }
1256
1257
        // Use packed file reader if packed_slice_location is present
1258
0
        std::unique_ptr<DeleteBitmapFileReader> reader;
1259
0
        if (storage.has_packed_slice_location() &&
1260
0
            !storage.packed_slice_location().packed_file_path().empty()) {
1261
0
            reader = std::make_unique<DeleteBitmapFileReader>(tablet->tablet_id(), rowset_id,
1262
0
                                                              storage_resource,
1263
0
                                                              storage.packed_slice_location());
1264
0
        } else {
1265
0
            reader = std::make_unique<DeleteBitmapFileReader>(tablet->tablet_id(), rowset_id,
1266
0
                                                              storage_resource);
1267
0
        }
1268
1269
0
        RETURN_IF_ERROR(reader->init());
1270
0
        DeleteBitmapPB dbm;
1271
0
        RETURN_IF_ERROR(reader->read(dbm));
1272
0
        RETURN_IF_ERROR(reader->close());
1273
0
        return merge_delete_bitmap(rowset_id, dbm);
1274
0
    };
1275
0
    CloudStorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_cloud();
1276
0
    std::unique_ptr<ThreadPoolToken> token = engine.sync_delete_bitmap_thread_pool().new_token(
1277
0
            ThreadPool::ExecutionMode::CONCURRENT);
1278
0
    bthread::CountdownEvent wait {rowset_ids.size()};
1279
0
    for (int i = 0; i < rowset_ids.size(); i++) {
1280
0
        auto& rowset_id = rowset_ids[i];
1281
0
        if (delete_bitmap_storages[i].store_in_fdb()) {
1282
0
            wait.signal();
1283
0
            DeleteBitmapPB dbm = delete_bitmap_storages[i].delete_bitmap();
1284
0
            RETURN_IF_ERROR(merge_delete_bitmap(rowset_id, dbm));
1285
0
        } else {
1286
0
            const auto& storage = delete_bitmap_storages[i];
1287
0
            auto submit_st = token->submit_func([&, rowset_id, storage]() {
1288
0
                auto status = get_delete_bitmap_from_file(rowset_id, storage);
1289
0
                if (!status.ok()) {
1290
0
                    LOG(WARNING) << "failed to get delete bitmap for tablet_id="
1291
0
                                 << tablet->tablet_id() << ", rowset_id=" << rowset_id
1292
0
                                 << " from file, st=" << status.to_string();
1293
0
                    std::lock_guard lock(result_mtx);
1294
0
                    if (result.ok()) {
1295
0
                        result = status;
1296
0
                    }
1297
0
                }
1298
0
                wait.signal();
1299
0
            });
1300
0
            RETURN_IF_ERROR(submit_st);
1301
0
        }
1302
0
    }
1303
    // wait for all finished
1304
0
    wait.wait();
1305
0
    token->wait();
1306
0
    return result;
1307
0
}
1308
1309
Status CloudMetaMgr::prepare_rowset(const RowsetMeta& rs_meta, const std::string& job_id,
1310
0
                                    RowsetMetaSharedPtr* existed_rs_meta) {
1311
0
    VLOG_DEBUG << "prepare rowset, tablet_id: " << rs_meta.tablet_id()
1312
0
               << ", rowset_id: " << rs_meta.rowset_id() << " txn_id: " << rs_meta.txn_id();
1313
0
    {
1314
0
        Status ret_st;
1315
0
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::prepare_rowset", ret_st);
1316
0
    }
1317
0
    CreateRowsetRequest req;
1318
0
    CreateRowsetResponse resp;
1319
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1320
0
    req.set_txn_id(rs_meta.txn_id());
1321
0
    req.set_tablet_job_id(job_id);
1322
1323
0
    RowsetMetaPB doris_rs_meta = rs_meta.get_rowset_pb(/*skip_schema=*/true);
1324
0
    doris_rowset_meta_to_cloud(req.mutable_rowset_meta(), std::move(doris_rs_meta));
1325
1326
0
    Status st = retry_rpc("prepare rowset", req, &resp, &MetaService_Stub::prepare_rowset);
1327
0
    if (!st.ok() && resp.status().code() == MetaServiceCode::ALREADY_EXISTED) {
1328
0
        if (existed_rs_meta != nullptr && resp.has_existed_rowset_meta()) {
1329
0
            RowsetMetaPB doris_rs_meta_tmp =
1330
0
                    cloud_rowset_meta_to_doris(std::move(*resp.mutable_existed_rowset_meta()));
1331
0
            *existed_rs_meta = std::make_shared<RowsetMeta>();
1332
0
            (*existed_rs_meta)->init_from_pb(doris_rs_meta_tmp);
1333
0
        }
1334
0
        return Status::AlreadyExist("failed to prepare rowset: {}", resp.status().msg());
1335
0
    }
1336
0
    return st;
1337
0
}
1338
1339
Status CloudMetaMgr::commit_rowset(RowsetMeta& rs_meta, const std::string& job_id,
1340
0
                                   RowsetMetaSharedPtr* existed_rs_meta) {
1341
0
    VLOG_DEBUG << "commit rowset, tablet_id: " << rs_meta.tablet_id()
1342
0
               << ", rowset_id: " << rs_meta.rowset_id() << " txn_id: " << rs_meta.txn_id();
1343
0
    {
1344
0
        Status ret_st;
1345
0
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::commit_rowset", ret_st);
1346
0
    }
1347
0
    check_table_size_correctness(rs_meta);
1348
0
    CreateRowsetRequest req;
1349
0
    CreateRowsetResponse resp;
1350
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1351
0
    req.set_txn_id(rs_meta.txn_id());
1352
0
    req.set_tablet_job_id(job_id);
1353
1354
0
    RowsetMetaPB rs_meta_pb = rs_meta.get_rowset_pb();
1355
0
    doris_rowset_meta_to_cloud(req.mutable_rowset_meta(), std::move(rs_meta_pb));
1356
0
    Status st = retry_rpc("commit rowset", req, &resp, &MetaService_Stub::commit_rowset);
1357
0
    if (!st.ok() && resp.status().code() == MetaServiceCode::ALREADY_EXISTED) {
1358
0
        if (existed_rs_meta != nullptr && resp.has_existed_rowset_meta()) {
1359
0
            RowsetMetaPB doris_rs_meta =
1360
0
                    cloud_rowset_meta_to_doris(std::move(*resp.mutable_existed_rowset_meta()));
1361
0
            *existed_rs_meta = std::make_shared<RowsetMeta>();
1362
0
            (*existed_rs_meta)->init_from_pb(doris_rs_meta);
1363
0
        }
1364
0
        return Status::AlreadyExist("failed to commit rowset: {}", resp.status().msg());
1365
0
    }
1366
0
    int64_t timeout_ms = -1;
1367
    // if the `job_id` is not empty, it means this rowset was produced by a compaction job.
1368
0
    if (config::enable_compaction_delay_commit_for_warm_up && !job_id.empty()) {
1369
        // 1. assume the download speed is 100MB/s
1370
        // 2. we double the download time as timeout for safety
1371
        // 3. for small rowsets, the timeout we calculate maybe quite small, so we need a min_time_out
1372
0
        const double speed_mbps = 100.0; // 100MB/s
1373
0
        const double safety_factor = 2.0;
1374
0
        timeout_ms = std::min(
1375
0
                std::max(static_cast<int64_t>(static_cast<double>(rs_meta.total_disk_size()) /
1376
0
                                              (speed_mbps * 1024 * 1024) * safety_factor * 1000),
1377
0
                         config::warm_up_rowset_sync_wait_min_timeout_ms),
1378
0
                config::warm_up_rowset_sync_wait_max_timeout_ms);
1379
0
        LOG(INFO) << "warm up rowset: " << rs_meta.version() << ", job_id: " << job_id
1380
0
                  << ", with timeout: " << timeout_ms << " ms";
1381
0
    }
1382
0
    auto& manager = ExecEnv::GetInstance()->storage_engine().to_cloud().cloud_warm_up_manager();
1383
0
    manager.warm_up_rowset(rs_meta, timeout_ms);
1384
0
    return st;
1385
0
}
1386
1387
0
void CloudMetaMgr::cache_committed_rowset(RowsetMetaSharedPtr rs_meta, int64_t expiration_time) {
1388
    // For load-generated rowsets (job_id is empty), add to pending rowset manager
1389
    // so FE can notify BE to promote them later
1390
1391
    // TODO(bobhan1): copy rs_meta?
1392
0
    int64_t txn_id = rs_meta->txn_id();
1393
0
    int64_t tablet_id = rs_meta->tablet_id();
1394
0
    ExecEnv::GetInstance()->storage_engine().to_cloud().committed_rs_mgr().add_committed_rowset(
1395
0
            txn_id, tablet_id, std::move(rs_meta), expiration_time);
1396
0
}
1397
1398
0
Status CloudMetaMgr::update_tmp_rowset(const RowsetMeta& rs_meta) {
1399
0
    VLOG_DEBUG << "update committed rowset, tablet_id: " << rs_meta.tablet_id()
1400
0
               << ", rowset_id: " << rs_meta.rowset_id();
1401
0
    CreateRowsetRequest req;
1402
0
    CreateRowsetResponse resp;
1403
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1404
1405
    // Variant schema maybe updated, so we need to update the schema as well.
1406
    // The updated rowset meta after `rowset->merge_rowset_meta` in `BaseTablet::update_delete_bitmap`
1407
    // 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
1408
    // for variant type
1409
0
    bool skip_schema = rs_meta.tablet_schema()->num_variant_columns() == 0;
1410
0
    RowsetMetaPB rs_meta_pb = rs_meta.get_rowset_pb(skip_schema);
1411
0
    doris_rowset_meta_to_cloud(req.mutable_rowset_meta(), std::move(rs_meta_pb));
1412
0
    Status st =
1413
0
            retry_rpc("update committed rowset", req, &resp, &MetaService_Stub::update_tmp_rowset);
1414
0
    if (!st.ok() && resp.status().code() == MetaServiceCode::ROWSET_META_NOT_FOUND) {
1415
0
        return Status::InternalError("failed to update committed rowset: {}", resp.status().msg());
1416
0
    }
1417
0
    return st;
1418
0
}
1419
1420
// async send TableStats(in res) to FE coz we are in streamload ctx, response to the user ASAP
1421
static void send_stats_to_fe_async(const int64_t db_id, const int64_t txn_id,
1422
0
                                   const std::string& label, CommitTxnResponse& res) {
1423
0
    std::string protobufBytes;
1424
0
    res.SerializeToString(&protobufBytes);
1425
0
    auto st = ExecEnv::GetInstance()->send_table_stats_thread_pool()->submit_func(
1426
0
            [db_id, txn_id, label, protobufBytes]() -> Status {
1427
0
                TReportCommitTxnResultRequest request;
1428
0
                TStatus result;
1429
1430
0
                if (protobufBytes.length() <= 0) {
1431
0
                    LOG(WARNING) << "protobufBytes: " << protobufBytes.length();
1432
0
                    return Status::OK(); // nobody cares the return status
1433
0
                }
1434
1435
0
                request.__set_dbId(db_id);
1436
0
                request.__set_txnId(txn_id);
1437
0
                request.__set_label(label);
1438
0
                request.__set_payload(protobufBytes);
1439
1440
0
                Status status;
1441
0
                int64_t duration_ns = 0;
1442
0
                TNetworkAddress master_addr =
1443
0
                        ExecEnv::GetInstance()->cluster_info()->master_fe_addr;
1444
0
                if (master_addr.hostname.empty() || master_addr.port == 0) {
1445
0
                    status = Status::Error<SERVICE_UNAVAILABLE>(
1446
0
                            "Have not get FE Master heartbeat yet");
1447
0
                } else {
1448
0
                    SCOPED_RAW_TIMER(&duration_ns);
1449
1450
0
                    RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
1451
0
                            master_addr.hostname, master_addr.port,
1452
0
                            [&request, &result](FrontendServiceConnection& client) {
1453
0
                                client->reportCommitTxnResult(result, request);
1454
0
                            }));
1455
1456
0
                    status = Status::create<false>(result);
1457
0
                }
1458
0
                g_cloud_commit_txn_resp_redirect_latency << duration_ns / 1000;
1459
1460
0
                if (!status.ok()) {
1461
0
                    LOG(WARNING) << "TableStats report RPC to FE failed, errmsg=" << status
1462
0
                                 << " dbId=" << db_id << " txnId=" << txn_id << " label=" << label;
1463
0
                    return Status::OK(); // nobody cares the return status
1464
0
                } else {
1465
0
                    LOG(INFO) << "TableStats report RPC to FE success, msg=" << status
1466
0
                              << " dbId=" << db_id << " txnId=" << txn_id << " label=" << label;
1467
0
                    return Status::OK();
1468
0
                }
1469
0
            });
1470
0
    if (!st.ok()) {
1471
0
        LOG(WARNING) << "TableStats report to FE task submission failed: " << st.to_string();
1472
0
    }
1473
0
}
1474
1475
0
Status CloudMetaMgr::commit_txn(const StreamLoadContext& ctx, bool is_2pc) {
1476
0
    VLOG_DEBUG << "commit txn, db_id: " << ctx.db_id << ", txn_id: " << ctx.txn_id
1477
0
               << ", label: " << ctx.label << ", is_2pc: " << is_2pc;
1478
0
    {
1479
0
        Status ret_st;
1480
0
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::commit_txn", ret_st);
1481
0
    }
1482
0
    CommitTxnRequest req;
1483
0
    CommitTxnResponse res;
1484
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1485
0
    req.set_db_id(ctx.db_id);
1486
0
    req.set_txn_id(ctx.txn_id);
1487
0
    req.set_is_2pc(is_2pc);
1488
0
    req.set_enable_txn_lazy_commit(config::enable_cloud_txn_lazy_commit);
1489
0
    auto st = retry_rpc("commit txn", req, &res, &MetaService_Stub::commit_txn);
1490
1491
0
    if (st.ok()) {
1492
0
        send_stats_to_fe_async(ctx.db_id, ctx.txn_id, ctx.label, res);
1493
0
    }
1494
1495
0
    return st;
1496
0
}
1497
1498
0
Status CloudMetaMgr::abort_txn(const StreamLoadContext& ctx) {
1499
0
    VLOG_DEBUG << "abort txn, db_id: " << ctx.db_id << ", txn_id: " << ctx.txn_id
1500
0
               << ", label: " << ctx.label;
1501
0
    {
1502
0
        Status ret_st;
1503
0
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::abort_txn", ret_st);
1504
0
    }
1505
0
    AbortTxnRequest req;
1506
0
    AbortTxnResponse res;
1507
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1508
0
    req.set_reason(std::string(ctx.status.msg().substr(0, 1024)));
1509
0
    if (ctx.db_id > 0 && !ctx.label.empty()) {
1510
0
        req.set_db_id(ctx.db_id);
1511
0
        req.set_label(ctx.label);
1512
0
    } else if (ctx.txn_id > 0) {
1513
0
        req.set_txn_id(ctx.txn_id);
1514
0
    } else {
1515
0
        LOG(WARNING) << "failed abort txn, with illegal input, db_id=" << ctx.db_id
1516
0
                     << " txn_id=" << ctx.txn_id << " label=" << ctx.label;
1517
0
        return Status::InternalError<false>("failed to abort txn");
1518
0
    }
1519
0
    return retry_rpc("abort txn", req, &res, &MetaService_Stub::abort_txn);
1520
0
}
1521
1522
0
Status CloudMetaMgr::precommit_txn(const StreamLoadContext& ctx) {
1523
0
    VLOG_DEBUG << "precommit txn, db_id: " << ctx.db_id << ", txn_id: " << ctx.txn_id
1524
0
               << ", label: " << ctx.label;
1525
0
    {
1526
0
        Status ret_st;
1527
0
        TEST_INJECTION_POINT_RETURN_WITH_VALUE("CloudMetaMgr::precommit_txn", ret_st);
1528
0
    }
1529
0
    PrecommitTxnRequest req;
1530
0
    PrecommitTxnResponse res;
1531
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1532
0
    req.set_db_id(ctx.db_id);
1533
0
    req.set_txn_id(ctx.txn_id);
1534
0
    return retry_rpc("precommit txn", req, &res, &MetaService_Stub::precommit_txn);
1535
0
}
1536
1537
0
Status CloudMetaMgr::prepare_restore_job(const TabletMetaPB& tablet_meta) {
1538
0
    VLOG_DEBUG << "prepare restore job, tablet_id: " << tablet_meta.tablet_id();
1539
0
    RestoreJobRequest req;
1540
0
    RestoreJobResponse resp;
1541
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1542
0
    req.set_tablet_id(tablet_meta.tablet_id());
1543
0
    req.set_expiration(config::snapshot_expire_time_sec);
1544
0
    req.set_action(RestoreJobRequest::PREPARE);
1545
1546
0
    doris_tablet_meta_to_cloud(req.mutable_tablet_meta(), std::move(tablet_meta));
1547
0
    return retry_rpc("prepare restore job", req, &resp, &MetaService_Stub::prepare_restore_job);
1548
0
}
1549
1550
0
Status CloudMetaMgr::commit_restore_job(const int64_t tablet_id) {
1551
0
    VLOG_DEBUG << "commit restore job, tablet_id: " << tablet_id;
1552
0
    RestoreJobRequest req;
1553
0
    RestoreJobResponse resp;
1554
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1555
0
    req.set_tablet_id(tablet_id);
1556
0
    req.set_action(RestoreJobRequest::COMMIT);
1557
0
    req.set_store_version(config::delete_bitmap_store_write_version);
1558
1559
0
    return retry_rpc("commit restore job", req, &resp, &MetaService_Stub::commit_restore_job);
1560
0
}
1561
1562
0
Status CloudMetaMgr::finish_restore_job(const int64_t tablet_id, bool is_completed) {
1563
0
    VLOG_DEBUG << "finish restore job, tablet_id: " << tablet_id
1564
0
               << ", is_completed: " << is_completed;
1565
0
    RestoreJobRequest req;
1566
0
    RestoreJobResponse resp;
1567
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1568
0
    req.set_tablet_id(tablet_id);
1569
0
    req.set_action(is_completed ? RestoreJobRequest::COMPLETE : RestoreJobRequest::ABORT);
1570
1571
0
    return retry_rpc("finish restore job", req, &resp, &MetaService_Stub::finish_restore_job);
1572
0
}
1573
1574
0
Status CloudMetaMgr::get_storage_vault_info(StorageVaultInfos* vault_infos, bool* is_vault_mode) {
1575
0
    GetObjStoreInfoRequest req;
1576
0
    GetObjStoreInfoResponse resp;
1577
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1578
0
    Status s =
1579
0
            retry_rpc("get storage vault info", req, &resp, &MetaService_Stub::get_obj_store_info);
1580
0
    if (!s.ok()) {
1581
0
        return s;
1582
0
    }
1583
1584
0
    *is_vault_mode = resp.enable_storage_vault();
1585
1586
0
    auto add_obj_store = [&vault_infos](const auto& obj_store) {
1587
0
        vault_infos->emplace_back(obj_store.id(), S3Conf::get_s3_conf(obj_store),
1588
0
                                  StorageVaultPB_PathFormat {});
1589
0
    };
1590
1591
0
    std::ranges::for_each(resp.obj_info(), add_obj_store);
1592
0
    std::ranges::for_each(resp.storage_vault(), [&](const auto& vault) {
1593
0
        if (vault.has_hdfs_info()) {
1594
0
            vault_infos->emplace_back(vault.id(), vault.hdfs_info(), vault.path_format());
1595
0
        }
1596
0
        if (vault.has_obj_info()) {
1597
0
            add_obj_store(vault.obj_info());
1598
0
        }
1599
0
    });
1600
1601
    // desensitization, hide secret
1602
0
    for (int i = 0; i < resp.obj_info_size(); ++i) {
1603
0
        resp.mutable_obj_info(i)->set_sk(resp.obj_info(i).sk().substr(0, 2) + "xxx");
1604
0
    }
1605
0
    for (int i = 0; i < resp.storage_vault_size(); ++i) {
1606
0
        auto* j = resp.mutable_storage_vault(i);
1607
0
        if (!j->has_obj_info()) continue;
1608
0
        j->mutable_obj_info()->set_sk(j->obj_info().sk().substr(0, 2) + "xxx");
1609
0
    }
1610
1611
0
    for (int i = 0; i < resp.obj_info_size(); ++i) {
1612
0
        resp.mutable_obj_info(i)->set_ak(hide_access_key(resp.obj_info(i).sk()));
1613
0
    }
1614
0
    for (int i = 0; i < resp.storage_vault_size(); ++i) {
1615
0
        auto* j = resp.mutable_storage_vault(i);
1616
0
        if (!j->has_obj_info()) continue;
1617
0
        j->mutable_obj_info()->set_sk(hide_access_key(j->obj_info().sk()));
1618
0
    }
1619
1620
0
    LOG(INFO) << "get storage vault, enable_storage_vault=" << *is_vault_mode
1621
0
              << " response=" << resp.ShortDebugString();
1622
0
    return Status::OK();
1623
0
}
1624
1625
7
Status CloudMetaMgr::prepare_tablet_job(const TabletJobInfoPB& job, StartTabletJobResponse* res) {
1626
7
    VLOG_DEBUG << "prepare_tablet_job: " << job.ShortDebugString();
1627
7
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::prepare_tablet_job", Status::OK(), job, res);
1628
1629
0
    StartTabletJobRequest req;
1630
0
    req.mutable_job()->CopyFrom(job);
1631
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1632
0
    return retry_rpc("start tablet job", req, res, &MetaService_Stub::start_tablet_job);
1633
7
}
1634
1635
2
Status CloudMetaMgr::commit_tablet_job(const TabletJobInfoPB& job, FinishTabletJobResponse* res) {
1636
2
    VLOG_DEBUG << "commit_tablet_job: " << job.ShortDebugString();
1637
2
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudMetaMgr::commit_tablet_job", Status::OK(), job, res);
1638
0
    DBUG_EXECUTE_IF("CloudMetaMgr::commit_tablet_job.fail", {
1639
0
        return Status::InternalError<false>("inject CloudMetaMgr::commit_tablet_job.fail");
1640
0
    });
1641
1642
0
    FinishTabletJobRequest req;
1643
0
    req.mutable_job()->CopyFrom(job);
1644
0
    req.set_action(FinishTabletJobRequest::COMMIT);
1645
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1646
0
    auto st = retry_rpc("commit tablet job", req, res, &MetaService_Stub::finish_tablet_job);
1647
0
    if (res->status().code() == MetaServiceCode::KV_TXN_CONFLICT_RETRY_EXCEEDED_MAX_TIMES) {
1648
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
1649
0
                "txn conflict when commit tablet job {}", job.ShortDebugString());
1650
0
    }
1651
0
    return st;
1652
0
}
1653
1654
0
Status CloudMetaMgr::abort_tablet_job(const TabletJobInfoPB& job) {
1655
0
    VLOG_DEBUG << "abort_tablet_job: " << job.ShortDebugString();
1656
0
    FinishTabletJobRequest req;
1657
0
    FinishTabletJobResponse res;
1658
0
    req.mutable_job()->CopyFrom(job);
1659
0
    req.set_action(FinishTabletJobRequest::ABORT);
1660
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1661
0
    return retry_rpc("abort tablet job", req, &res, &MetaService_Stub::finish_tablet_job);
1662
0
}
1663
1664
0
Status CloudMetaMgr::lease_tablet_job(const TabletJobInfoPB& job) {
1665
0
    VLOG_DEBUG << "lease_tablet_job: " << job.ShortDebugString();
1666
0
    FinishTabletJobRequest req;
1667
0
    FinishTabletJobResponse res;
1668
0
    req.mutable_job()->CopyFrom(job);
1669
0
    req.set_action(FinishTabletJobRequest::LEASE);
1670
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1671
0
    return retry_rpc("lease tablet job", req, &res, &MetaService_Stub::finish_tablet_job);
1672
0
}
1673
1674
static void add_delete_bitmap(DeleteBitmapPB& delete_bitmap_pb, const DeleteBitmap::BitmapKey& key,
1675
0
                              roaring::Roaring& bitmap) {
1676
0
    delete_bitmap_pb.add_rowset_ids(std::get<0>(key).to_string());
1677
0
    delete_bitmap_pb.add_segment_ids(std::get<1>(key));
1678
0
    delete_bitmap_pb.add_versions(std::get<2>(key));
1679
    // To save space, convert array and bitmap containers to run containers
1680
0
    bitmap.runOptimize();
1681
0
    std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
1682
0
    bitmap.write(bitmap_data.data());
1683
0
    *(delete_bitmap_pb.add_segment_delete_bitmaps()) = std::move(bitmap_data);
1684
0
}
1685
1686
static Status store_delete_bitmap(std::string& rowset_id, DeleteBitmapPB& delete_bitmap_pb,
1687
                                  int64_t tablet_id,
1688
                                  std::optional<StorageResource> storage_resource,
1689
0
                                  UpdateDeleteBitmapRequest& req, int64_t txn_id) {
1690
0
    if (config::enable_mow_verbose_log) {
1691
0
        std::stringstream ss;
1692
0
        for (int i = 0; i < delete_bitmap_pb.rowset_ids_size(); i++) {
1693
0
            ss << "{rid=" << delete_bitmap_pb.rowset_ids(i)
1694
0
               << ", sid=" << delete_bitmap_pb.segment_ids(i)
1695
0
               << ", ver=" << delete_bitmap_pb.versions(i) << "}, ";
1696
0
        }
1697
0
        LOG(INFO) << "handle one rowset delete bitmap for tablet_id: " << tablet_id
1698
0
                  << ", rowset_id: " << rowset_id
1699
0
                  << ", delete_bitmap num: " << delete_bitmap_pb.rowset_ids_size()
1700
0
                  << ",  size: " << delete_bitmap_pb.ByteSizeLong() << ", keys=[" << ss.str()
1701
0
                  << "]";
1702
0
    }
1703
0
    if (delete_bitmap_pb.rowset_ids_size() == 0) {
1704
0
        return Status::OK();
1705
0
    }
1706
0
    DeleteBitmapStoragePB delete_bitmap_storage;
1707
0
    if (config::delete_bitmap_store_v2_max_bytes_in_fdb >= 0 &&
1708
0
        delete_bitmap_pb.ByteSizeLong() > config::delete_bitmap_store_v2_max_bytes_in_fdb) {
1709
        // Enable packed file only for load (txn_id > 0)
1710
0
        bool enable_packed = config::enable_packed_file && txn_id > 0;
1711
0
        DeleteBitmapFileWriter file_writer(tablet_id, rowset_id, storage_resource, enable_packed,
1712
0
                                           txn_id);
1713
0
        RETURN_IF_ERROR(file_writer.init());
1714
0
        RETURN_IF_ERROR(file_writer.write(delete_bitmap_pb));
1715
0
        RETURN_IF_ERROR(file_writer.close());
1716
0
        delete_bitmap_pb.Clear();
1717
0
        delete_bitmap_storage.set_store_in_fdb(false);
1718
1719
        // Store packed slice location if file was written to packed file
1720
0
        if (file_writer.is_packed()) {
1721
0
            io::PackedSliceLocation loc;
1722
0
            RETURN_IF_ERROR(file_writer.get_packed_slice_location(&loc));
1723
0
            auto* packed_loc = delete_bitmap_storage.mutable_packed_slice_location();
1724
0
            packed_loc->set_packed_file_path(loc.packed_file_path);
1725
0
            packed_loc->set_offset(loc.offset);
1726
0
            packed_loc->set_size(loc.size);
1727
0
            packed_loc->set_packed_file_size(loc.packed_file_size);
1728
0
        }
1729
0
    } else {
1730
0
        delete_bitmap_storage.set_store_in_fdb(true);
1731
0
        *(delete_bitmap_storage.mutable_delete_bitmap()) = std::move(delete_bitmap_pb);
1732
0
    }
1733
0
    req.add_delta_rowset_ids(rowset_id);
1734
0
    *(req.add_delete_bitmap_storages()) = std::move(delete_bitmap_storage);
1735
0
    return Status::OK();
1736
0
}
1737
1738
Status CloudMetaMgr::update_delete_bitmap(const CloudTablet& tablet, int64_t lock_id,
1739
                                          int64_t initiator, DeleteBitmap* delete_bitmap,
1740
                                          DeleteBitmap* delete_bitmap_v2, std::string rowset_id,
1741
                                          std::optional<StorageResource> storage_resource,
1742
                                          int64_t store_version, int64_t txn_id,
1743
0
                                          bool is_explicit_txn, int64_t next_visible_version) {
1744
0
    VLOG_DEBUG << "update_delete_bitmap , tablet_id: " << tablet.tablet_id();
1745
0
    if (config::enable_mow_verbose_log) {
1746
0
        std::stringstream ss;
1747
0
        ss << "start update delete bitmap for tablet_id: " << tablet.tablet_id()
1748
0
           << ", rowset_id: " << rowset_id
1749
0
           << ", delete_bitmap num: " << delete_bitmap->delete_bitmap.size()
1750
0
           << ", store_version: " << store_version << ", lock_id=" << lock_id
1751
0
           << ", initiator=" << initiator;
1752
0
        if (store_version == 2 || store_version == 3) {
1753
0
            ss << ", delete_bitmap v2 num: " << delete_bitmap_v2->delete_bitmap.size();
1754
0
        }
1755
0
        LOG(INFO) << ss.str();
1756
0
    }
1757
0
    UpdateDeleteBitmapRequest req;
1758
0
    UpdateDeleteBitmapResponse res;
1759
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1760
0
    req.set_table_id(tablet.table_id());
1761
0
    req.set_partition_id(tablet.partition_id());
1762
0
    req.set_tablet_id(tablet.tablet_id());
1763
0
    req.set_lock_id(lock_id);
1764
0
    req.set_initiator(initiator);
1765
0
    req.set_is_explicit_txn(is_explicit_txn);
1766
0
    if (txn_id > 0) {
1767
0
        req.set_txn_id(txn_id);
1768
0
    }
1769
0
    if (next_visible_version > 0) {
1770
0
        req.set_next_visible_version(next_visible_version);
1771
0
    }
1772
0
    req.set_store_version(store_version);
1773
1774
0
    bool write_v1 = store_version == 1 || store_version == 3;
1775
0
    bool write_v2 = store_version == 2 || store_version == 3;
1776
    // write v1 kvs
1777
0
    if (write_v1) {
1778
0
        for (auto& [key, bitmap] : delete_bitmap->delete_bitmap) {
1779
0
            req.add_rowset_ids(std::get<0>(key).to_string());
1780
0
            req.add_segment_ids(std::get<1>(key));
1781
0
            req.add_versions(std::get<2>(key));
1782
            // To save space, convert array and bitmap containers to run containers
1783
0
            bitmap.runOptimize();
1784
0
            std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
1785
0
            bitmap.write(bitmap_data.data());
1786
0
            *(req.add_segment_delete_bitmaps()) = std::move(bitmap_data);
1787
0
        }
1788
0
    }
1789
1790
    // write v2 kvs
1791
0
    if (write_v2) {
1792
0
        if (config::enable_mow_verbose_log) {
1793
0
            LOG(INFO) << "update delete bitmap for tablet_id: " << tablet.tablet_id()
1794
0
                      << ", rowset_id: " << rowset_id
1795
0
                      << ", delete_bitmap num: " << delete_bitmap_v2->delete_bitmap.size()
1796
0
                      << ", lock_id=" << lock_id << ", initiator=" << initiator;
1797
0
        }
1798
0
        if (rowset_id.empty()) {
1799
0
            std::string pre_rowset_id = "";
1800
0
            std::string cur_rowset_id = "";
1801
0
            DeleteBitmapPB delete_bitmap_pb;
1802
0
            for (auto it = delete_bitmap_v2->delete_bitmap.begin();
1803
0
                 it != delete_bitmap_v2->delete_bitmap.end(); ++it) {
1804
0
                auto& key = it->first;
1805
0
                auto& bitmap = it->second;
1806
0
                cur_rowset_id = std::get<0>(key).to_string();
1807
0
                if (cur_rowset_id != pre_rowset_id) {
1808
0
                    if (!pre_rowset_id.empty() && delete_bitmap_pb.rowset_ids_size() > 0) {
1809
0
                        RETURN_IF_ERROR(store_delete_bitmap(pre_rowset_id, delete_bitmap_pb,
1810
0
                                                            tablet.tablet_id(), storage_resource,
1811
0
                                                            req, txn_id));
1812
0
                    }
1813
0
                    pre_rowset_id = cur_rowset_id;
1814
0
                    DCHECK_EQ(delete_bitmap_pb.rowset_ids_size(), 0);
1815
0
                    DCHECK_EQ(delete_bitmap_pb.segment_ids_size(), 0);
1816
0
                    DCHECK_EQ(delete_bitmap_pb.versions_size(), 0);
1817
0
                    DCHECK_EQ(delete_bitmap_pb.segment_delete_bitmaps_size(), 0);
1818
0
                }
1819
0
                add_delete_bitmap(delete_bitmap_pb, key, bitmap);
1820
0
            }
1821
0
            if (delete_bitmap_pb.rowset_ids_size() > 0) {
1822
0
                DCHECK(!cur_rowset_id.empty());
1823
0
                RETURN_IF_ERROR(store_delete_bitmap(cur_rowset_id, delete_bitmap_pb,
1824
0
                                                    tablet.tablet_id(), storage_resource, req,
1825
0
                                                    txn_id));
1826
0
            }
1827
0
        } else {
1828
0
            DeleteBitmapPB delete_bitmap_pb;
1829
0
            for (auto& [key, bitmap] : delete_bitmap_v2->delete_bitmap) {
1830
0
                add_delete_bitmap(delete_bitmap_pb, key, bitmap);
1831
0
            }
1832
0
            RETURN_IF_ERROR(store_delete_bitmap(rowset_id, delete_bitmap_pb, tablet.tablet_id(),
1833
0
                                                storage_resource, req, txn_id));
1834
0
        }
1835
0
        DCHECK_EQ(req.delta_rowset_ids_size(), req.delete_bitmap_storages_size());
1836
0
    }
1837
0
    DBUG_EXECUTE_IF("CloudMetaMgr::test_update_big_delete_bitmap", {
1838
0
        LOG(INFO) << "test_update_big_delete_bitmap for tablet " << tablet.tablet_id();
1839
0
        auto count = dp->param<int>("count", 30000);
1840
0
        if (!delete_bitmap->delete_bitmap.empty()) {
1841
0
            auto& key = delete_bitmap->delete_bitmap.begin()->first;
1842
0
            auto& bitmap = delete_bitmap->delete_bitmap.begin()->second;
1843
0
            for (int i = 1000; i < (1000 + count); i++) {
1844
0
                req.add_rowset_ids(std::get<0>(key).to_string());
1845
0
                req.add_segment_ids(std::get<1>(key));
1846
0
                req.add_versions(i);
1847
                // To save space, convert array and bitmap containers to run containers
1848
0
                bitmap.runOptimize();
1849
0
                std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
1850
0
                bitmap.write(bitmap_data.data());
1851
0
                *(req.add_segment_delete_bitmaps()) = std::move(bitmap_data);
1852
0
            }
1853
0
        }
1854
0
    });
1855
0
    DBUG_EXECUTE_IF("CloudMetaMgr::test_update_delete_bitmap_fail", {
1856
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR>(
1857
0
                "test update delete bitmap failed, tablet_id: {}, lock_id: {}", tablet.tablet_id(),
1858
0
                lock_id);
1859
0
    });
1860
0
    auto st = retry_rpc("update delete bitmap", req, &res, &MetaService_Stub::update_delete_bitmap);
1861
0
    if (config::enable_update_delete_bitmap_kv_check_core &&
1862
0
        res.status().code() == MetaServiceCode::UPDATE_OVERRIDE_EXISTING_KV) {
1863
0
        auto& msg = res.status().msg();
1864
0
        LOG_WARNING(msg);
1865
0
        CHECK(false) << msg;
1866
0
    }
1867
0
    if (res.status().code() == MetaServiceCode::LOCK_EXPIRED) {
1868
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
1869
0
                "lock expired when update delete bitmap, tablet_id: {}, lock_id: {}, initiator: "
1870
0
                "{}, error_msg: {}",
1871
0
                tablet.tablet_id(), lock_id, initiator, res.status().msg());
1872
0
    }
1873
0
    return st;
1874
0
}
1875
1876
Status CloudMetaMgr::cloud_update_delete_bitmap_without_lock(
1877
        const CloudTablet& tablet, DeleteBitmap* delete_bitmap,
1878
        std::map<std::string, int64_t>& rowset_to_versions, int64_t pre_rowset_agg_start_version,
1879
0
        int64_t pre_rowset_agg_end_version) {
1880
0
    if (config::delete_bitmap_store_write_version == 2) {
1881
0
        VLOG_DEBUG << "no need to agg delete bitmap v1 in ms because use v2";
1882
0
        return Status::OK();
1883
0
    }
1884
0
    LOG(INFO) << "cloud_update_delete_bitmap_without_lock, tablet_id: " << tablet.tablet_id()
1885
0
              << ", delete_bitmap size: " << delete_bitmap->delete_bitmap.size();
1886
0
    UpdateDeleteBitmapRequest req;
1887
0
    UpdateDeleteBitmapResponse res;
1888
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1889
0
    req.set_table_id(tablet.table_id());
1890
0
    req.set_partition_id(tablet.partition_id());
1891
0
    req.set_tablet_id(tablet.tablet_id());
1892
    // use a fake lock id to resolve compatibility issues
1893
0
    req.set_lock_id(-3);
1894
0
    req.set_without_lock(true);
1895
0
    for (auto& [key, bitmap] : delete_bitmap->delete_bitmap) {
1896
0
        req.add_rowset_ids(std::get<0>(key).to_string());
1897
0
        req.add_segment_ids(std::get<1>(key));
1898
0
        req.add_versions(std::get<2>(key));
1899
0
        if (pre_rowset_agg_end_version > 0) {
1900
0
            DCHECK(rowset_to_versions.find(std::get<0>(key).to_string()) !=
1901
0
                   rowset_to_versions.end())
1902
0
                    << "rowset_to_versions not found for key=" << std::get<0>(key).to_string();
1903
0
            req.add_pre_rowset_versions(rowset_to_versions[std::get<0>(key).to_string()]);
1904
0
        }
1905
0
        DCHECK(pre_rowset_agg_end_version <= 0 || pre_rowset_agg_end_version == std::get<2>(key))
1906
0
                << "pre_rowset_agg_end_version=" << pre_rowset_agg_end_version
1907
0
                << " not equal to version=" << std::get<2>(key);
1908
        // To save space, convert array and bitmap containers to run containers
1909
0
        bitmap.runOptimize();
1910
0
        std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
1911
0
        bitmap.write(bitmap_data.data());
1912
0
        *(req.add_segment_delete_bitmaps()) = std::move(bitmap_data);
1913
0
    }
1914
0
    if (pre_rowset_agg_start_version > 0 && pre_rowset_agg_end_version > 0) {
1915
0
        req.set_pre_rowset_agg_start_version(pre_rowset_agg_start_version);
1916
0
        req.set_pre_rowset_agg_end_version(pre_rowset_agg_end_version);
1917
0
    }
1918
0
    return retry_rpc("update delete bitmap", req, &res, &MetaService_Stub::update_delete_bitmap);
1919
0
}
1920
1921
Status CloudMetaMgr::get_delete_bitmap_update_lock(const CloudTablet& tablet, int64_t lock_id,
1922
0
                                                   int64_t initiator) {
1923
0
    DBUG_EXECUTE_IF("get_delete_bitmap_update_lock.inject_fail", {
1924
0
        auto p = dp->param("percent", 0.01);
1925
0
        std::mt19937 gen {std::random_device {}()};
1926
0
        std::bernoulli_distribution inject_fault {p};
1927
0
        if (inject_fault(gen)) {
1928
0
            return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR>(
1929
0
                    "injection error when get get_delete_bitmap_update_lock, "
1930
0
                    "tablet_id={}, lock_id={}, initiator={}",
1931
0
                    tablet.tablet_id(), lock_id, initiator);
1932
0
        }
1933
0
    });
1934
0
    VLOG_DEBUG << "get_delete_bitmap_update_lock , tablet_id: " << tablet.tablet_id()
1935
0
               << ",lock_id:" << lock_id;
1936
0
    GetDeleteBitmapUpdateLockRequest req;
1937
0
    GetDeleteBitmapUpdateLockResponse res;
1938
0
    req.set_cloud_unique_id(config::cloud_unique_id);
1939
0
    req.set_table_id(tablet.table_id());
1940
0
    req.set_lock_id(lock_id);
1941
0
    req.set_initiator(initiator);
1942
    // set expiration time for compaction and schema_change
1943
0
    req.set_expiration(config::delete_bitmap_lock_expiration_seconds);
1944
0
    int retry_times = 0;
1945
0
    Status st;
1946
0
    std::default_random_engine rng = make_random_engine();
1947
0
    std::uniform_int_distribution<uint32_t> u(500, 2000);
1948
0
    uint64_t backoff_sleep_time_ms {0};
1949
0
    do {
1950
0
        bool test_conflict = false;
1951
0
        st = retry_rpc("get delete bitmap update lock", req, &res,
1952
0
                       &MetaService_Stub::get_delete_bitmap_update_lock);
1953
0
        DBUG_EXECUTE_IF("CloudMetaMgr::test_get_delete_bitmap_update_lock_conflict",
1954
0
                        { test_conflict = true; });
1955
0
        if (!test_conflict && res.status().code() != MetaServiceCode::LOCK_CONFLICT) {
1956
0
            break;
1957
0
        }
1958
1959
0
        uint32_t duration_ms = u(rng);
1960
0
        LOG(WARNING) << "get delete bitmap lock conflict. " << debug_info(req)
1961
0
                     << " retry_times=" << retry_times << " sleep=" << duration_ms
1962
0
                     << "ms : " << res.status().msg();
1963
0
        auto start = std::chrono::steady_clock::now();
1964
0
        bthread_usleep(duration_ms * 1000);
1965
0
        auto end = std::chrono::steady_clock::now();
1966
0
        backoff_sleep_time_ms += duration_cast<std::chrono::milliseconds>(end - start).count();
1967
0
    } while (++retry_times <= config::get_delete_bitmap_lock_max_retry_times);
1968
0
    g_cloud_be_mow_get_dbm_lock_backoff_sleep_time << backoff_sleep_time_ms;
1969
0
    DBUG_EXECUTE_IF("CloudMetaMgr.get_delete_bitmap_update_lock.inject_sleep", {
1970
0
        auto p = dp->param("percent", 0.01);
1971
        // 100s > Config.calculate_delete_bitmap_task_timeout_seconds = 60s
1972
0
        auto sleep_time = dp->param("sleep", 15);
1973
0
        std::mt19937 gen {std::random_device {}()};
1974
0
        std::bernoulli_distribution inject_fault {p};
1975
0
        if (inject_fault(gen)) {
1976
0
            LOG_INFO("injection sleep for {} seconds, tablet_id={}", sleep_time,
1977
0
                     tablet.tablet_id());
1978
0
            std::this_thread::sleep_for(std::chrono::seconds(sleep_time));
1979
0
        }
1980
0
    });
1981
0
    if (res.status().code() == MetaServiceCode::KV_TXN_CONFLICT_RETRY_EXCEEDED_MAX_TIMES) {
1982
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
1983
0
                "txn conflict when get delete bitmap update lock, table_id {}, lock_id {}, "
1984
0
                "initiator {}",
1985
0
                tablet.table_id(), lock_id, initiator);
1986
0
    } else if (res.status().code() == MetaServiceCode::LOCK_CONFLICT) {
1987
0
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR, false>(
1988
0
                "lock conflict when get delete bitmap update lock, table_id {}, lock_id {}, "
1989
0
                "initiator {}",
1990
0
                tablet.table_id(), lock_id, initiator);
1991
0
    }
1992
0
    return st;
1993
0
}
1994
1995
void CloudMetaMgr::remove_delete_bitmap_update_lock(int64_t table_id, int64_t lock_id,
1996
0
                                                    int64_t initiator, int64_t tablet_id) {
1997
0
    LOG(INFO) << "remove_delete_bitmap_update_lock ,table_id: " << table_id
1998
0
              << ",lock_id:" << lock_id << ",initiator:" << initiator << ",tablet_id:" << tablet_id;
1999
0
    RemoveDeleteBitmapUpdateLockRequest req;
2000
0
    RemoveDeleteBitmapUpdateLockResponse res;
2001
0
    req.set_cloud_unique_id(config::cloud_unique_id);
2002
0
    req.set_table_id(table_id);
2003
0
    req.set_tablet_id(tablet_id);
2004
0
    req.set_lock_id(lock_id);
2005
0
    req.set_initiator(initiator);
2006
0
    auto st = retry_rpc("remove delete bitmap update lock", req, &res,
2007
0
                        &MetaService_Stub::remove_delete_bitmap_update_lock);
2008
0
    if (!st.ok()) {
2009
0
        LOG(WARNING) << "remove delete bitmap update lock fail,table_id=" << table_id
2010
0
                     << ",tablet_id=" << tablet_id << ",lock_id=" << lock_id
2011
0
                     << ",st=" << st.to_string();
2012
0
    }
2013
0
}
2014
2015
0
void CloudMetaMgr::check_table_size_correctness(RowsetMeta& rs_meta) {
2016
0
    if (!config::enable_table_size_correctness_check) {
2017
0
        return;
2018
0
    }
2019
0
    int64_t total_segment_size = get_segment_file_size(rs_meta);
2020
0
    int64_t total_inverted_index_size = get_inverted_index_file_size(rs_meta);
2021
0
    if (rs_meta.data_disk_size() != total_segment_size ||
2022
0
        rs_meta.index_disk_size() != total_inverted_index_size ||
2023
0
        rs_meta.data_disk_size() + rs_meta.index_disk_size() != rs_meta.total_disk_size()) {
2024
0
        LOG(WARNING) << "[Cloud table table size check failed]:"
2025
0
                     << " tablet id: " << rs_meta.tablet_id()
2026
0
                     << ", rowset id:" << rs_meta.rowset_id()
2027
0
                     << ", rowset data disk size:" << rs_meta.data_disk_size()
2028
0
                     << ", rowset real data disk size:" << total_segment_size
2029
0
                     << ", rowset index disk size:" << rs_meta.index_disk_size()
2030
0
                     << ", rowset real index disk size:" << total_inverted_index_size
2031
0
                     << ", rowset total disk size:" << rs_meta.total_disk_size()
2032
0
                     << ", rowset segment path:"
2033
0
                     << StorageResource().remote_segment_path(rs_meta.tablet_id(),
2034
0
                                                              rs_meta.rowset_id().to_string(), 0);
2035
0
        DCHECK(false);
2036
0
    }
2037
0
}
2038
2039
0
int64_t CloudMetaMgr::get_segment_file_size(RowsetMeta& rs_meta) {
2040
0
    int64_t total_segment_size = 0;
2041
0
    const auto fs = rs_meta.fs();
2042
0
    if (!fs) {
2043
0
        LOG(WARNING) << "get fs failed, resource_id={}" << rs_meta.resource_id();
2044
0
    }
2045
0
    for (int64_t seg_id = 0; seg_id < rs_meta.num_segments(); seg_id++) {
2046
0
        std::string segment_path = StorageResource().remote_segment_path(
2047
0
                rs_meta.tablet_id(), rs_meta.rowset_id().to_string(), seg_id);
2048
0
        int64_t segment_file_size = 0;
2049
0
        auto st = fs->file_size(segment_path, &segment_file_size);
2050
0
        if (!st.ok()) {
2051
0
            segment_file_size = 0;
2052
0
            if (st.is<NOT_FOUND>()) {
2053
0
                LOG(INFO) << "cloud table size correctness check get segment size 0 because "
2054
0
                             "file not exist! msg:"
2055
0
                          << st.msg() << ", segment path:" << segment_path;
2056
0
            } else {
2057
0
                LOG(WARNING) << "cloud table size correctness check get segment size failed! msg:"
2058
0
                             << st.msg() << ", segment path:" << segment_path;
2059
0
            }
2060
0
        }
2061
0
        total_segment_size += segment_file_size;
2062
0
    }
2063
0
    return total_segment_size;
2064
0
}
2065
2066
0
int64_t CloudMetaMgr::get_inverted_index_file_size(RowsetMeta& rs_meta) {
2067
0
    int64_t total_inverted_index_size = 0;
2068
0
    const auto fs = rs_meta.fs();
2069
0
    if (!fs) {
2070
0
        LOG(WARNING) << "get fs failed, resource_id={}" << rs_meta.resource_id();
2071
0
    }
2072
0
    if (rs_meta.tablet_schema()->get_inverted_index_storage_format() ==
2073
0
        InvertedIndexStorageFormatPB::V1) {
2074
0
        const auto& indices = rs_meta.tablet_schema()->inverted_indexes();
2075
0
        for (auto& index : indices) {
2076
0
            for (int seg_id = 0; seg_id < rs_meta.num_segments(); ++seg_id) {
2077
0
                std::string segment_path = StorageResource().remote_segment_path(
2078
0
                        rs_meta.tablet_id(), rs_meta.rowset_id().to_string(), seg_id);
2079
0
                int64_t file_size = 0;
2080
2081
0
                std::string inverted_index_file_path =
2082
0
                        InvertedIndexDescriptor::get_index_file_path_v1(
2083
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(segment_path),
2084
0
                                index->index_id(), index->get_index_suffix());
2085
0
                auto st = fs->file_size(inverted_index_file_path, &file_size);
2086
0
                if (!st.ok()) {
2087
0
                    file_size = 0;
2088
0
                    if (st.is<NOT_FOUND>()) {
2089
0
                        LOG(INFO) << "cloud table size correctness check get inverted index v1 "
2090
0
                                     "0 because file not exist! msg:"
2091
0
                                  << st.msg()
2092
0
                                  << ", inverted index path:" << inverted_index_file_path;
2093
0
                    } else {
2094
0
                        LOG(WARNING)
2095
0
                                << "cloud table size correctness check get inverted index v1 "
2096
0
                                   "size failed! msg:"
2097
0
                                << st.msg() << ", inverted index path:" << inverted_index_file_path;
2098
0
                    }
2099
0
                }
2100
0
                total_inverted_index_size += file_size;
2101
0
            }
2102
0
        }
2103
0
    } else {
2104
0
        for (int seg_id = 0; seg_id < rs_meta.num_segments(); ++seg_id) {
2105
0
            int64_t file_size = 0;
2106
0
            std::string segment_path = StorageResource().remote_segment_path(
2107
0
                    rs_meta.tablet_id(), rs_meta.rowset_id().to_string(), seg_id);
2108
2109
0
            std::string inverted_index_file_path = InvertedIndexDescriptor::get_index_file_path_v2(
2110
0
                    InvertedIndexDescriptor::get_index_file_path_prefix(segment_path));
2111
0
            auto st = fs->file_size(inverted_index_file_path, &file_size);
2112
0
            if (!st.ok()) {
2113
0
                file_size = 0;
2114
0
                if (st.is<NOT_FOUND>()) {
2115
0
                    LOG(INFO) << "cloud table size correctness check get inverted index v2 "
2116
0
                                 "0 because file not exist! msg:"
2117
0
                              << st.msg() << ", inverted index path:" << inverted_index_file_path;
2118
0
                } else {
2119
0
                    LOG(WARNING) << "cloud table size correctness check get inverted index v2 "
2120
0
                                    "size failed! msg:"
2121
0
                                 << st.msg()
2122
0
                                 << ", inverted index path:" << inverted_index_file_path;
2123
0
                }
2124
0
            }
2125
0
            total_inverted_index_size += file_size;
2126
0
        }
2127
0
    }
2128
0
    return total_inverted_index_size;
2129
0
}
2130
2131
Status CloudMetaMgr::fill_version_holes(CloudTablet* tablet, int64_t max_version,
2132
9
                                        std::unique_lock<std::shared_mutex>& wlock) {
2133
9
    if (max_version <= 0) {
2134
2
        return Status::OK();
2135
2
    }
2136
2137
7
    Versions existing_versions;
2138
19
    for (const auto& [_, rs] : tablet->tablet_meta()->all_rs_metas()) {
2139
19
        existing_versions.emplace_back(rs->version());
2140
19
    }
2141
2142
    // If there are no existing versions, it may be a new tablet for restore, so skip filling holes.
2143
7
    if (existing_versions.empty()) {
2144
1
        return Status::OK();
2145
1
    }
2146
2147
6
    std::vector<RowsetSharedPtr> hole_rowsets;
2148
    // sort the existing versions in ascending order
2149
6
    std::sort(existing_versions.begin(), existing_versions.end(),
2150
13
              [](const Version& a, const Version& b) {
2151
                  // simple because 2 versions are certainly not overlapping
2152
13
                  return a.first < b.first;
2153
13
              });
2154
2155
    // During schema change, get_tablet operations on new tablets trigger sync_tablet_rowsets which calls
2156
    // fill_version_holes. For schema change tablets (TABLET_NOTREADY state), we selectively skip hole
2157
    // filling for versions <= alter_version to prevent:
2158
    // 1. Abnormal compaction score calculations for schema change tablets
2159
    // 2. Unexpected -235 errors during load operations
2160
    // This allows schema change to proceed normally while still permitting hole filling for versions
2161
    // beyond the alter_version threshold.
2162
6
    bool is_schema_change_tablet = tablet->tablet_state() == TABLET_NOTREADY;
2163
6
    if (is_schema_change_tablet && tablet->alter_version() <= 1) {
2164
0
        LOG(INFO) << "Skip version hole filling for new schema change tablet "
2165
0
                  << tablet->tablet_id() << " with alter_version " << tablet->alter_version();
2166
0
        return Status::OK();
2167
0
    }
2168
2169
6
    int64_t last_version = -1;
2170
19
    for (const Version& version : existing_versions) {
2171
19
        VLOG_NOTICE << "Existing version for tablet " << tablet->tablet_id() << ": ["
2172
0
                    << version.first << ", " << version.second << "]";
2173
        // missing versions are those that are not in the existing_versions
2174
19
        if (version.first > last_version + 1) {
2175
            // there is a hole between versions
2176
6
            auto prev_non_hole_rowset = tablet->get_rowset_by_version(version);
2177
16
            for (int64_t ver = last_version + 1; ver < version.first; ++ver) {
2178
                // Skip hole filling for versions <= alter_version during schema change
2179
10
                if (is_schema_change_tablet && ver <= tablet->alter_version()) {
2180
0
                    continue;
2181
0
                }
2182
10
                RowsetSharedPtr hole_rowset;
2183
10
                RETURN_IF_ERROR(create_empty_rowset_for_hole(
2184
10
                        tablet, ver, prev_non_hole_rowset->rowset_meta(), &hole_rowset));
2185
10
                hole_rowsets.push_back(hole_rowset);
2186
10
            }
2187
6
            LOG(INFO) << "Created empty rowset for version hole, from " << last_version + 1
2188
6
                      << " to " << version.first - 1 << " for tablet " << tablet->tablet_id()
2189
6
                      << (is_schema_change_tablet
2190
6
                                  ? (", schema change tablet skipped filling versions <= " +
2191
0
                                     std::to_string(tablet->alter_version()))
2192
6
                                  : "");
2193
6
        }
2194
19
        last_version = version.second;
2195
19
    }
2196
2197
6
    if (last_version + 1 <= max_version) {
2198
2
        LOG(INFO) << "Created empty rowset for version hole, from " << last_version + 1 << " to "
2199
2
                  << max_version << " for tablet " << tablet->tablet_id()
2200
2
                  << (is_schema_change_tablet
2201
2
                              ? (", schema change tablet skipped filling versions <= " +
2202
0
                                 std::to_string(tablet->alter_version()))
2203
2
                              : "");
2204
        // there is a hole after the last existing version
2205
7
        for (; last_version + 1 <= max_version; ++last_version) {
2206
            // Skip hole filling for versions <= alter_version during schema change
2207
5
            if (is_schema_change_tablet && last_version + 1 <= tablet->alter_version()) {
2208
0
                continue;
2209
0
            }
2210
5
            RowsetSharedPtr hole_rowset;
2211
5
            auto prev_non_hole_rowset = tablet->get_rowset_by_version(existing_versions.back());
2212
5
            RETURN_IF_ERROR(create_empty_rowset_for_hole(
2213
5
                    tablet, last_version + 1, prev_non_hole_rowset->rowset_meta(), &hole_rowset));
2214
5
            hole_rowsets.push_back(hole_rowset);
2215
5
        }
2216
2
    }
2217
2218
6
    if (!hole_rowsets.empty()) {
2219
5
        size_t hole_count = hole_rowsets.size();
2220
5
        tablet->add_rowsets(std::move(hole_rowsets), false, wlock, false);
2221
5
        g_cloud_version_hole_filled_count << hole_count;
2222
5
    }
2223
6
    return Status::OK();
2224
6
}
2225
2226
Status CloudMetaMgr::create_empty_rowset_for_hole(CloudTablet* tablet, int64_t version,
2227
                                                  RowsetMetaSharedPtr prev_rowset_meta,
2228
19
                                                  RowsetSharedPtr* rowset) {
2229
    // Create a RowsetMeta for the empty rowset
2230
19
    auto rs_meta = std::make_shared<RowsetMeta>();
2231
2232
    // Generate a deterministic rowset ID for the hole (same tablet_id + version = same rowset_id)
2233
19
    RowsetId hole_rowset_id;
2234
19
    hole_rowset_id.init(2, 0, tablet->tablet_id(), version);
2235
19
    rs_meta->set_rowset_id(hole_rowset_id);
2236
2237
    // Generate a deterministic load_id for the hole rowset (same tablet_id + version = same load_id)
2238
19
    PUniqueId load_id;
2239
19
    load_id.set_hi(tablet->tablet_id());
2240
19
    load_id.set_lo(version);
2241
19
    rs_meta->set_load_id(load_id);
2242
2243
    // Copy schema and other metadata from template
2244
19
    rs_meta->set_tablet_schema(prev_rowset_meta->tablet_schema());
2245
19
    rs_meta->set_rowset_type(prev_rowset_meta->rowset_type());
2246
19
    rs_meta->set_tablet_schema_hash(prev_rowset_meta->tablet_schema_hash());
2247
19
    rs_meta->set_resource_id(prev_rowset_meta->resource_id());
2248
2249
    // Basic tablet information
2250
19
    rs_meta->set_tablet_id(tablet->tablet_id());
2251
19
    rs_meta->set_index_id(tablet->index_id());
2252
19
    rs_meta->set_partition_id(tablet->partition_id());
2253
19
    rs_meta->set_tablet_uid(tablet->tablet_uid());
2254
19
    rs_meta->set_version(Version(version, version));
2255
19
    rs_meta->set_txn_id(version);
2256
2257
19
    rs_meta->set_num_rows(0);
2258
19
    rs_meta->set_total_disk_size(0);
2259
19
    rs_meta->set_data_disk_size(0);
2260
19
    rs_meta->set_index_disk_size(0);
2261
19
    rs_meta->set_empty(true);
2262
19
    rs_meta->set_num_segments(0);
2263
19
    rs_meta->set_segments_overlap(NONOVERLAPPING);
2264
19
    rs_meta->set_rowset_state(VISIBLE);
2265
19
    rs_meta->set_creation_time(UnixSeconds());
2266
19
    rs_meta->set_newest_write_timestamp(UnixSeconds());
2267
2268
19
    Status s = RowsetFactory::create_rowset(nullptr, "", rs_meta, rowset);
2269
19
    if (!s.ok()) {
2270
0
        LOG_WARNING("Failed to create empty rowset for hole")
2271
0
                .tag("tablet_id", tablet->tablet_id())
2272
0
                .tag("version", version)
2273
0
                .error(s);
2274
0
        return s;
2275
0
    }
2276
19
    (*rowset)->set_hole_rowset(true);
2277
2278
19
    return Status::OK();
2279
19
}
2280
2281
0
Status CloudMetaMgr::list_snapshot(std::vector<SnapshotInfoPB>& snapshots) {
2282
0
    ListSnapshotRequest req;
2283
0
    ListSnapshotResponse res;
2284
0
    req.set_cloud_unique_id(config::cloud_unique_id);
2285
0
    req.set_include_aborted(true);
2286
0
    RETURN_IF_ERROR(retry_rpc("list snapshot", req, &res, &MetaService_Stub::list_snapshot));
2287
0
    for (auto& snapshot : res.snapshots()) {
2288
0
        snapshots.emplace_back(snapshot);
2289
0
    }
2290
0
    return Status::OK();
2291
0
}
2292
2293
Status CloudMetaMgr::get_snapshot_properties(SnapshotSwitchStatus& switch_status,
2294
                                             int64_t& max_reserved_snapshots,
2295
0
                                             int64_t& snapshot_interval_seconds) {
2296
0
    GetInstanceRequest req;
2297
0
    GetInstanceResponse res;
2298
0
    req.set_cloud_unique_id(config::cloud_unique_id);
2299
0
    RETURN_IF_ERROR(
2300
0
            retry_rpc("get snapshot properties", req, &res, &MetaService_Stub::get_instance));
2301
0
    switch_status = res.instance().has_snapshot_switch_status()
2302
0
                            ? res.instance().snapshot_switch_status()
2303
0
                            : SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
2304
0
    max_reserved_snapshots =
2305
0
            res.instance().has_max_reserved_snapshot() ? res.instance().max_reserved_snapshot() : 0;
2306
0
    snapshot_interval_seconds = res.instance().has_snapshot_interval_seconds()
2307
0
                                        ? res.instance().snapshot_interval_seconds()
2308
0
                                        : 3600;
2309
0
    return Status::OK();
2310
0
}
2311
2312
Status CloudMetaMgr::update_packed_file_info(const std::string& packed_file_path,
2313
0
                                             const cloud::PackedFileInfoPB& packed_file_info) {
2314
0
    VLOG_DEBUG << "Updating meta service for packed file: " << packed_file_path << " with "
2315
0
               << packed_file_info.total_slice_num() << " small files"
2316
0
               << ", total bytes: " << packed_file_info.total_slice_bytes();
2317
2318
    // Create request
2319
0
    cloud::UpdatePackedFileInfoRequest req;
2320
0
    cloud::UpdatePackedFileInfoResponse resp;
2321
2322
    // Set required fields
2323
0
    req.set_cloud_unique_id(config::cloud_unique_id);
2324
0
    req.set_packed_file_path(packed_file_path);
2325
0
    *req.mutable_packed_file_info() = packed_file_info;
2326
2327
    // Make RPC call using retry pattern
2328
0
    return retry_rpc("update packed file info", req, &resp,
2329
0
                     &cloud::MetaService_Stub::update_packed_file_info);
2330
0
}
2331
2332
Status CloudMetaMgr::get_cluster_status(
2333
        std::unordered_map<std::string, std::pair<int32_t, int64_t>>* result,
2334
0
        std::string* my_cluster_id) {
2335
0
    GetClusterStatusRequest req;
2336
0
    GetClusterStatusResponse resp;
2337
0
    req.add_cloud_unique_ids(config::cloud_unique_id);
2338
2339
0
    Status s = retry_rpc("get cluster status", req, &resp, &MetaService_Stub::get_cluster_status);
2340
0
    if (!s.ok()) {
2341
0
        return s;
2342
0
    }
2343
2344
0
    result->clear();
2345
0
    for (const auto& detail : resp.details()) {
2346
0
        for (const auto& cluster : detail.clusters()) {
2347
            // Store cluster status and mtime (mtime is in seconds from MS, convert to ms).
2348
            // If mtime is not set, use current time as a conservative default
2349
            // to avoid immediate takeover due to elapsed being huge.
2350
0
            int64_t mtime_ms = cluster.has_mtime() ? cluster.mtime() * 1000 : UnixMillis();
2351
0
            (*result)[cluster.cluster_id()] = {static_cast<int32_t>(cluster.cluster_status()),
2352
0
                                               mtime_ms};
2353
0
        }
2354
0
    }
2355
2356
0
    if (my_cluster_id && resp.has_requester_cluster_id()) {
2357
0
        *my_cluster_id = resp.requester_cluster_id();
2358
0
    }
2359
2360
0
    return Status::OK();
2361
0
}
2362
2363
#include "common/compile_check_end.h"
2364
} // namespace doris::cloud