Coverage Report

Created: 2026-04-11 00:05

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