Coverage Report

Created: 2026-04-14 12:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_storage_engine.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
18
#include "cloud/cloud_storage_engine.h"
19
20
#include <bvar/reducer.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
#include <gen_cpp/cloud.pb.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <rapidjson/document.h>
25
#include <rapidjson/encodings.h>
26
#include <rapidjson/prettywriter.h>
27
#include <rapidjson/stringbuffer.h>
28
29
#include <algorithm>
30
#include <memory>
31
#include <variant>
32
33
#include "cloud/cloud_base_compaction.h"
34
#include "cloud/cloud_compaction_stop_token.h"
35
#include "cloud/cloud_cumulative_compaction.h"
36
#include "cloud/cloud_cumulative_compaction_policy.h"
37
#include "cloud/cloud_full_compaction.h"
38
#include "cloud/cloud_index_change_compaction.h"
39
#include "cloud/cloud_meta_mgr.h"
40
#include "cloud/cloud_snapshot_mgr.h"
41
#include "cloud/cloud_tablet_hotspot.h"
42
#include "cloud/cloud_tablet_mgr.h"
43
#include "cloud/cloud_txn_delete_bitmap_cache.h"
44
#include "cloud/cloud_warm_up_manager.h"
45
#include "cloud/config.h"
46
#include "common/config.h"
47
#include "common/metrics/doris_metrics.h"
48
#include "common/signal_handler.h"
49
#include "common/status.h"
50
#include "core/assert_cast.h"
51
#include "io/cache/block_file_cache_downloader.h"
52
#include "io/cache/block_file_cache_factory.h"
53
#include "io/cache/file_cache_common.h"
54
#include "io/fs/file_system.h"
55
#include "io/fs/hdfs_file_system.h"
56
#include "io/fs/s3_file_system.h"
57
#include "io/hdfs_util.h"
58
#include "io/io_common.h"
59
#include "load/memtable/memtable_flush_executor.h"
60
#include "runtime/exec_env.h"
61
#include "runtime/memory/cache_manager.h"
62
#include "storage/compaction/cumulative_compaction_policy.h"
63
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
64
#include "storage/compaction_task_tracker.h"
65
#include "storage/storage_policy.h"
66
#include "util/parse_util.h"
67
#include "util/time.h"
68
69
namespace doris {
70
71
using namespace std::literals;
72
73
bvar::Adder<uint64_t> g_base_compaction_running_task_count("base_compaction_running_task_count");
74
bvar::Adder<uint64_t> g_full_compaction_running_task_count("full_compaction_running_task_count");
75
bvar::Adder<uint64_t> g_cumu_compaction_running_task_count(
76
        "cumulative_compaction_running_task_count");
77
78
19.3k
int get_cumu_thread_num() {
79
19.3k
    if (config::max_cumu_compaction_threads > 0) {
80
0
        return config::max_cumu_compaction_threads;
81
0
    }
82
83
19.3k
    int num_cores = doris::CpuInfo::num_cores();
84
19.3k
    return std::min(std::max(int(num_cores * config::cumu_compaction_thread_num_factor), 2), 20);
85
19.3k
}
86
87
19.3k
int get_base_thread_num() {
88
19.3k
    if (config::max_base_compaction_threads > 0) {
89
19.3k
        return config::max_base_compaction_threads;
90
19.3k
    }
91
92
0
    int num_cores = doris::CpuInfo::num_cores();
93
0
    return std::min(std::max(int(num_cores * config::base_compaction_thread_num_factor), 1), 10);
94
19.3k
}
95
96
CloudStorageEngine::CloudStorageEngine(const EngineOptions& options)
97
158
        : BaseStorageEngine(Type::CLOUD, options.backend_uid),
98
158
          _meta_mgr(std::make_unique<cloud::CloudMetaMgr>()),
99
158
          _tablet_mgr(std::make_unique<CloudTabletMgr>(*this)),
100
158
          _options(options) {
101
158
    _cumulative_compaction_policies[CUMULATIVE_SIZE_BASED_POLICY] =
102
158
            std::make_shared<CloudSizeBasedCumulativeCompactionPolicy>();
103
158
    _cumulative_compaction_policies[CUMULATIVE_TIME_SERIES_POLICY] =
104
158
            std::make_shared<CloudTimeSeriesCumulativeCompactionPolicy>();
105
158
    _startup_timepoint = std::chrono::system_clock::now();
106
158
}
107
108
157
CloudStorageEngine::~CloudStorageEngine() {
109
157
    stop();
110
157
}
111
112
static Status vault_process_error(std::string_view id,
113
0
                                  std::variant<S3Conf, cloud::HdfsVaultInfo>& vault, Status err) {
114
0
    std::stringstream ss;
115
0
    std::visit(
116
0
            [&]<typename T>(T& val) {
117
0
                if constexpr (std::is_same_v<T, S3Conf>) {
118
0
                    ss << val.to_string();
119
0
                } else if constexpr (std::is_same_v<T, cloud::HdfsVaultInfo>) {
120
0
                    val.SerializeToOstream(&ss);
121
0
                }
122
0
            },
Unexecuted instantiation: cloud_storage_engine.cpp:_ZZN5dorisL19vault_process_errorESt17basic_string_viewIcSt11char_traitsIcEERSt7variantIJNS_6S3ConfENS_5cloud13HdfsVaultInfoEEENS_6StatusEENK3$_0clIS5_EEDaRT_
Unexecuted instantiation: cloud_storage_engine.cpp:_ZZN5dorisL19vault_process_errorESt17basic_string_viewIcSt11char_traitsIcEERSt7variantIJNS_6S3ConfENS_5cloud13HdfsVaultInfoEEENS_6StatusEENK3$_0clIS7_EEDaRT_
123
0
            vault);
124
0
    return Status::IOError("Invalid vault, id {}, err {}, detail conf {}", id, err, ss.str());
125
0
}
126
127
struct VaultCreateFSVisitor {
128
    VaultCreateFSVisitor(const std::string& id, const cloud::StorageVaultPB_PathFormat& path_format,
129
                         bool check_fs)
130
1
            : id(id), path_format(path_format), check_fs(check_fs) {}
131
1
    Status operator()(const S3Conf& s3_conf) const {
132
1
        LOG(INFO) << "get new s3 info: " << s3_conf.to_string() << " resource_id=" << id
133
1
                  << " check_fs: " << check_fs;
134
135
1
        auto fs = DORIS_TRY(io::S3FileSystem::create(s3_conf, id));
136
1
        if (check_fs && !s3_conf.client_conf.role_arn.empty()) {
137
0
            bool res = false;
138
            // just check connectivity, not care object if exist
139
0
            auto st = fs->exists("not_exist_object", &res);
140
0
            if (!st.ok()) {
141
0
                LOG(FATAL) << "failed to check s3 fs, resource_id: " << id << " st: " << st
142
0
                           << "s3_conf: " << s3_conf.to_string()
143
0
                           << "add enable_check_storage_vault=false to be.conf to skip the check";
144
0
            }
145
0
        }
146
147
1
        put_storage_resource(id, {std::move(fs), path_format}, 0);
148
1
        LOG_INFO("successfully create s3 vault, vault id {}", id);
149
1
        return Status::OK();
150
1
    }
151
152
    // TODO(ByteYue): Make sure enable_java_support is on
153
0
    Status operator()(const cloud::HdfsVaultInfo& vault) const {
154
0
        auto hdfs_params = io::to_hdfs_params(vault);
155
0
        auto fs = DORIS_TRY(io::HdfsFileSystem::create(hdfs_params, hdfs_params.fs_name, id,
156
0
                                                       nullptr, vault.prefix()));
157
0
        put_storage_resource(id, {std::move(fs), path_format}, 0);
158
0
        LOG_INFO("successfully create hdfs vault, vault id {}", id);
159
0
        return Status::OK();
160
0
    }
161
162
    const std::string& id;
163
    const cloud::StorageVaultPB_PathFormat& path_format;
164
    bool check_fs;
165
};
166
167
struct RefreshFSVaultVisitor {
168
    RefreshFSVaultVisitor(const std::string& id, io::FileSystemSPtr fs,
169
                          const cloud::StorageVaultPB_PathFormat& path_format)
170
115
            : id(id), fs(std::move(fs)), path_format(path_format) {}
171
172
115
    Status operator()(const S3Conf& s3_conf) const {
173
115
        DCHECK_EQ(fs->type(), io::FileSystemType::S3) << id;
174
115
        auto s3_fs = std::static_pointer_cast<io::S3FileSystem>(fs);
175
115
        auto client_holder = s3_fs->client_holder();
176
115
        auto st = client_holder->reset(s3_conf.client_conf);
177
115
        if (!st.ok()) {
178
0
            LOG(WARNING) << "failed to update s3 fs, resource_id=" << id << ": " << st;
179
0
        }
180
115
        return st;
181
115
    }
182
183
0
    Status operator()(const cloud::HdfsVaultInfo& vault) const {
184
0
        auto hdfs_params = io::to_hdfs_params(vault);
185
0
        auto hdfs_fs =
186
0
                DORIS_TRY(io::HdfsFileSystem::create(hdfs_params, hdfs_params.fs_name, id, nullptr,
187
0
                                                     vault.has_prefix() ? vault.prefix() : ""));
188
0
        auto hdfs = std::static_pointer_cast<io::HdfsFileSystem>(hdfs_fs);
189
0
        put_storage_resource(id, {std::move(hdfs), path_format}, 0);
190
0
        return Status::OK();
191
0
    }
192
193
    const std::string& id;
194
    io::FileSystemSPtr fs;
195
    const cloud::StorageVaultPB_PathFormat& path_format;
196
};
197
198
1
Status CloudStorageEngine::open() {
199
1
    sync_storage_vault();
200
201
    // TODO(plat1ko): DeleteBitmapTxnManager
202
203
1
    _memtable_flush_executor = std::make_unique<MemTableFlushExecutor>();
204
    // Use file cache disks number
205
1
    _memtable_flush_executor->init(
206
1
            cast_set<int32_t>(io::FileCacheFactory::instance()->get_cache_instance_size()));
207
208
1
    _calc_delete_bitmap_executor = std::make_unique<CalcDeleteBitmapExecutor>();
209
1
    _calc_delete_bitmap_executor->init(config::calc_delete_bitmap_max_thread);
210
211
1
    _calc_delete_bitmap_executor_for_load = std::make_unique<CalcDeleteBitmapExecutor>();
212
1
    _calc_delete_bitmap_executor_for_load->init(
213
1
            config::calc_delete_bitmap_for_load_max_thread > 0
214
1
                    ? config::calc_delete_bitmap_for_load_max_thread
215
1
                    : std::max(1, CpuInfo::num_cores() / 2));
216
217
    // The default cache is set to 100MB, use memory limit to dynamic adjustment
218
1
    bool is_percent = false;
219
1
    int64_t delete_bitmap_agg_cache_cache_limit =
220
1
            ParseUtil::parse_mem_spec(config::delete_bitmap_dynamic_agg_cache_limit,
221
1
                                      MemInfo::mem_limit(), MemInfo::physical_mem(), &is_percent);
222
1
    _txn_delete_bitmap_cache = std::make_unique<CloudTxnDeleteBitmapCache>(
223
1
            delete_bitmap_agg_cache_cache_limit > config::delete_bitmap_agg_cache_capacity
224
1
                    ? delete_bitmap_agg_cache_cache_limit
225
1
                    : config::delete_bitmap_agg_cache_capacity);
226
1
    RETURN_IF_ERROR(_txn_delete_bitmap_cache->init());
227
228
1
    _committed_rs_mgr = std::make_unique<CloudCommittedRSMgr>();
229
1
    RETURN_IF_ERROR(_committed_rs_mgr->init());
230
231
1
    _file_cache_block_downloader = std::make_unique<io::FileCacheBlockDownloader>(*this);
232
233
1
    _cloud_warm_up_manager = std::make_unique<CloudWarmUpManager>(*this);
234
235
1
    _tablet_hotspot = std::make_unique<TabletHotspot>();
236
237
1
    _cloud_snapshot_mgr = std::make_unique<CloudSnapshotMgr>(*this);
238
239
1
    RETURN_NOT_OK_STATUS_WITH_WARN(
240
1
            init_stream_load_recorder(ExecEnv::GetInstance()->store_paths()[0].path),
241
1
            "init StreamLoadRecorder failed");
242
243
    // check cluster id
244
1
    RETURN_NOT_OK_STATUS_WITH_WARN(_check_all_root_path_cluster_id(), "fail to check cluster id");
245
246
1
    RETURN_NOT_OK_STATUS_WITH_WARN(ThreadPoolBuilder("SyncLoadForTabletsThreadPool")
247
1
                                           .set_max_threads(config::sync_load_for_tablets_thread)
248
1
                                           .set_min_threads(config::sync_load_for_tablets_thread)
249
1
                                           .build(&_sync_load_for_tablets_thread_pool),
250
1
                                   "fail to build SyncLoadForTabletsThreadPool");
251
252
1
    RETURN_NOT_OK_STATUS_WITH_WARN(ThreadPoolBuilder("WarmupCacheAsyncThreadPool")
253
1
                                           .set_max_threads(config::warmup_cache_async_thread)
254
1
                                           .set_min_threads(config::warmup_cache_async_thread)
255
1
                                           .build(&_warmup_cache_async_thread_pool),
256
1
                                   "fail to build WarmupCacheAsyncThreadPool");
257
258
1
    return Status::OK();
259
1
}
260
261
157
void CloudStorageEngine::stop() {
262
157
    if (_stopped) {
263
0
        return;
264
0
    }
265
266
157
    _stopped = true;
267
157
    _stop_background_threads_latch.count_down();
268
269
157
    for (auto&& t : _bg_threads) {
270
0
        if (t) {
271
0
            t->join();
272
0
        }
273
0
    }
274
275
157
    if (_base_compaction_thread_pool) {
276
0
        _base_compaction_thread_pool->shutdown();
277
0
    }
278
157
    if (_cumu_compaction_thread_pool) {
279
0
        _cumu_compaction_thread_pool->shutdown();
280
0
    }
281
157
    _adaptive_thread_controller.stop();
282
157
    LOG(INFO) << "Cloud storage engine is stopped.";
283
284
157
    if (_calc_tablet_delete_bitmap_task_thread_pool) {
285
0
        _calc_tablet_delete_bitmap_task_thread_pool->shutdown();
286
0
    }
287
157
    if (_sync_delete_bitmap_thread_pool) {
288
0
        _sync_delete_bitmap_thread_pool->shutdown();
289
0
    }
290
157
}
291
292
64.3k
bool CloudStorageEngine::stopped() {
293
64.3k
    return _stopped;
294
64.3k
}
295
296
Result<BaseTabletSPtr> CloudStorageEngine::get_tablet(int64_t tablet_id,
297
                                                      SyncRowsetStats* sync_stats,
298
                                                      bool force_use_only_cached,
299
1.27M
                                                      bool cache_on_miss) {
300
1.27M
    return _tablet_mgr
301
1.27M
            ->get_tablet(tablet_id, false, true, sync_stats, force_use_only_cached, cache_on_miss)
302
1.27M
            .transform([](auto&& t) { return static_pointer_cast<BaseTablet>(std::move(t)); });
303
1.27M
}
304
305
Status CloudStorageEngine::get_tablet_meta(int64_t tablet_id, TabletMetaSharedPtr* tablet_meta,
306
183k
                                           bool force_use_only_cached) {
307
183k
    if (tablet_meta == nullptr) {
308
0
        return Status::InvalidArgument("tablet_meta output is null");
309
0
    }
310
311
#if 0
312
    if (_tablet_mgr && _tablet_mgr->peek_tablet_meta(tablet_id, tablet_meta)) {
313
        return Status::OK();
314
    }
315
316
    if (force_use_only_cached) {
317
        return Status::NotFound("tablet meta {} not found in cache", tablet_id);
318
    }
319
#endif
320
321
183k
    if (_meta_mgr == nullptr) {
322
0
        return Status::InternalError("cloud meta manager is not initialized");
323
0
    }
324
325
183k
    return _meta_mgr->get_tablet_meta(tablet_id, tablet_meta);
326
183k
}
327
328
1
Status CloudStorageEngine::start_bg_threads(std::shared_ptr<WorkloadGroup> wg_sptr) {
329
1
    RETURN_IF_ERROR(Thread::create(
330
1
            "CloudStorageEngine", "refresh_s3_info_thread",
331
1
            [this]() { this->_refresh_storage_vault_info_thread_callback(); },
332
1
            &_bg_threads.emplace_back()));
333
1
    LOG(INFO) << "refresh s3 info thread started";
334
335
1
    RETURN_IF_ERROR(Thread::create(
336
1
            "CloudStorageEngine", "vacuum_stale_rowsets_thread",
337
1
            [this]() { this->_vacuum_stale_rowsets_thread_callback(); },
338
1
            &_bg_threads.emplace_back()));
339
1
    LOG(INFO) << "vacuum stale rowsets thread started";
340
341
1
    RETURN_IF_ERROR(Thread::create(
342
1
            "CloudStorageEngine", "sync_tablets_thread",
343
1
            [this]() { this->_sync_tablets_thread_callback(); }, &_bg_threads.emplace_back()));
344
1
    LOG(INFO) << "sync tablets thread started";
345
346
1
    RETURN_IF_ERROR(Thread::create(
347
1
            "CloudStorageEngine", "evict_querying_rowset_thread",
348
1
            [this]() { this->_evict_quring_rowset_thread_callback(); },
349
1
            &_evict_quering_rowset_thread));
350
1
    LOG(INFO) << "evict quering thread started";
351
352
    // add calculate tablet delete bitmap task thread pool
353
1
    RETURN_IF_ERROR(ThreadPoolBuilder("TabletCalDeleteBitmapThreadPool")
354
1
                            .set_min_threads(config::calc_tablet_delete_bitmap_task_max_thread)
355
1
                            .set_max_threads(config::calc_tablet_delete_bitmap_task_max_thread)
356
1
                            .build(&_calc_tablet_delete_bitmap_task_thread_pool));
357
1
    RETURN_IF_ERROR(ThreadPoolBuilder("SyncDeleteBitmapThreadPool")
358
1
                            .set_min_threads(config::sync_delete_bitmap_task_max_thread)
359
1
                            .set_max_threads(config::sync_delete_bitmap_task_max_thread)
360
1
                            .build(&_sync_delete_bitmap_thread_pool));
361
362
    // TODO(plat1ko): check_bucket_enable_versioning_thread
363
364
    // compaction tasks producer thread
365
1
    int base_thread_num = get_base_thread_num();
366
1
    int cumu_thread_num = get_cumu_thread_num();
367
368
1
    RETURN_IF_ERROR(ThreadPoolBuilder("BaseCompactionTaskThreadPool")
369
1
                            .set_min_threads(base_thread_num)
370
1
                            .set_max_threads(base_thread_num)
371
1
                            .build(&_base_compaction_thread_pool));
372
1
    RETURN_IF_ERROR(ThreadPoolBuilder("CumuCompactionTaskThreadPool")
373
1
                            .set_min_threads(cumu_thread_num)
374
1
                            .set_max_threads(cumu_thread_num)
375
1
                            .build(&_cumu_compaction_thread_pool));
376
1
    RETURN_IF_ERROR(Thread::create(
377
1
            "StorageEngine", "compaction_tasks_producer_thread",
378
1
            [this]() { this->_compaction_tasks_producer_callback(); },
379
1
            &_bg_threads.emplace_back()));
380
1
    LOG(INFO) << "compaction tasks producer thread started,"
381
1
              << " base thread num " << base_thread_num << " cumu thread num " << cumu_thread_num;
382
383
1
    RETURN_IF_ERROR(Thread::create(
384
1
            "StorageEngine", "lease_compaction_thread",
385
1
            [this]() { this->_lease_compaction_thread_callback(); }, &_bg_threads.emplace_back()));
386
387
1
    LOG(INFO) << "lease compaction thread started";
388
389
1
    RETURN_IF_ERROR(Thread::create(
390
1
            "StorageEngine", "check_tablet_delete_bitmap_score_thread",
391
1
            [this]() { this->_check_tablet_delete_bitmap_score_callback(); },
392
1
            &_bg_threads.emplace_back()));
393
1
    LOG(INFO) << "check tablet delete bitmap score thread started";
394
395
1
    _start_adaptive_thread_controller();
396
397
1
    return Status::OK();
398
1
}
399
400
116
void CloudStorageEngine::sync_storage_vault() {
401
116
    cloud::StorageVaultInfos vault_infos;
402
116
    bool enable_storage_vault = false;
403
404
116
    auto st = _meta_mgr->get_storage_vault_info(&vault_infos, &enable_storage_vault);
405
116
    if (!st.ok()) {
406
0
        LOG(WARNING) << "failed to get storage vault info. err=" << st;
407
0
        return;
408
0
    }
409
410
116
    if (vault_infos.empty()) {
411
0
        LOG(WARNING) << "empty storage vault info";
412
0
        return;
413
0
    }
414
415
116
    bool check_storage_vault = false;
416
116
    bool expected = false;
417
116
    if (first_sync_storage_vault.compare_exchange_strong(expected, true)) {
418
0
        check_storage_vault = config::enable_check_storage_vault;
419
0
        LOG(INFO) << "first sync storage vault info, BE try to check iam role connectivity, "
420
0
                     "check_storage_vault="
421
0
                  << check_storage_vault;
422
0
    }
423
424
116
    for (auto& [id, vault_info, path_format] : vault_infos) {
425
116
        auto fs = get_filesystem(id);
426
116
        auto status =
427
116
                (fs == nullptr)
428
116
                        ? std::visit(VaultCreateFSVisitor {id, path_format, check_storage_vault},
429
1
                                     vault_info)
430
116
                        : std::visit(RefreshFSVaultVisitor {id, std::move(fs), path_format},
431
115
                                     vault_info);
432
116
        if (!status.ok()) [[unlikely]] {
433
0
            LOG(WARNING) << vault_process_error(id, vault_info, std::move(st));
434
0
        }
435
116
    }
436
437
116
    if (auto& id = std::get<0>(vault_infos.back());
438
116
        (latest_fs() == nullptr || latest_fs()->id() != id) && !enable_storage_vault) {
439
1
        set_latest_fs(get_filesystem(id));
440
1
    }
441
116
}
442
443
// We should enable_java_support if we want to use hdfs vault
444
1
void CloudStorageEngine::_refresh_storage_vault_info_thread_callback() {
445
66
    while (!_stop_background_threads_latch.wait_for(
446
66
            std::chrono::seconds(config::refresh_s3_info_interval_s))) {
447
65
        sync_storage_vault();
448
65
    }
449
1
}
450
451
1
void CloudStorageEngine::_vacuum_stale_rowsets_thread_callback() {
452
13
    while (!_stop_background_threads_latch.wait_for(
453
13
            std::chrono::seconds(config::vacuum_stale_rowsets_interval_s))) {
454
12
        _tablet_mgr->vacuum_stale_rowsets(_stop_background_threads_latch);
455
12
    }
456
1
}
457
458
1
void CloudStorageEngine::_sync_tablets_thread_callback() {
459
7
    while (!_stop_background_threads_latch.wait_for(
460
7
            std::chrono::seconds(config::schedule_sync_tablets_interval_s))) {
461
6
        _tablet_mgr->sync_tablets(_stop_background_threads_latch);
462
6
    }
463
1
}
464
465
void CloudStorageEngine::get_cumu_compaction(
466
111k
        int64_t tablet_id, std::vector<std::shared_ptr<CloudCumulativeCompaction>>& res) {
467
111k
    std::lock_guard lock(_compaction_mtx);
468
111k
    if (auto it = _submitted_cumu_compactions.find(tablet_id);
469
111k
        it != _submitted_cumu_compactions.end()) {
470
0
        res = it->second;
471
0
    }
472
111k
}
473
474
19.3k
Status CloudStorageEngine::_adjust_compaction_thread_num() {
475
19.3k
    int base_thread_num = get_base_thread_num();
476
477
19.3k
    if (!_base_compaction_thread_pool || !_cumu_compaction_thread_pool) {
478
0
        LOG(WARNING) << "base or cumu compaction thread pool is not created";
479
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>("");
480
0
    }
481
482
19.3k
    if (_base_compaction_thread_pool->max_threads() != base_thread_num) {
483
0
        int old_max_threads = _base_compaction_thread_pool->max_threads();
484
0
        Status status = _base_compaction_thread_pool->set_max_threads(base_thread_num);
485
0
        if (status.ok()) {
486
0
            VLOG_NOTICE << "update base compaction thread pool max_threads from " << old_max_threads
487
0
                        << " to " << base_thread_num;
488
0
        }
489
0
    }
490
19.3k
    if (_base_compaction_thread_pool->min_threads() != base_thread_num) {
491
0
        int old_min_threads = _base_compaction_thread_pool->min_threads();
492
0
        Status status = _base_compaction_thread_pool->set_min_threads(base_thread_num);
493
0
        if (status.ok()) {
494
0
            VLOG_NOTICE << "update base compaction thread pool min_threads from " << old_min_threads
495
0
                        << " to " << base_thread_num;
496
0
        }
497
0
    }
498
499
19.3k
    int cumu_thread_num = get_cumu_thread_num();
500
19.3k
    if (_cumu_compaction_thread_pool->max_threads() != cumu_thread_num) {
501
0
        int old_max_threads = _cumu_compaction_thread_pool->max_threads();
502
0
        Status status = _cumu_compaction_thread_pool->set_max_threads(cumu_thread_num);
503
0
        if (status.ok()) {
504
0
            VLOG_NOTICE << "update cumu compaction thread pool max_threads from " << old_max_threads
505
0
                        << " to " << cumu_thread_num;
506
0
        }
507
0
    }
508
19.3k
    if (_cumu_compaction_thread_pool->min_threads() != cumu_thread_num) {
509
0
        int old_min_threads = _cumu_compaction_thread_pool->min_threads();
510
0
        Status status = _cumu_compaction_thread_pool->set_min_threads(cumu_thread_num);
511
0
        if (status.ok()) {
512
0
            VLOG_NOTICE << "update cumu compaction thread pool min_threads from " << old_min_threads
513
0
                        << " to " << cumu_thread_num;
514
0
        }
515
0
    }
516
19.3k
    return Status::OK();
517
19.3k
}
518
519
1
void CloudStorageEngine::_compaction_tasks_producer_callback() {
520
1
    LOG(INFO) << "try to start compaction producer process!";
521
522
1
    int round = 0;
523
1
    CompactionType compaction_type;
524
525
    // Used to record the time when the score metric was last updated.
526
    // The update of the score metric is accompanied by the logic of selecting the tablet.
527
    // If there is no slot available, the logic of selecting the tablet will be terminated,
528
    // which causes the score metric update to be terminated.
529
    // In order to avoid this situation, we need to update the score regularly.
530
1
    int64_t last_cumulative_score_update_time = 0;
531
1
    int64_t last_base_score_update_time = 0;
532
1
    static const int64_t check_score_interval_ms = 5000; // 5 secs
533
534
1
    int64_t interval = config::generate_compaction_tasks_interval_ms;
535
19.3k
    do {
536
19.3k
        int64_t cur_time = UnixMillis();
537
19.3k
        if (!config::disable_auto_compaction) {
538
19.3k
            Status st = _adjust_compaction_thread_num();
539
19.3k
            if (!st.ok()) {
540
0
                break;
541
0
            }
542
543
19.3k
            bool check_score = false;
544
19.3k
            if (round < config::cumulative_compaction_rounds_for_each_base_compaction_round) {
545
17.4k
                compaction_type = CompactionType::CUMULATIVE_COMPACTION;
546
17.4k
                round++;
547
17.4k
                if (cur_time - last_cumulative_score_update_time >= check_score_interval_ms) {
548
751
                    check_score = true;
549
751
                    last_cumulative_score_update_time = cur_time;
550
751
                }
551
17.4k
            } else {
552
1.93k
                compaction_type = CompactionType::BASE_COMPACTION;
553
1.93k
                round = 0;
554
1.93k
                if (cur_time - last_base_score_update_time >= check_score_interval_ms) {
555
639
                    check_score = true;
556
639
                    last_base_score_update_time = cur_time;
557
639
                }
558
1.93k
            }
559
19.3k
            std::unique_ptr<ThreadPool>& thread_pool =
560
19.3k
                    (compaction_type == CompactionType::CUMULATIVE_COMPACTION)
561
19.3k
                            ? _cumu_compaction_thread_pool
562
19.3k
                            : _base_compaction_thread_pool;
563
19.3k
            VLOG_CRITICAL << "compaction thread pool. type: "
564
0
                          << (compaction_type == CompactionType::CUMULATIVE_COMPACTION ? "CUMU"
565
0
                                                                                       : "BASE")
566
0
                          << ", num_threads: " << thread_pool->num_threads()
567
0
                          << ", num_threads_pending_start: "
568
0
                          << thread_pool->num_threads_pending_start()
569
0
                          << ", num_active_threads: " << thread_pool->num_active_threads()
570
0
                          << ", max_threads: " << thread_pool->max_threads()
571
0
                          << ", min_threads: " << thread_pool->min_threads()
572
0
                          << ", num_total_queued_tasks: " << thread_pool->get_queue_size();
573
19.3k
            std::vector<CloudTabletSPtr> tablets_compaction =
574
19.3k
                    _generate_cloud_compaction_tasks(compaction_type, check_score);
575
576
            /// Regardless of whether the tablet is submitted for compaction or not,
577
            /// we need to call 'reset_compaction' to clean up the base_compaction or cumulative_compaction objects
578
            /// in the tablet, because these two objects store the tablet's own shared_ptr.
579
            /// If it is not cleaned up, the reference count of the tablet will always be greater than 1,
580
            /// thus cannot be collected by the garbage collector. (TabletManager::start_trash_sweep)
581
114k
            for (const auto& tablet : tablets_compaction) {
582
114k
                Status status = submit_compaction_task(tablet, compaction_type);
583
114k
                if (status.ok()) continue;
584
108k
                if ((!status.is<ErrorCode::BE_NO_SUITABLE_VERSION>() &&
585
108k
                     !status.is<ErrorCode::CUMULATIVE_NO_SUITABLE_VERSION>()) ||
586
108k
                    VLOG_DEBUG_IS_ON) {
587
44
                    LOG(WARNING) << "failed to submit compaction task for tablet: "
588
44
                                 << tablet->tablet_id() << ", err: " << status;
589
44
                }
590
108k
            }
591
19.3k
            interval = config::generate_compaction_tasks_interval_ms;
592
19.3k
        } else {
593
0
            interval = config::check_auto_compaction_interval_seconds * 1000;
594
0
        }
595
19.3k
        int64_t end_time = UnixMillis();
596
19.3k
        DorisMetrics::instance()->compaction_producer_callback_a_round_time->set_value(end_time -
597
19.3k
                                                                                       cur_time);
598
19.3k
    } while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(interval)));
599
1
}
600
601
void CloudStorageEngine::unregister_index_change_compaction(int64_t tablet_id,
602
848
                                                            bool is_base_compact) {
603
848
    std::lock_guard lock(_compaction_mtx);
604
848
    if (is_base_compact) {
605
0
        _submitted_index_change_base_compaction.erase(tablet_id);
606
848
    } else {
607
848
        _submitted_index_change_cumu_compaction.erase(tablet_id);
608
848
    }
609
848
}
610
611
bool CloudStorageEngine::register_index_change_compaction(
612
        std::shared_ptr<CloudIndexChangeCompaction> compact, int64_t tablet_id,
613
850
        bool is_base_compact, std::string& err_reason) {
614
850
    std::lock_guard lock(_compaction_mtx);
615
850
    if (is_base_compact) {
616
2
        if (_submitted_base_compactions.contains(tablet_id) ||
617
2
            _submitted_full_compactions.contains(tablet_id) ||
618
2
            _submitted_index_change_base_compaction.contains(tablet_id)) {
619
1
            std::stringstream ss;
620
1
            ss << "reason:" << ((int)_submitted_base_compactions.contains(tablet_id)) << ", "
621
1
               << ((int)_submitted_full_compactions.contains(tablet_id)) << ", "
622
1
               << ((int)_submitted_index_change_base_compaction.contains(tablet_id));
623
1
            err_reason = ss.str();
624
1
            return false;
625
1
        } else {
626
1
            _submitted_index_change_base_compaction[tablet_id] = compact;
627
1
            return true;
628
1
        }
629
848
    } else {
630
848
        if (_tablet_preparing_cumu_compaction.contains(tablet_id) ||
631
850
            _submitted_cumu_compactions.contains(tablet_id) ||
632
848
            _submitted_index_change_cumu_compaction.contains(tablet_id)) {
633
2
            std::stringstream ss;
634
2
            ss << "reason:" << ((int)_tablet_preparing_cumu_compaction.contains(tablet_id)) << ", "
635
2
               << ((int)_submitted_cumu_compactions.contains(tablet_id)) << ", "
636
2
               << ((int)_submitted_index_change_cumu_compaction.contains(tablet_id));
637
2
            err_reason = ss.str();
638
2
            return false;
639
846
        } else {
640
846
            _submitted_index_change_cumu_compaction[tablet_id] = compact;
641
846
        }
642
846
        return true;
643
848
    }
644
850
}
645
646
std::vector<CloudTabletSPtr> CloudStorageEngine::_generate_cloud_compaction_tasks(
647
19.3k
        CompactionType compaction_type, bool check_score) {
648
19.3k
    std::vector<std::shared_ptr<CloudTablet>> tablets_compaction;
649
650
19.3k
    int64_t max_compaction_score = 0;
651
19.3k
    std::unordered_set<int64_t> tablet_preparing_cumu_compaction;
652
19.3k
    std::unordered_map<int64_t, std::vector<std::shared_ptr<CloudCumulativeCompaction>>>
653
19.3k
            submitted_cumu_compactions;
654
19.3k
    std::unordered_map<int64_t, std::shared_ptr<CloudBaseCompaction>> submitted_base_compactions;
655
19.3k
    std::unordered_map<int64_t, std::shared_ptr<CloudFullCompaction>> submitted_full_compactions;
656
19.3k
    std::unordered_map<int64_t, std::shared_ptr<CloudIndexChangeCompaction>>
657
19.3k
            submitted_index_change_cumu_compactions;
658
19.3k
    std::unordered_map<int64_t, std::shared_ptr<CloudIndexChangeCompaction>>
659
19.3k
            submitted_index_change_base_compactions;
660
19.3k
    {
661
19.3k
        std::lock_guard lock(_compaction_mtx);
662
19.3k
        tablet_preparing_cumu_compaction = _tablet_preparing_cumu_compaction;
663
19.3k
        submitted_cumu_compactions = _submitted_cumu_compactions;
664
19.3k
        submitted_base_compactions = _submitted_base_compactions;
665
19.3k
        submitted_full_compactions = _submitted_full_compactions;
666
19.3k
        submitted_index_change_cumu_compactions = _submitted_index_change_cumu_compaction;
667
19.3k
        submitted_index_change_base_compactions = _submitted_index_change_base_compaction;
668
19.3k
    }
669
670
19.3k
    bool need_pick_tablet = true;
671
19.3k
    int thread_per_disk =
672
19.3k
            config::compaction_task_num_per_fast_disk; // all disks are fast in cloud mode
673
19.3k
    int num_cumu =
674
19.3k
            std::accumulate(submitted_cumu_compactions.begin(), submitted_cumu_compactions.end(), 0,
675
19.3k
                            [](int a, auto& b) { return a + b.second.size(); });
676
19.3k
    int num_base =
677
19.3k
            cast_set<int>(submitted_base_compactions.size() + submitted_full_compactions.size());
678
19.3k
    int n = thread_per_disk - num_cumu - num_base;
679
19.3k
    if (compaction_type == CompactionType::BASE_COMPACTION) {
680
        // We need to reserve at least one thread for cumulative compaction,
681
        // because base compactions may take too long to complete, which may
682
        // leads to "too many rowsets" error.
683
1.93k
        int base_n = std::min(config::max_base_compaction_task_num_per_disk, thread_per_disk - 1) -
684
1.93k
                     num_base;
685
1.93k
        n = std::min(base_n, n);
686
1.93k
    }
687
19.3k
    if (n <= 0) { // No threads available
688
390
        if (!check_score) return tablets_compaction;
689
21
        need_pick_tablet = false;
690
21
        n = 0;
691
21
    }
692
693
    // Return true for skipping compaction
694
19.0k
    std::function<bool(CloudTablet*)> filter_out;
695
19.0k
    if (compaction_type == CompactionType::BASE_COMPACTION) {
696
1.90k
        filter_out = [&submitted_base_compactions, &submitted_full_compactions,
697
68.6M
                      &submitted_index_change_base_compactions](CloudTablet* t) {
698
68.6M
            return submitted_base_compactions.contains(t->tablet_id()) ||
699
68.6M
                   submitted_full_compactions.contains(t->tablet_id()) ||
700
68.6M
                   submitted_index_change_base_compactions.contains(t->tablet_id()) ||
701
68.6M
                   t->tablet_state() != TABLET_RUNNING;
702
68.6M
        };
703
17.1k
    } else if (config::enable_parallel_cumu_compaction) {
704
0
        filter_out = [&tablet_preparing_cumu_compaction,
705
0
                      &submitted_index_change_cumu_compactions](CloudTablet* t) {
706
0
            return tablet_preparing_cumu_compaction.contains(t->tablet_id()) ||
707
0
                   submitted_index_change_cumu_compactions.contains(t->tablet_id()) ||
708
0
                   (t->tablet_state() != TABLET_RUNNING &&
709
0
                    (!config::enable_new_tablet_do_compaction || t->alter_version() == -1));
710
0
        };
711
17.1k
    } else {
712
17.1k
        filter_out = [&tablet_preparing_cumu_compaction, &submitted_cumu_compactions,
713
251M
                      &submitted_index_change_cumu_compactions](CloudTablet* t) {
714
251M
            return tablet_preparing_cumu_compaction.contains(t->tablet_id()) ||
715
251M
                   submitted_index_change_cumu_compactions.contains(t->tablet_id()) ||
716
251M
                   submitted_cumu_compactions.contains(t->tablet_id()) ||
717
251M
                   (t->tablet_state() != TABLET_RUNNING &&
718
251M
                    (!config::enable_new_tablet_do_compaction || t->alter_version() == -1));
719
251M
        };
720
17.1k
    }
721
722
    // Even if need_pick_tablet is false, we still need to call find_best_tablet_to_compaction(),
723
    // So that we can update the max_compaction_score metric.
724
19.0k
    do {
725
19.0k
        std::vector<CloudTabletSPtr> tablets;
726
19.0k
        auto st = tablet_mgr().get_topn_tablets_to_compact(n, compaction_type, filter_out, &tablets,
727
19.0k
                                                           &max_compaction_score);
728
19.0k
        if (!st.ok()) {
729
0
            LOG(WARNING) << "failed to get tablets to compact, err=" << st;
730
0
            break;
731
0
        }
732
19.0k
        if (!need_pick_tablet) break;
733
18.9k
        tablets_compaction = std::move(tablets);
734
18.9k
    } while (false);
735
736
19.0k
    if (max_compaction_score > 0) {
737
17.4k
        if (compaction_type == CompactionType::BASE_COMPACTION) {
738
1.85k
            DorisMetrics::instance()->tablet_base_max_compaction_score->set_value(
739
1.85k
                    max_compaction_score);
740
15.6k
        } else {
741
15.6k
            DorisMetrics::instance()->tablet_cumulative_max_compaction_score->set_value(
742
15.6k
                    max_compaction_score);
743
15.6k
        }
744
17.4k
    }
745
746
19.0k
    return tablets_compaction;
747
19.3k
}
748
749
Status CloudStorageEngine::_request_tablet_global_compaction_lock(
750
        ReaderType compaction_type, const CloudTabletSPtr& tablet,
751
6.95k
        std::shared_ptr<CloudCompactionMixin> compaction) {
752
6.95k
    long now = duration_cast<std::chrono::milliseconds>(
753
6.95k
                       std::chrono::system_clock::now().time_since_epoch())
754
6.95k
                       .count();
755
6.95k
    if (compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION) {
756
6.77k
        auto cumu_compaction = static_pointer_cast<CloudCumulativeCompaction>(compaction);
757
6.77k
        if (auto st = cumu_compaction->request_global_lock(); !st.ok()) {
758
442
            LOG_WARNING("failed to request cumu compactoin global lock")
759
442
                    .tag("tablet id", tablet->tablet_id())
760
442
                    .tag("msg", st.to_string());
761
442
            tablet->set_last_cumu_compaction_failure_time(now);
762
442
            return st;
763
442
        }
764
6.33k
        {
765
6.33k
            std::lock_guard lock(_compaction_mtx);
766
6.33k
            _executing_cumu_compactions[tablet->tablet_id()].push_back(cumu_compaction);
767
6.33k
        }
768
6.33k
        return Status::OK();
769
6.77k
    } else if (compaction_type == ReaderType::READER_BASE_COMPACTION) {
770
73
        auto base_compaction = static_pointer_cast<CloudBaseCompaction>(compaction);
771
73
        if (auto st = base_compaction->request_global_lock(); !st.ok()) {
772
3
            LOG_WARNING("failed to request base compactoin global lock")
773
3
                    .tag("tablet id", tablet->tablet_id())
774
3
                    .tag("msg", st.to_string());
775
3
            tablet->set_last_base_compaction_failure_time(now);
776
3
            return st;
777
3
        }
778
70
        {
779
70
            std::lock_guard lock(_compaction_mtx);
780
70
            _executing_base_compactions[tablet->tablet_id()] = base_compaction;
781
70
        }
782
70
        return Status::OK();
783
105
    } else if (compaction_type == ReaderType::READER_FULL_COMPACTION) {
784
105
        auto full_compaction = static_pointer_cast<CloudFullCompaction>(compaction);
785
105
        if (auto st = full_compaction->request_global_lock(); !st.ok()) {
786
0
            LOG_WARNING("failed to request full compactoin global lock")
787
0
                    .tag("tablet id", tablet->tablet_id())
788
0
                    .tag("msg", st.to_string());
789
0
            tablet->set_last_full_compaction_failure_time(now);
790
0
            return st;
791
0
        }
792
105
        {
793
105
            std::lock_guard lock(_compaction_mtx);
794
105
            _executing_full_compactions[tablet->tablet_id()] = full_compaction;
795
105
        }
796
105
        return Status::OK();
797
105
    } else {
798
0
        LOG(WARNING) << "unsupport compaction task for tablet: " << tablet->tablet_id()
799
0
                     << ", compaction name: " << compaction->compaction_name();
800
0
        return Status::NotFound("Unsupport compaction type {}", compaction->compaction_name());
801
0
    }
802
6.95k
}
803
804
Status CloudStorageEngine::_submit_base_compaction_task(const CloudTabletSPtr& tablet,
805
3.47k
                                                        int trigger_method) {
806
3.47k
    using namespace std::chrono;
807
3.47k
    {
808
3.47k
        std::lock_guard lock(_compaction_mtx);
809
        // Take a placeholder for base compaction
810
3.47k
        auto [_, success] = _submitted_base_compactions.emplace(tablet->tablet_id(), nullptr);
811
3.47k
        if (!success) {
812
0
            return Status::AlreadyExist(
813
0
                    "other base compaction or full compaction is submitted, tablet_id={}",
814
0
                    tablet->tablet_id());
815
0
        }
816
3.47k
    }
817
3.47k
    auto compaction = std::make_shared<CloudBaseCompaction>(*this, tablet);
818
3.47k
    auto st = compaction->prepare_compact();
819
3.47k
    if (!st.ok()) {
820
3.39k
        long now = duration_cast<std::chrono::milliseconds>(
821
3.39k
                           std::chrono::system_clock::now().time_since_epoch())
822
3.39k
                           .count();
823
3.39k
        tablet->set_last_base_compaction_failure_time(now);
824
3.39k
        std::lock_guard lock(_compaction_mtx);
825
3.39k
        _submitted_base_compactions.erase(tablet->tablet_id());
826
3.39k
        return st;
827
3.39k
    }
828
    // Register task with CompactionTaskTracker as PENDING
829
73
    auto* tracker = CompactionTaskTracker::instance();
830
73
    int64_t compaction_id = compaction->compaction_id();
831
73
    {
832
73
        CompactionTaskInfo info;
833
73
        info.compaction_id = compaction_id;
834
73
        info.tablet_id = tablet->tablet_id();
835
73
        info.table_id = tablet->table_id();
836
73
        info.partition_id = tablet->partition_id();
837
73
        info.compaction_type = CompactionProfileType::BASE;
838
73
        info.status = CompactionTaskStatus::PENDING;
839
73
        info.trigger_method = static_cast<TriggerMethod>(trigger_method);
840
73
        info.scheduled_time_ms =
841
73
                duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
842
73
        info.backend_id = BackendOptions::get_backend_id();
843
73
        info.compaction_score = tablet->get_real_compaction_score();
844
73
        info.input_rowsets_count = compaction->input_rowsets_count();
845
73
        info.input_row_num = compaction->input_row_num_value();
846
73
        info.input_data_size = compaction->input_rowsets_data_size();
847
73
        info.input_index_size = compaction->input_rowsets_index_size();
848
73
        info.input_total_size = compaction->input_rowsets_total_size();
849
73
        info.input_segments_num = compaction->input_segments_num_value();
850
73
        info.input_version_range = compaction->input_version_range_str();
851
73
        info.is_vertical = compaction->is_vertical();
852
73
        tracker->register_task(std::move(info));
853
73
    }
854
73
    {
855
73
        std::lock_guard lock(_compaction_mtx);
856
73
        _submitted_base_compactions[tablet->tablet_id()] = compaction;
857
73
    }
858
73
    st = _base_compaction_thread_pool->submit_func([=, this, compaction = std::move(compaction)]() {
859
73
        DorisMetrics::instance()->base_compaction_task_running_total->increment(1);
860
73
        DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
861
73
                _base_compaction_thread_pool->get_queue_size());
862
73
        g_base_compaction_running_task_count << 1;
863
73
        signal::tablet_id = tablet->tablet_id();
864
73
        Defer defer {[&]() {
865
            // Idempotent cleanup: remove task from tracker
866
73
            CompactionTaskTracker::instance()->remove_task(compaction_id);
867
73
            g_base_compaction_running_task_count << -1;
868
73
            std::lock_guard lock(_compaction_mtx);
869
73
            _submitted_base_compactions.erase(tablet->tablet_id());
870
73
            DorisMetrics::instance()->base_compaction_task_running_total->increment(-1);
871
73
            DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
872
73
                    _base_compaction_thread_pool->get_queue_size());
873
73
        }};
874
73
        auto st = _request_tablet_global_compaction_lock(ReaderType::READER_BASE_COMPACTION, tablet,
875
73
                                                         compaction);
876
73
        if (!st.ok()) return;
877
        // Update tracker to RUNNING after acquiring global lock
878
70
        {
879
70
            RunningStats rs;
880
70
            rs.start_time_ms =
881
70
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
882
70
            CompactionTaskTracker::instance()->update_to_running(compaction_id, rs);
883
70
        }
884
70
        st = compaction->execute_compact();
885
70
        if (!st.ok()) {
886
            // Error log has been output in `execute_compact`
887
0
            long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
888
0
            tablet->set_last_base_compaction_failure_time(now);
889
0
        }
890
70
        std::lock_guard lock(_compaction_mtx);
891
70
        _executing_base_compactions.erase(tablet->tablet_id());
892
70
    });
893
73
    DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
894
73
            _base_compaction_thread_pool->get_queue_size());
895
73
    if (!st.ok()) {
896
0
        tracker->remove_task(compaction_id);
897
0
        std::lock_guard lock(_compaction_mtx);
898
0
        _submitted_base_compactions.erase(tablet->tablet_id());
899
0
        return Status::InternalError("failed to submit base compaction, tablet_id={}",
900
0
                                     tablet->tablet_id());
901
0
    }
902
73
    return st;
903
73
}
904
905
Status CloudStorageEngine::_submit_cumulative_compaction_task(const CloudTabletSPtr& tablet,
906
111k
                                                              int trigger_method) {
907
111k
    using namespace std::chrono;
908
111k
    {
909
111k
        std::lock_guard lock(_compaction_mtx);
910
111k
        if (!config::enable_parallel_cumu_compaction &&
911
111k
            _submitted_cumu_compactions.count(tablet->tablet_id())) {
912
4
            return Status::AlreadyExist("other cumu compaction is submitted, tablet_id={}",
913
4
                                        tablet->tablet_id());
914
4
        }
915
111k
        auto [_, success] = _tablet_preparing_cumu_compaction.insert(tablet->tablet_id());
916
111k
        if (!success) {
917
0
            return Status::AlreadyExist("other cumu compaction is preparing, tablet_id={}",
918
0
                                        tablet->tablet_id());
919
0
        }
920
111k
    }
921
111k
    auto compaction = std::make_shared<CloudCumulativeCompaction>(*this, tablet);
922
111k
    auto st = compaction->prepare_compact();
923
111k
    if (!st.ok()) {
924
105k
        long now = duration_cast<std::chrono::milliseconds>(
925
105k
                           std::chrono::system_clock::now().time_since_epoch())
926
105k
                           .count();
927
105k
        if (!st.is<ErrorCode::CUMULATIVE_MEET_DELETE_VERSION>()) {
928
105k
            if (st.is<ErrorCode::CUMULATIVE_NO_SUITABLE_VERSION>()) {
929
                // Backoff strategy if no suitable version
930
105k
                tablet->last_cumu_no_suitable_version_ms = now;
931
105k
            } else {
932
0
                tablet->set_last_cumu_compaction_failure_time(now);
933
0
            }
934
105k
        }
935
105k
        std::lock_guard lock(_compaction_mtx);
936
105k
        _tablet_preparing_cumu_compaction.erase(tablet->tablet_id());
937
105k
        return st;
938
105k
    }
939
    // Register task with CompactionTaskTracker as PENDING
940
    // IMPORTANT: use compaction->compaction_id(), NOT tracker->next_compaction_id(),
941
    // because the Compaction constructor already allocated an ID via the tracker.
942
6.77k
    auto* tracker = CompactionTaskTracker::instance();
943
6.77k
    int64_t compaction_id = compaction->compaction_id();
944
6.77k
    {
945
6.77k
        CompactionTaskInfo info;
946
6.77k
        info.compaction_id = compaction_id;
947
6.77k
        info.tablet_id = tablet->tablet_id();
948
6.77k
        info.table_id = tablet->table_id();
949
6.77k
        info.partition_id = tablet->partition_id();
950
6.77k
        info.compaction_type = CompactionProfileType::CUMULATIVE;
951
6.77k
        info.status = CompactionTaskStatus::PENDING;
952
6.77k
        info.trigger_method = static_cast<TriggerMethod>(trigger_method);
953
6.77k
        info.scheduled_time_ms =
954
6.77k
                duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
955
6.77k
        info.backend_id = BackendOptions::get_backend_id();
956
6.77k
        info.compaction_score = tablet->get_real_compaction_score();
957
6.77k
        info.input_rowsets_count = compaction->input_rowsets_count();
958
6.77k
        info.input_row_num = compaction->input_row_num_value();
959
6.77k
        info.input_data_size = compaction->input_rowsets_data_size();
960
6.77k
        info.input_index_size = compaction->input_rowsets_index_size();
961
6.77k
        info.input_total_size = compaction->input_rowsets_total_size();
962
6.77k
        info.input_segments_num = compaction->input_segments_num_value();
963
6.77k
        info.input_version_range = compaction->input_version_range_str();
964
6.77k
        info.is_vertical = compaction->is_vertical();
965
6.77k
        tracker->register_task(std::move(info));
966
6.77k
    }
967
6.77k
    {
968
6.77k
        std::lock_guard lock(_compaction_mtx);
969
6.77k
        _tablet_preparing_cumu_compaction.erase(tablet->tablet_id());
970
6.77k
        _submitted_cumu_compactions[tablet->tablet_id()].push_back(compaction);
971
6.77k
    }
972
6.77k
    auto erase_submitted_cumu_compaction = [=, this]() {
973
6.77k
        std::lock_guard lock(_compaction_mtx);
974
6.77k
        auto it = _submitted_cumu_compactions.find(tablet->tablet_id());
975
6.77k
        DCHECK(it != _submitted_cumu_compactions.end());
976
6.77k
        auto& compactions = it->second;
977
6.77k
        auto it1 = std::find(compactions.begin(), compactions.end(), compaction);
978
6.77k
        DCHECK(it1 != compactions.end());
979
6.77k
        compactions.erase(it1);
980
6.77k
        if (compactions.empty()) { // No compactions on this tablet, erase key
981
6.77k
            _submitted_cumu_compactions.erase(it);
982
            // No cumu compaction on this tablet, reset `last_cumu_no_suitable_version_ms` to enable this tablet to
983
            // enter the compaction scheduling candidate set. The purpose of doing this is to have at least one BE perform
984
            // cumu compaction on tablet which has suitable versions for cumu compaction.
985
6.77k
            tablet->last_cumu_no_suitable_version_ms = 0;
986
6.77k
        }
987
6.77k
    };
988
6.77k
    auto erase_executing_cumu_compaction = [=, this]() {
989
6.32k
        std::lock_guard lock(_compaction_mtx);
990
6.32k
        auto it = _executing_cumu_compactions.find(tablet->tablet_id());
991
6.32k
        DCHECK(it != _executing_cumu_compactions.end());
992
6.32k
        auto& compactions = it->second;
993
6.32k
        auto it1 = std::find(compactions.begin(), compactions.end(), compaction);
994
6.32k
        DCHECK(it1 != compactions.end());
995
6.32k
        compactions.erase(it1);
996
6.33k
        if (compactions.empty()) { // No compactions on this tablet, erase key
997
6.33k
            _executing_cumu_compactions.erase(it);
998
            // No cumu compaction on this tablet, reset `last_cumu_no_suitable_version_ms` to enable this tablet to
999
            // enter the compaction scheduling candidate set. The purpose of doing this is to have at least one BE perform
1000
            // cumu compaction on tablet which has suitable versions for cumu compaction.
1001
6.33k
            tablet->last_cumu_no_suitable_version_ms = 0;
1002
6.33k
        }
1003
6.32k
    };
1004
6.77k
    st = _cumu_compaction_thread_pool->submit_func([=, this, compaction = std::move(compaction)]() {
1005
6.77k
        DorisMetrics::instance()->cumulative_compaction_task_running_total->increment(1);
1006
6.77k
        DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
1007
6.77k
                _cumu_compaction_thread_pool->get_queue_size());
1008
6.77k
        DBUG_EXECUTE_IF("CloudStorageEngine._submit_cumulative_compaction_task.wait_in_line",
1009
6.77k
                        { sleep(5); })
1010
6.77k
        signal::tablet_id = tablet->tablet_id();
1011
6.77k
        g_cumu_compaction_running_task_count << 1;
1012
6.77k
        bool is_large_task = true;
1013
6.77k
        Defer defer {[&]() {
1014
6.77k
            DBUG_EXECUTE_IF("CloudStorageEngine._submit_cumulative_compaction_task.sleep",
1015
6.77k
                            { sleep(5); })
1016
            // Idempotent cleanup: remove task from tracker
1017
6.77k
            CompactionTaskTracker::instance()->remove_task(compaction_id);
1018
6.77k
            std::lock_guard lock(_cumu_compaction_delay_mtx);
1019
6.77k
            _cumu_compaction_thread_pool_used_threads--;
1020
6.77k
            if (!is_large_task) {
1021
6.33k
                _cumu_compaction_thread_pool_small_tasks_running--;
1022
6.33k
            }
1023
6.77k
            g_cumu_compaction_running_task_count << -1;
1024
6.77k
            erase_submitted_cumu_compaction();
1025
6.77k
            DorisMetrics::instance()->cumulative_compaction_task_running_total->increment(-1);
1026
6.77k
            DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
1027
6.77k
                    _cumu_compaction_thread_pool->get_queue_size());
1028
6.77k
        }};
1029
6.77k
        auto st = _request_tablet_global_compaction_lock(ReaderType::READER_CUMULATIVE_COMPACTION,
1030
6.77k
                                                         tablet, compaction);
1031
6.77k
        if (!st.ok()) return;
1032
        // Update tracker to RUNNING after acquiring global lock
1033
6.33k
        {
1034
6.33k
            RunningStats rs;
1035
6.33k
            rs.start_time_ms =
1036
6.33k
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1037
6.33k
            CompactionTaskTracker::instance()->update_to_running(compaction_id, rs);
1038
6.33k
        }
1039
6.33k
        do {
1040
6.33k
            std::lock_guard lock(_cumu_compaction_delay_mtx);
1041
6.33k
            _cumu_compaction_thread_pool_used_threads++;
1042
6.33k
            if (config::large_cumu_compaction_task_min_thread_num > 1 &&
1043
6.33k
                _cumu_compaction_thread_pool->max_threads() >=
1044
6.33k
                        config::large_cumu_compaction_task_min_thread_num) {
1045
                // Determine if this is a small task based on configured thresholds
1046
6.33k
                is_large_task = (compaction->get_input_rowsets_bytes() >
1047
6.33k
                                         config::large_cumu_compaction_task_bytes_threshold ||
1048
6.33k
                                 compaction->get_input_num_rows() >
1049
6.33k
                                         config::large_cumu_compaction_task_row_num_threshold);
1050
                // Small task. No delay needed
1051
6.33k
                if (!is_large_task) {
1052
6.33k
                    _cumu_compaction_thread_pool_small_tasks_running++;
1053
6.33k
                    break;
1054
6.33k
                }
1055
                // Deal with large task
1056
1
                if (_should_delay_large_task()) {
1057
0
                    long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch())
1058
0
                                       .count();
1059
                    // sleep 5s for this tablet
1060
0
                    tablet->set_last_cumu_compaction_failure_time(now);
1061
0
                    erase_executing_cumu_compaction();
1062
0
                    LOG_WARNING(
1063
0
                            "failed to do CloudCumulativeCompaction, cumu thread pool is "
1064
0
                            "intensive, delay large task.")
1065
0
                            .tag("tablet_id", tablet->tablet_id())
1066
0
                            .tag("input_rows", compaction->get_input_num_rows())
1067
0
                            .tag("input_rowsets_total_size", compaction->get_input_rowsets_bytes())
1068
0
                            .tag("config::large_cumu_compaction_task_bytes_threshold",
1069
0
                                 config::large_cumu_compaction_task_bytes_threshold)
1070
0
                            .tag("config::large_cumu_compaction_task_row_num_threshold",
1071
0
                                 config::large_cumu_compaction_task_row_num_threshold)
1072
0
                            .tag("remaining threads", _cumu_compaction_thread_pool_used_threads)
1073
0
                            .tag("small_tasks_running",
1074
0
                                 _cumu_compaction_thread_pool_small_tasks_running);
1075
0
                    return;
1076
0
                }
1077
1
            }
1078
6.33k
        } while (false);
1079
6.33k
        st = compaction->execute_compact();
1080
6.33k
        if (!st.ok()) {
1081
            // Error log has been output in `execute_compact`
1082
62
            long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1083
62
            tablet->set_last_cumu_compaction_failure_time(now);
1084
62
        }
1085
6.33k
        erase_executing_cumu_compaction();
1086
6.33k
    });
1087
6.77k
    DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
1088
6.77k
            _cumu_compaction_thread_pool->get_queue_size());
1089
6.77k
    if (!st.ok()) {
1090
0
        tracker->remove_task(compaction_id);
1091
0
        erase_submitted_cumu_compaction();
1092
0
        return Status::InternalError("failed to submit cumu compaction, tablet_id={}",
1093
0
                                     tablet->tablet_id());
1094
0
    }
1095
6.77k
    return st;
1096
6.77k
}
1097
1098
Status CloudStorageEngine::_submit_full_compaction_task(const CloudTabletSPtr& tablet,
1099
105
                                                        int trigger_method) {
1100
105
    using namespace std::chrono;
1101
105
    {
1102
105
        std::lock_guard lock(_compaction_mtx);
1103
        // Take a placeholder for full compaction
1104
105
        auto [_, success] = _submitted_full_compactions.emplace(tablet->tablet_id(), nullptr);
1105
105
        if (!success) {
1106
0
            return Status::AlreadyExist(
1107
0
                    "other full compaction or base compaction is submitted, tablet_id={}",
1108
0
                    tablet->tablet_id());
1109
0
        }
1110
105
    }
1111
    //auto compaction = std::make_shared<CloudFullCompaction>(tablet);
1112
105
    auto compaction = std::make_shared<CloudFullCompaction>(*this, tablet);
1113
105
    auto st = compaction->prepare_compact();
1114
105
    if (!st.ok()) {
1115
0
        long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1116
0
        tablet->set_last_full_compaction_failure_time(now);
1117
0
        std::lock_guard lock(_compaction_mtx);
1118
0
        _submitted_full_compactions.erase(tablet->tablet_id());
1119
0
        return st;
1120
0
    }
1121
    // Register task with CompactionTaskTracker as PENDING
1122
105
    auto* tracker = CompactionTaskTracker::instance();
1123
105
    int64_t compaction_id = compaction->compaction_id();
1124
105
    {
1125
105
        CompactionTaskInfo info;
1126
105
        info.compaction_id = compaction_id;
1127
105
        info.tablet_id = tablet->tablet_id();
1128
105
        info.table_id = tablet->table_id();
1129
105
        info.partition_id = tablet->partition_id();
1130
105
        info.compaction_type = CompactionProfileType::FULL;
1131
105
        info.status = CompactionTaskStatus::PENDING;
1132
105
        info.trigger_method = static_cast<TriggerMethod>(trigger_method);
1133
105
        info.scheduled_time_ms =
1134
105
                duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1135
105
        info.backend_id = BackendOptions::get_backend_id();
1136
105
        info.compaction_score = tablet->get_real_compaction_score();
1137
105
        info.input_rowsets_count = compaction->input_rowsets_count();
1138
105
        info.input_row_num = compaction->input_row_num_value();
1139
105
        info.input_data_size = compaction->input_rowsets_data_size();
1140
105
        info.input_index_size = compaction->input_rowsets_index_size();
1141
105
        info.input_total_size = compaction->input_rowsets_total_size();
1142
105
        info.input_segments_num = compaction->input_segments_num_value();
1143
105
        info.input_version_range = compaction->input_version_range_str();
1144
105
        info.is_vertical = compaction->is_vertical();
1145
105
        tracker->register_task(std::move(info));
1146
105
    }
1147
105
    {
1148
105
        std::lock_guard lock(_compaction_mtx);
1149
105
        _submitted_full_compactions[tablet->tablet_id()] = compaction;
1150
105
    }
1151
105
    st = _base_compaction_thread_pool->submit_func([=, this, compaction = std::move(compaction)]() {
1152
105
        g_full_compaction_running_task_count << 1;
1153
105
        signal::tablet_id = tablet->tablet_id();
1154
105
        Defer defer {[&]() {
1155
            // Idempotent cleanup: remove task from tracker
1156
105
            CompactionTaskTracker::instance()->remove_task(compaction_id);
1157
105
            g_full_compaction_running_task_count << -1;
1158
105
            std::lock_guard lock(_compaction_mtx);
1159
105
            _submitted_full_compactions.erase(tablet->tablet_id());
1160
105
        }};
1161
105
        auto st = _request_tablet_global_compaction_lock(ReaderType::READER_FULL_COMPACTION, tablet,
1162
105
                                                         compaction);
1163
105
        if (!st.ok()) return;
1164
        // Update tracker to RUNNING after acquiring global lock
1165
105
        {
1166
105
            RunningStats rs;
1167
105
            rs.start_time_ms =
1168
105
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1169
105
            CompactionTaskTracker::instance()->update_to_running(compaction_id, rs);
1170
105
        }
1171
105
        st = compaction->execute_compact();
1172
105
        if (!st.ok()) {
1173
            // Error log has been output in `execute_compact`
1174
0
            long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1175
0
            tablet->set_last_full_compaction_failure_time(now);
1176
0
        }
1177
105
        std::lock_guard lock(_compaction_mtx);
1178
105
        _executing_full_compactions.erase(tablet->tablet_id());
1179
105
    });
1180
105
    if (!st.ok()) {
1181
0
        tracker->remove_task(compaction_id);
1182
0
        std::lock_guard lock(_compaction_mtx);
1183
0
        _submitted_full_compactions.erase(tablet->tablet_id());
1184
0
        return Status::InternalError("failed to submit full compaction, tablet_id={}",
1185
0
                                     tablet->tablet_id());
1186
0
    }
1187
105
    return st;
1188
105
}
1189
1190
Status CloudStorageEngine::submit_compaction_task(const CloudTabletSPtr& tablet,
1191
                                                  CompactionType compaction_type,
1192
115k
                                                  int trigger_method) {
1193
115k
    DCHECK(compaction_type == CompactionType::CUMULATIVE_COMPACTION ||
1194
115k
           compaction_type == CompactionType::BASE_COMPACTION ||
1195
115k
           compaction_type == CompactionType::FULL_COMPACTION);
1196
115k
    switch (compaction_type) {
1197
3.47k
    case CompactionType::BASE_COMPACTION:
1198
3.47k
        RETURN_IF_ERROR(_submit_base_compaction_task(tablet, trigger_method));
1199
73
        return Status::OK();
1200
111k
    case CompactionType::CUMULATIVE_COMPACTION:
1201
111k
        RETURN_IF_ERROR(_submit_cumulative_compaction_task(tablet, trigger_method));
1202
6.77k
        return Status::OK();
1203
105
    case CompactionType::FULL_COMPACTION:
1204
105
        RETURN_IF_ERROR(_submit_full_compaction_task(tablet, trigger_method));
1205
105
        return Status::OK();
1206
0
    default:
1207
0
        return Status::InternalError("unknown compaction type!");
1208
115k
    }
1209
115k
}
1210
1211
1
void CloudStorageEngine::_lease_compaction_thread_callback() {
1212
196
    while (!_stop_background_threads_latch.wait_for(
1213
196
            std::chrono::seconds(config::lease_compaction_interval_seconds))) {
1214
195
        std::vector<std::shared_ptr<CloudFullCompaction>> full_compactions;
1215
195
        std::vector<std::shared_ptr<CloudBaseCompaction>> base_compactions;
1216
195
        std::vector<std::shared_ptr<CloudCumulativeCompaction>> cumu_compactions;
1217
195
        std::vector<std::shared_ptr<CloudCompactionStopToken>> compation_stop_tokens;
1218
195
        std::vector<std::shared_ptr<CloudIndexChangeCompaction>> index_change_compations;
1219
195
        {
1220
195
            std::lock_guard lock(_compaction_mtx);
1221
195
            for (auto& [_, base] : _executing_base_compactions) {
1222
1
                if (base) { // `base` might be a nullptr placeholder
1223
1
                    base_compactions.push_back(base);
1224
1
                }
1225
1
            }
1226
195
            for (auto& [_, cumus] : _executing_cumu_compactions) {
1227
154
                for (auto& cumu : cumus) {
1228
154
                    cumu_compactions.push_back(cumu);
1229
154
                }
1230
154
            }
1231
195
            for (auto& [_, full] : _executing_full_compactions) {
1232
6
                if (full) {
1233
6
                    full_compactions.push_back(full);
1234
6
                }
1235
6
            }
1236
195
            for (auto& [_, stop_token] : _active_compaction_stop_tokens) {
1237
7
                if (stop_token) {
1238
5
                    compation_stop_tokens.push_back(stop_token);
1239
5
                }
1240
7
            }
1241
195
            for (auto& [_, index_change] : _submitted_index_change_cumu_compaction) {
1242
1
                if (index_change) {
1243
1
                    index_change_compations.push_back(index_change);
1244
1
                }
1245
1
            }
1246
195
            for (auto& [_, index_change] : _submitted_index_change_base_compaction) {
1247
0
                if (index_change) {
1248
0
                    index_change_compations.push_back(index_change);
1249
0
                }
1250
0
            }
1251
195
        }
1252
        // TODO(plat1ko): Support batch lease rpc
1253
195
        for (auto& stop_token : compation_stop_tokens) {
1254
5
            stop_token->do_lease();
1255
5
        }
1256
195
        for (auto& comp : full_compactions) {
1257
6
            comp->do_lease();
1258
6
        }
1259
195
        for (auto& comp : cumu_compactions) {
1260
154
            comp->do_lease();
1261
154
        }
1262
195
        for (auto& comp : base_compactions) {
1263
1
            comp->do_lease();
1264
1
        }
1265
195
        for (auto& comp : index_change_compations) {
1266
1
            comp->do_lease();
1267
1
        }
1268
195
    }
1269
1
}
1270
1271
1
void CloudStorageEngine::_check_tablet_delete_bitmap_score_callback() {
1272
1
    LOG(INFO) << "try to start check tablet delete bitmap score!";
1273
13
    while (!_stop_background_threads_latch.wait_for(
1274
13
            std::chrono::seconds(config::check_tablet_delete_bitmap_interval_seconds))) {
1275
12
        if (!config::enable_check_tablet_delete_bitmap_score) {
1276
0
            return;
1277
0
        }
1278
12
        uint64_t max_delete_bitmap_score = 0;
1279
12
        uint64_t max_base_rowset_delete_bitmap_score = 0;
1280
12
        tablet_mgr().get_topn_tablet_delete_bitmap_score(&max_delete_bitmap_score,
1281
12
                                                         &max_base_rowset_delete_bitmap_score);
1282
12
        if (max_delete_bitmap_score > 0) {
1283
12
            _tablet_max_delete_bitmap_score_metrics->set_value(max_delete_bitmap_score);
1284
12
        }
1285
12
        if (max_base_rowset_delete_bitmap_score > 0) {
1286
12
            _tablet_max_base_rowset_delete_bitmap_score_metrics->set_value(
1287
12
                    max_base_rowset_delete_bitmap_score);
1288
12
        }
1289
12
    }
1290
1
}
1291
1292
0
Status CloudStorageEngine::get_compaction_status_json(std::string* result) {
1293
0
    rapidjson::Document root;
1294
0
    root.SetObject();
1295
1296
0
    std::lock_guard lock(_compaction_mtx);
1297
    // cumu
1298
0
    std::string_view cumu = "CumulativeCompaction";
1299
0
    rapidjson::Value cumu_key;
1300
0
    cumu_key.SetString(cumu.data(), cast_set<uint32_t>(cumu.length()), root.GetAllocator());
1301
0
    rapidjson::Document cumu_arr;
1302
0
    cumu_arr.SetArray();
1303
0
    for (auto& [tablet_id, v] : _submitted_cumu_compactions) {
1304
0
        for (int i = 0; i < v.size(); ++i) {
1305
0
            cumu_arr.PushBack(tablet_id, root.GetAllocator());
1306
0
        }
1307
0
    }
1308
0
    root.AddMember(cumu_key, cumu_arr, root.GetAllocator());
1309
    // base
1310
0
    std::string_view base = "BaseCompaction";
1311
0
    rapidjson::Value base_key;
1312
0
    base_key.SetString(base.data(), cast_set<uint32_t>(base.length()), root.GetAllocator());
1313
0
    rapidjson::Document base_arr;
1314
0
    base_arr.SetArray();
1315
0
    for (auto& [tablet_id, _] : _submitted_base_compactions) {
1316
0
        base_arr.PushBack(tablet_id, root.GetAllocator());
1317
0
    }
1318
0
    root.AddMember(base_key, base_arr, root.GetAllocator());
1319
1320
0
    rapidjson::StringBuffer strbuf;
1321
0
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
1322
0
    root.Accept(writer);
1323
0
    *result = std::string(strbuf.GetString());
1324
0
    return Status::OK();
1325
0
}
1326
1327
std::shared_ptr<CloudCumulativeCompactionPolicy> CloudStorageEngine::cumu_compaction_policy(
1328
124k
        std::string_view compaction_policy) {
1329
124k
    if (!_cumulative_compaction_policies.contains(compaction_policy)) {
1330
0
        return _cumulative_compaction_policies.at(CUMULATIVE_SIZE_BASED_POLICY);
1331
0
    }
1332
124k
    return _cumulative_compaction_policies.at(compaction_policy);
1333
124k
}
1334
1335
Status CloudStorageEngine::register_compaction_stop_token(CloudTabletSPtr tablet,
1336
1.19k
                                                          int64_t initiator) {
1337
1.19k
    {
1338
1.19k
        std::lock_guard lock(_compaction_mtx);
1339
1.19k
        auto [_, success] = _active_compaction_stop_tokens.emplace(tablet->tablet_id(), nullptr);
1340
1.19k
        if (!success) {
1341
0
            return Status::AlreadyExist("stop token already exists for tablet_id={}",
1342
0
                                        tablet->tablet_id());
1343
0
        }
1344
1.19k
    }
1345
1346
1.19k
    auto stop_token = std::make_shared<CloudCompactionStopToken>(*this, tablet, initiator);
1347
1.19k
    auto st = stop_token->do_register();
1348
1349
1.19k
    if (!st.ok()) {
1350
0
        std::lock_guard lock(_compaction_mtx);
1351
0
        _active_compaction_stop_tokens.erase(tablet->tablet_id());
1352
0
        return st;
1353
0
    }
1354
1355
1.19k
    {
1356
1.19k
        std::lock_guard lock(_compaction_mtx);
1357
1.19k
        _active_compaction_stop_tokens[tablet->tablet_id()] = stop_token;
1358
1.19k
    }
1359
1.19k
    LOG_INFO(
1360
1.19k
            "successfully register compaction stop token for tablet_id={}, "
1361
1.19k
            "delete_bitmap_lock_initiator={}",
1362
1.19k
            tablet->tablet_id(), initiator);
1363
1.19k
    return st;
1364
1.19k
}
1365
1366
1.19k
Status CloudStorageEngine::unregister_compaction_stop_token(CloudTabletSPtr tablet, bool clear_ms) {
1367
1.19k
    std::shared_ptr<CloudCompactionStopToken> stop_token;
1368
1.19k
    {
1369
1.19k
        std::lock_guard lock(_compaction_mtx);
1370
1.19k
        if (auto it = _active_compaction_stop_tokens.find(tablet->tablet_id());
1371
1.19k
            it != _active_compaction_stop_tokens.end()) {
1372
1.19k
            stop_token = it->second;
1373
1.19k
        } else {
1374
0
            return Status::NotFound("stop token not found for tablet_id={}", tablet->tablet_id());
1375
0
        }
1376
1.19k
        _active_compaction_stop_tokens.erase(tablet->tablet_id());
1377
1.19k
    }
1378
1.19k
    LOG_INFO("successfully unregister compaction stop token for tablet_id={}", tablet->tablet_id());
1379
1.19k
    if (stop_token && clear_ms) {
1380
0
        RETURN_IF_ERROR(stop_token->do_unregister());
1381
0
        LOG_INFO(
1382
0
                "successfully remove compaction stop token from MS for tablet_id={}, "
1383
0
                "delete_bitmap_lock_initiator={}",
1384
0
                tablet->tablet_id(), stop_token->initiator());
1385
0
    }
1386
1.19k
    return Status::OK();
1387
1.19k
}
1388
1389
1
Status CloudStorageEngine::_check_all_root_path_cluster_id() {
1390
    // Check if all root paths have the same cluster id
1391
1
    std::set<int32_t> cluster_ids;
1392
1
    for (const auto& path : _options.store_paths) {
1393
1
        auto cluster_id_path = fmt::format("{}/{}", path.path, CLUSTER_ID_PREFIX);
1394
1
        bool exists = false;
1395
1
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(cluster_id_path, &exists));
1396
1
        if (exists) {
1397
0
            io::FileReaderSPtr reader;
1398
0
            RETURN_IF_ERROR(io::global_local_filesystem()->open_file(cluster_id_path, &reader));
1399
0
            size_t fsize = reader->size();
1400
0
            if (fsize > 0) {
1401
0
                std::string content;
1402
0
                content.resize(fsize, '\0');
1403
0
                size_t bytes_read = 0;
1404
0
                RETURN_IF_ERROR(reader->read_at(0, {content.data(), fsize}, &bytes_read));
1405
0
                DCHECK_EQ(fsize, bytes_read);
1406
0
                int32_t tmp_cluster_id = std::stoi(content);
1407
0
                cluster_ids.insert(tmp_cluster_id);
1408
0
            }
1409
0
        }
1410
1
    }
1411
1
    _effective_cluster_id = config::cluster_id;
1412
    // first init
1413
1
    if (cluster_ids.empty()) {
1414
        // not set configured cluster id
1415
1
        if (_effective_cluster_id == -1) {
1416
1
            return Status::OK();
1417
1
        } else {
1418
            // If no cluster id file exists, use the configured cluster id
1419
0
            return set_cluster_id(_effective_cluster_id);
1420
0
        }
1421
1
    }
1422
0
    if (cluster_ids.size() > 1) {
1423
0
        return Status::InternalError(
1424
0
                "All root paths must have the same cluster id, but you have "
1425
0
                "different cluster ids: {}",
1426
0
                fmt::join(cluster_ids, ", "));
1427
0
    }
1428
0
    if (_effective_cluster_id != -1 && !cluster_ids.empty() &&
1429
0
        *cluster_ids.begin() != _effective_cluster_id) {
1430
0
        return Status::Corruption(
1431
0
                "multiple cluster ids is not equal. config::cluster_id={}, "
1432
0
                "storage path cluster_id={}",
1433
0
                _effective_cluster_id, *cluster_ids.begin());
1434
0
    }
1435
0
    return Status::OK();
1436
0
}
1437
1438
1
Status CloudStorageEngine::set_cluster_id(int32_t cluster_id) {
1439
1
    std::lock_guard<std::mutex> l(_store_lock);
1440
1
    for (auto& path : _options.store_paths) {
1441
1
        auto cluster_id_path = fmt::format("{}/{}", path.path, CLUSTER_ID_PREFIX);
1442
1
        bool exists = false;
1443
1
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(cluster_id_path, &exists));
1444
1
        if (!exists) {
1445
1
            io::FileWriterPtr file_writer;
1446
1
            RETURN_IF_ERROR(
1447
1
                    io::global_local_filesystem()->create_file(cluster_id_path, &file_writer));
1448
1
            RETURN_IF_ERROR(file_writer->append(std::to_string(cluster_id)));
1449
1
            RETURN_IF_ERROR(file_writer->close());
1450
1
        }
1451
1
    }
1452
1
    _effective_cluster_id = cluster_id;
1453
1
    return Status::OK();
1454
1
}
1455
1456
} // namespace doris