Coverage Report

Created: 2026-06-08 17:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/olap_server.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 <gen_cpp/Types_types.h>
19
#include <gen_cpp/olap_file.pb.h>
20
#include <glog/logging.h>
21
#include <rapidjson/prettywriter.h>
22
#include <rapidjson/stringbuffer.h>
23
#include <stdint.h>
24
#include <sys/types.h>
25
26
#include <algorithm>
27
#include <atomic>
28
// IWYU pragma: no_include <bits/chrono.h>
29
#include <gen_cpp/internal_service.pb.h>
30
31
#include <chrono> // IWYU pragma: keep
32
#include <cmath>
33
#include <condition_variable>
34
#include <cstdint>
35
#include <ctime>
36
#include <functional>
37
#include <map>
38
#include <memory>
39
#include <mutex>
40
#include <ostream>
41
#include <random>
42
#include <shared_mutex>
43
#include <string>
44
#include <thread>
45
#include <unordered_set>
46
#include <utility>
47
#include <vector>
48
49
#include "agent/utils.h"
50
#include "common/config.h"
51
#include "common/logging.h"
52
#include "common/metrics/doris_metrics.h"
53
#include "common/metrics/metrics.h"
54
#include "common/status.h"
55
#include "cpp/sync_point.h"
56
#include "io/fs/file_writer.h" // IWYU pragma: keep
57
#include "io/fs/path.h"
58
#include "load/memtable/memtable_flush_executor.h"
59
#include "runtime/memory/cache_manager.h"
60
#include "runtime/memory/global_memory_arbitrator.h"
61
#include "storage/compaction/cold_data_compaction.h"
62
#include "storage/compaction/compaction_permit_limiter.h"
63
#include "storage/compaction/cumulative_compaction.h"
64
#include "storage/compaction/cumulative_compaction_policy.h"
65
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
66
#include "storage/compaction_task_tracker.h"
67
#include "storage/data_dir.h"
68
#include "storage/olap_common.h"
69
#include "storage/olap_define.h"
70
#include "storage/rowset/segcompaction.h"
71
#include "storage/schema_change/schema_change.h"
72
#include "storage/storage_engine.h"
73
#include "storage/storage_policy.h"
74
#include "storage/tablet/base_tablet.h"
75
#include "storage/tablet/tablet.h"
76
#include "storage/tablet/tablet_manager.h"
77
#include "storage/tablet/tablet_meta.h"
78
#include "storage/tablet/tablet_meta_manager.h"
79
#include "storage/tablet/tablet_schema.h"
80
#include "storage/task/engine_publish_version_task.h"
81
#include "storage/task/index_builder.h"
82
#include "util/client_cache.h"
83
#include "util/countdown_latch.h"
84
#include "util/debug_points.h"
85
#include "util/mem_info.h"
86
#include "util/thread.h"
87
#include "util/threadpool.h"
88
#include "util/time.h"
89
#include "util/uid_util.h"
90
#include "util/work_thread_pool.hpp"
91
92
using std::string;
93
94
namespace doris {
95
using io::Path;
96
97
// number of running SCHEMA-CHANGE threads
98
volatile uint32_t g_schema_change_active_threads = 0;
99
bvar::Status<int64_t> g_cumu_compaction_task_num_per_round("cumu_compaction_task_num_per_round", 0);
100
bvar::Status<int64_t> g_base_compaction_task_num_per_round("base_compaction_task_num_per_round", 0);
101
102
0
CompactionSubmitRegistry::CompactionSubmitRegistry(CompactionSubmitRegistry&& r) {
103
0
    std::swap(_tablet_submitted_cumu_compaction, r._tablet_submitted_cumu_compaction);
104
0
    std::swap(_tablet_submitted_base_compaction, r._tablet_submitted_base_compaction);
105
0
    std::swap(_tablet_submitted_full_compaction, r._tablet_submitted_full_compaction);
106
0
    std::swap(_tablet_submitted_binlog_compaction, r._tablet_submitted_binlog_compaction);
107
0
}
108
109
5
CompactionSubmitRegistry CompactionSubmitRegistry::create_snapshot() {
110
    // full compaction is not engaged in this method
111
5
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
112
5
    CompactionSubmitRegistry registry;
113
5
    registry._tablet_submitted_base_compaction = _tablet_submitted_base_compaction;
114
5
    registry._tablet_submitted_cumu_compaction = _tablet_submitted_cumu_compaction;
115
5
    registry._tablet_submitted_binlog_compaction = _tablet_submitted_binlog_compaction;
116
5
    return registry;
117
5
}
118
119
2
void CompactionSubmitRegistry::reset(const std::vector<DataDir*>& stores) {
120
    // full compaction is not engaged in this method
121
2
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
122
2
    for (const auto& store : stores) {
123
2
        _tablet_submitted_cumu_compaction[store] = {};
124
2
        _tablet_submitted_base_compaction[store] = {};
125
2
        _tablet_submitted_binlog_compaction[store] = {};
126
2
    }
127
2
}
128
129
uint32_t CompactionSubmitRegistry::count_executing_compaction(DataDir* dir,
130
12
                                                              CompactionType compaction_type) {
131
    // non-lock, used in snapshot
132
12
    const auto& compaction_tasks = _get_tablet_set(dir, compaction_type);
133
12
    return cast_set<uint32_t>(std::count_if(
134
12
            compaction_tasks.begin(), compaction_tasks.end(),
135
12
            [](const auto& task) { return task->compaction_stage == CompactionStage::EXECUTING; }));
136
12
}
137
138
6
uint32_t CompactionSubmitRegistry::count_executing_cumu_and_base(DataDir* dir) {
139
    // non-lock, used in snapshot
140
6
    return count_executing_compaction(dir, CompactionType::BASE_COMPACTION) +
141
6
           count_executing_compaction(dir, CompactionType::CUMULATIVE_COMPACTION);
142
6
}
143
144
9
bool CompactionSubmitRegistry::has_compaction_task(DataDir* dir, CompactionType compaction_type) {
145
    // non-lock, used in snapshot
146
9
    return !_get_tablet_set(dir, compaction_type).empty();
147
9
}
148
149
std::vector<TabletCompactionContext> CompactionSubmitRegistry::pick_topn_tablets_for_compaction(
150
        TabletManager* tablet_mgr, DataDir* data_dir, CompactionType compaction_type,
151
        const CumuCompactionPolicyTable& cumu_compaction_policies,
152
4
        CompactionScoreStats* disk_score_stats) {
153
    // non-lock, used in snapshot
154
4
    return tablet_mgr->find_best_tablets_to_compaction(compaction_type, data_dir,
155
4
                                                       _get_tablet_set(data_dir, compaction_type),
156
4
                                                       disk_score_stats, cumu_compaction_policies);
157
4
}
158
159
22
bool CompactionSubmitRegistry::insert(TabletSharedPtr tablet, CompactionType compaction_type) {
160
22
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
161
22
    auto& tablet_set = _get_tablet_set(tablet->data_dir(), compaction_type);
162
22
    bool already_exist = !(tablet_set.insert(tablet).second);
163
22
    return already_exist;
164
22
}
165
166
void CompactionSubmitRegistry::remove(TabletSharedPtr tablet, CompactionType compaction_type,
167
7
                                      std::function<void()> wakeup_cb) {
168
7
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
169
7
    auto& tablet_set = _get_tablet_set(tablet->data_dir(), compaction_type);
170
7
    size_t removed = tablet_set.erase(tablet);
171
7
    if (removed == 1) {
172
7
        wakeup_cb();
173
7
    }
174
7
}
175
176
CompactionSubmitRegistry::TabletSet& CompactionSubmitRegistry::_get_tablet_set(
177
54
        DataDir* dir, CompactionType compaction_type) {
178
54
    switch (compaction_type) {
179
6
    case CompactionType::BASE_COMPACTION:
180
6
        return _tablet_submitted_base_compaction[dir];
181
48
    case CompactionType::CUMULATIVE_COMPACTION:
182
48
        return _tablet_submitted_cumu_compaction[dir];
183
0
    case CompactionType::FULL_COMPACTION:
184
0
        return _tablet_submitted_full_compaction[dir];
185
0
    case CompactionType::BINLOG_COMPACTION:
186
0
        return _tablet_submitted_binlog_compaction[dir];
187
0
    default:
188
0
        CHECK(false) << "invalid compaction type";
189
54
    }
190
54
}
191
192
0
static int32_t get_cumu_compaction_threads_num(size_t data_dirs_num) {
193
0
    int32_t threads_num = config::max_cumu_compaction_threads;
194
0
    if (threads_num == -1) {
195
0
        int32_t num_cores = doris::CpuInfo::num_cores();
196
0
        threads_num = std::max(cast_set<int32_t>(data_dirs_num), num_cores / 6);
197
0
    }
198
0
    threads_num = threads_num <= 0 ? 1 : threads_num;
199
0
    return threads_num;
200
0
}
201
202
0
static int32_t get_base_compaction_threads_num(size_t data_dirs_num) {
203
0
    int32_t threads_num = config::max_base_compaction_threads;
204
0
    if (threads_num == -1) {
205
0
        threads_num = cast_set<int32_t>(data_dirs_num);
206
0
    }
207
0
    threads_num = threads_num <= 0 ? 1 : threads_num;
208
0
    return threads_num;
209
0
}
210
211
0
static int32_t get_binlog_compaction_threads_num(size_t data_dirs_num) {
212
0
    int32_t threads_num = config::max_binlog_compaction_threads;
213
0
    if (threads_num == -1) {
214
0
        threads_num = cast_set<int32_t>(data_dirs_num);
215
0
    }
216
0
    threads_num = threads_num <= 0 ? 1 : threads_num;
217
0
    return threads_num;
218
0
}
219
220
0
Status StorageEngine::start_bg_threads(std::shared_ptr<WorkloadGroup> wg_sptr) {
221
0
    RETURN_IF_ERROR(Thread::create(
222
0
            "StorageEngine", "unused_rowset_monitor_thread",
223
0
            [this]() { this->_unused_rowset_monitor_thread_callback(); },
224
0
            &_unused_rowset_monitor_thread));
225
0
    LOG(INFO) << "unused rowset monitor thread started";
226
227
0
    RETURN_IF_ERROR(Thread::create(
228
0
            "StorageEngine", "evict_querying_rowset_thread",
229
0
            [this]() { this->_evict_quring_rowset_thread_callback(); },
230
0
            &_evict_quering_rowset_thread));
231
0
    LOG(INFO) << "evict quering thread started";
232
233
    // start thread for monitoring the snapshot and trash folder
234
0
    RETURN_IF_ERROR(Thread::create(
235
0
            "StorageEngine", "garbage_sweeper_thread",
236
0
            [this]() { this->_garbage_sweeper_thread_callback(); }, &_garbage_sweeper_thread));
237
0
    LOG(INFO) << "garbage sweeper thread started";
238
239
    // start thread for monitoring the tablet with io error
240
0
    RETURN_IF_ERROR(Thread::create(
241
0
            "StorageEngine", "disk_stat_monitor_thread",
242
0
            [this]() { this->_disk_stat_monitor_thread_callback(); }, &_disk_stat_monitor_thread));
243
0
    LOG(INFO) << "disk stat monitor thread started";
244
245
    // convert store map to vector
246
0
    std::vector<DataDir*> data_dirs = get_stores();
247
248
0
    auto base_compaction_threads = get_base_compaction_threads_num(data_dirs.size());
249
0
    auto cumu_compaction_threads = get_cumu_compaction_threads_num(data_dirs.size());
250
0
    auto binlog_compaction_threads = get_binlog_compaction_threads_num(data_dirs.size());
251
252
0
    RETURN_IF_ERROR(ThreadPoolBuilder("BaseCompactionTaskThreadPool")
253
0
                            .set_min_threads(base_compaction_threads)
254
0
                            .set_max_threads(base_compaction_threads)
255
0
                            .build(&_base_compaction_thread_pool));
256
0
    RETURN_IF_ERROR(ThreadPoolBuilder("CumuCompactionTaskThreadPool")
257
0
                            .set_min_threads(cumu_compaction_threads)
258
0
                            .set_max_threads(cumu_compaction_threads)
259
0
                            .build(&_cumu_compaction_thread_pool));
260
0
    RETURN_IF_ERROR(ThreadPoolBuilder("BinlogCompactionTaskThreadPool")
261
0
                            .set_min_threads(binlog_compaction_threads)
262
0
                            .set_max_threads(binlog_compaction_threads)
263
0
                            .build(&_binlog_compaction_thread_pool));
264
265
0
    if (config::enable_segcompaction) {
266
0
        RETURN_IF_ERROR(ThreadPoolBuilder("SegCompactionTaskThreadPool")
267
0
                                .set_min_threads(config::segcompaction_num_threads)
268
0
                                .set_max_threads(config::segcompaction_num_threads)
269
0
                                .build(&_seg_compaction_thread_pool));
270
0
    }
271
0
    RETURN_IF_ERROR(ThreadPoolBuilder("ColdDataCompactionTaskThreadPool")
272
0
                            .set_min_threads(config::cold_data_compaction_thread_num)
273
0
                            .set_max_threads(config::cold_data_compaction_thread_num)
274
0
                            .build(&_cold_data_compaction_thread_pool));
275
276
0
    _compaction_submit_registry.reset(data_dirs);
277
278
    // compaction tasks producer thread
279
0
    RETURN_IF_ERROR(Thread::create(
280
0
            "StorageEngine", "compaction_tasks_producer_thread",
281
0
            [this]() { this->_compaction_tasks_producer_callback(); },
282
0
            &_compaction_tasks_producer_thread));
283
0
    LOG(INFO) << "compaction tasks producer thread started";
284
285
0
    RETURN_IF_ERROR(Thread::create(
286
0
            "StorageEngine", "binlog_compaction_tasks_producer_thread",
287
0
            [this]() { this->_binlog_compaction_tasks_producer_callback(); },
288
0
            &_binlog_compaction_tasks_producer_thread));
289
0
    LOG(INFO) << "binlog compaction tasks producer thread started";
290
291
0
    int32_t max_checkpoint_thread_num = config::max_meta_checkpoint_threads;
292
0
    if (max_checkpoint_thread_num < 0) {
293
0
        max_checkpoint_thread_num = cast_set<int32_t>(data_dirs.size());
294
0
    }
295
0
    RETURN_IF_ERROR(ThreadPoolBuilder("TabletMetaCheckpointTaskThreadPool")
296
0
                            .set_max_threads(max_checkpoint_thread_num)
297
0
                            .build(&_tablet_meta_checkpoint_thread_pool));
298
299
0
    RETURN_IF_ERROR(Thread::create(
300
0
            "StorageEngine", "tablet_checkpoint_tasks_producer_thread",
301
0
            [this, data_dirs]() { this->_tablet_checkpoint_callback(data_dirs); },
302
0
            &_tablet_checkpoint_tasks_producer_thread));
303
0
    LOG(INFO) << "tablet checkpoint tasks producer thread started";
304
305
0
    RETURN_IF_ERROR(Thread::create(
306
0
            "StorageEngine", "tablet_path_check_thread",
307
0
            [this]() { this->_tablet_path_check_callback(); }, &_tablet_path_check_thread));
308
0
    LOG(INFO) << "tablet path check thread started";
309
310
    // path scan and gc thread
311
0
    if (config::path_gc_check) {
312
0
        for (auto data_dir : get_stores()) {
313
0
            std::shared_ptr<Thread> path_gc_thread;
314
0
            RETURN_IF_ERROR(Thread::create(
315
0
                    "StorageEngine", "path_gc_thread",
316
0
                    [this, data_dir]() { this->_path_gc_thread_callback(data_dir); },
317
0
                    &path_gc_thread));
318
0
            _path_gc_threads.emplace_back(path_gc_thread);
319
0
        }
320
0
        LOG(INFO) << "path gc threads started. number:" << get_stores().size();
321
0
    }
322
323
0
    RETURN_IF_ERROR(ThreadPoolBuilder("CooldownTaskThreadPool")
324
0
                            .set_min_threads(config::cooldown_thread_num)
325
0
                            .set_max_threads(config::cooldown_thread_num)
326
0
                            .build(&_cooldown_thread_pool));
327
0
    LOG(INFO) << "cooldown thread pool started";
328
329
0
    RETURN_IF_ERROR(Thread::create(
330
0
            "StorageEngine", "cooldown_tasks_producer_thread",
331
0
            [this]() { this->_cooldown_tasks_producer_callback(); },
332
0
            &_cooldown_tasks_producer_thread));
333
0
    LOG(INFO) << "cooldown tasks producer thread started";
334
335
0
    RETURN_IF_ERROR(Thread::create(
336
0
            "StorageEngine", "remove_unused_remote_files_thread",
337
0
            [this]() { this->_remove_unused_remote_files_callback(); },
338
0
            &_remove_unused_remote_files_thread));
339
0
    LOG(INFO) << "remove unused remote files thread started";
340
341
0
    RETURN_IF_ERROR(Thread::create(
342
0
            "StorageEngine", "cold_data_compaction_producer_thread",
343
0
            [this]() { this->_cold_data_compaction_producer_callback(); },
344
0
            &_cold_data_compaction_producer_thread));
345
0
    LOG(INFO) << "cold data compaction producer thread started";
346
347
    // add tablet publish version thread pool
348
0
    RETURN_IF_ERROR(ThreadPoolBuilder("TabletPublishTxnThreadPool")
349
0
                            .set_min_threads(config::tablet_publish_txn_max_thread)
350
0
                            .set_max_threads(config::tablet_publish_txn_max_thread)
351
0
                            .build(&_tablet_publish_txn_thread_pool));
352
353
0
    RETURN_IF_ERROR(Thread::create(
354
0
            "StorageEngine", "async_publish_version_thread",
355
0
            [this]() { this->_async_publish_callback(); }, &_async_publish_thread));
356
0
    LOG(INFO) << "async publish thread started";
357
358
0
    RETURN_IF_ERROR(Thread::create(
359
0
            "StorageEngine", "check_tablet_delete_bitmap_score_thread",
360
0
            [this]() { this->_check_tablet_delete_bitmap_score_callback(); },
361
0
            &_check_delete_bitmap_score_thread));
362
0
    LOG(INFO) << "check tablet delete bitmap score thread started";
363
364
0
    _start_adaptive_thread_controller();
365
366
0
    LOG(INFO) << "all storage engine's background threads are started.";
367
0
    return Status::OK();
368
0
}
369
370
0
void StorageEngine::_garbage_sweeper_thread_callback() {
371
0
    uint32_t max_interval = config::max_garbage_sweep_interval;
372
0
    uint32_t min_interval = config::min_garbage_sweep_interval;
373
374
0
    if (max_interval < min_interval || min_interval <= 0) {
375
0
        LOG(WARNING) << "garbage sweep interval config is illegal: [max=" << max_interval
376
0
                     << " min=" << min_interval << "].";
377
0
        min_interval = 1;
378
0
        max_interval = max_interval >= min_interval ? max_interval : min_interval;
379
0
        LOG(INFO) << "force reset garbage sweep interval. "
380
0
                  << "max_interval=" << max_interval << ", min_interval=" << min_interval;
381
0
    }
382
383
0
    const double pi = M_PI;
384
0
    double usage = 1.0;
385
    // After the program starts, the first round of cleaning starts after min_interval.
386
0
    uint32_t curr_interval = min_interval;
387
0
    do {
388
        // Function properties:
389
        // when usage < 0.6,          ratio close to 1.(interval close to max_interval)
390
        // when usage at [0.6, 0.75], ratio is rapidly decreasing from 0.87 to 0.27.
391
        // when usage > 0.75,         ratio is slowly decreasing.
392
        // when usage > 0.8,          ratio close to min_interval.
393
        // when usage = 0.88,         ratio is approximately 0.0057.
394
0
        double ratio = (1.1 * (pi / 2 - std::atan(usage * 100 / 5 - 14)) - 0.28) / pi;
395
0
        ratio = ratio > 0 ? ratio : 0;
396
        // TODO(dx): fix it
397
0
        auto curr_interval_not_work = uint32_t(max_interval * ratio);
398
0
        curr_interval_not_work = std::max(curr_interval_not_work, min_interval);
399
0
        curr_interval_not_work = std::min(curr_interval_not_work, max_interval);
400
401
        // start clean trash and update usage.
402
0
        Status res = start_trash_sweep(&usage);
403
0
        if (res.ok() && _need_clean_trash.exchange(false, std::memory_order_relaxed)) {
404
0
            res = start_trash_sweep(&usage, true);
405
0
        }
406
407
0
        if (!res.ok()) {
408
0
            LOG(WARNING) << "one or more errors occur when sweep trash."
409
0
                         << "see previous message for detail. err code=" << res;
410
            // do nothing. continue next loop.
411
0
        }
412
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(curr_interval)));
413
0
}
414
415
0
void StorageEngine::_disk_stat_monitor_thread_callback() {
416
0
    int32_t interval = config::disk_stat_monitor_interval;
417
0
    do {
418
0
        _start_disk_stat_monitor();
419
420
0
        interval = config::disk_stat_monitor_interval;
421
0
        if (interval <= 0) {
422
0
            LOG(WARNING) << "disk_stat_monitor_interval config is illegal: " << interval
423
0
                         << ", force set to 1";
424
0
            interval = 1;
425
0
        }
426
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
427
0
}
428
429
0
void StorageEngine::_unused_rowset_monitor_thread_callback() {
430
0
    int32_t interval = config::unused_rowset_monitor_interval;
431
0
    do {
432
0
        start_delete_unused_rowset();
433
434
0
        interval = config::unused_rowset_monitor_interval;
435
0
        if (interval <= 0) {
436
0
            LOG(WARNING) << "unused_rowset_monitor_interval config is illegal: " << interval
437
0
                         << ", force set to 1";
438
0
            interval = 1;
439
0
        }
440
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
441
0
}
442
443
0
int32_t StorageEngine::_auto_get_interval_by_disk_capacity(DataDir* data_dir) {
444
0
    double disk_used = data_dir->get_usage(0);
445
0
    double remain_used = 1 - disk_used;
446
0
    DCHECK(remain_used >= 0 && remain_used <= 1);
447
0
    DCHECK(config::path_gc_check_interval_second >= 0);
448
0
    int32_t ret = 0;
449
0
    if (remain_used > 0.9) {
450
        // if config::path_gc_check_interval_second == 24h
451
0
        ret = config::path_gc_check_interval_second;
452
0
    } else if (remain_used > 0.7) {
453
        // 12h
454
0
        ret = config::path_gc_check_interval_second / 2;
455
0
    } else if (remain_used > 0.5) {
456
        // 6h
457
0
        ret = config::path_gc_check_interval_second / 4;
458
0
    } else if (remain_used > 0.3) {
459
        // 4h
460
0
        ret = config::path_gc_check_interval_second / 6;
461
0
    } else {
462
        // 3h
463
0
        ret = config::path_gc_check_interval_second / 8;
464
0
    }
465
0
    return ret;
466
0
}
467
468
0
void StorageEngine::_path_gc_thread_callback(DataDir* data_dir) {
469
0
    LOG(INFO) << "try to start path gc thread!";
470
0
    time_t last_exec_time = 0;
471
0
    do {
472
0
        time_t current_time = time(nullptr);
473
474
0
        int32_t interval = _auto_get_interval_by_disk_capacity(data_dir);
475
0
        DBUG_EXECUTE_IF("_path_gc_thread_callback.interval.eq.1ms", {
476
0
            LOG(INFO) << "debug point change interval eq 1ms";
477
0
            interval = 1;
478
0
            while (DebugPoints::instance()->is_enable("_path_gc_thread_callback.always.do")) {
479
0
                data_dir->perform_path_gc();
480
0
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
481
0
            }
482
0
        });
483
0
        if (interval <= 0) {
484
0
            LOG(WARNING) << "path gc thread check interval config is illegal:" << interval
485
0
                         << " will be forced set to half hour";
486
0
            interval = 1800; // 0.5 hour
487
0
        }
488
0
        if (current_time - last_exec_time >= interval) {
489
0
            LOG(INFO) << "try to perform path gc! disk remain [" << 1 - data_dir->get_usage(0)
490
0
                      << "] internal [" << interval << "]";
491
0
            data_dir->perform_path_gc();
492
0
            last_exec_time = time(nullptr);
493
0
        }
494
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(5)));
495
0
    LOG(INFO) << "stop path gc thread!";
496
0
}
497
498
0
void StorageEngine::_tablet_checkpoint_callback(const std::vector<DataDir*>& data_dirs) {
499
0
    int64_t interval = config::generate_tablet_meta_checkpoint_tasks_interval_secs;
500
0
    do {
501
0
        for (auto data_dir : data_dirs) {
502
0
            LOG(INFO) << "begin to produce tablet meta checkpoint tasks, data_dir="
503
0
                      << data_dir->path();
504
0
            auto st = _tablet_meta_checkpoint_thread_pool->submit_func(
505
0
                    [data_dir, this]() { _tablet_manager->do_tablet_meta_checkpoint(data_dir); });
506
0
            if (!st.ok()) {
507
0
                LOG(WARNING) << "submit tablet checkpoint tasks failed.";
508
0
            }
509
0
        }
510
0
        interval = config::generate_tablet_meta_checkpoint_tasks_interval_secs;
511
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
512
0
}
513
514
0
void StorageEngine::_tablet_path_check_callback() {
515
0
    struct TabletIdComparator {
516
0
        bool operator()(Tablet* a, Tablet* b) { return a->tablet_id() < b->tablet_id(); }
517
0
    };
518
519
0
    using TabletQueue = std::priority_queue<Tablet*, std::vector<Tablet*>, TabletIdComparator>;
520
521
0
    int64_t interval = config::tablet_path_check_interval_seconds;
522
0
    if (interval <= 0) {
523
0
        return;
524
0
    }
525
526
0
    int64_t last_tablet_id = 0;
527
0
    do {
528
0
        int32_t batch_size = config::tablet_path_check_batch_size;
529
0
        if (batch_size <= 0) {
530
0
            if (_stop_background_threads_latch.wait_for(std::chrono::seconds(interval))) {
531
0
                break;
532
0
            }
533
0
            continue;
534
0
        }
535
536
0
        LOG(INFO) << "start to check tablet path";
537
538
0
        auto all_tablets = _tablet_manager->get_all_tablet(
539
0
                [](Tablet* t) { return t->is_used() && t->tablet_state() == TABLET_RUNNING; });
540
541
0
        TabletQueue big_id_tablets;
542
0
        TabletQueue small_id_tablets;
543
0
        for (auto tablet : all_tablets) {
544
0
            auto tablet_id = tablet->tablet_id();
545
0
            TabletQueue* belong_tablets = nullptr;
546
0
            if (tablet_id > last_tablet_id) {
547
0
                if (big_id_tablets.size() < batch_size ||
548
0
                    big_id_tablets.top()->tablet_id() > tablet_id) {
549
0
                    belong_tablets = &big_id_tablets;
550
0
                }
551
0
            } else if (big_id_tablets.size() < batch_size) {
552
0
                if (small_id_tablets.size() < batch_size ||
553
0
                    small_id_tablets.top()->tablet_id() > tablet_id) {
554
0
                    belong_tablets = &small_id_tablets;
555
0
                }
556
0
            }
557
0
            if (belong_tablets != nullptr) {
558
0
                belong_tablets->push(tablet.get());
559
0
                if (belong_tablets->size() > batch_size) {
560
0
                    belong_tablets->pop();
561
0
                }
562
0
            }
563
0
        }
564
565
0
        int32_t need_small_id_tablet_size =
566
0
                batch_size - static_cast<int32_t>(big_id_tablets.size());
567
568
0
        if (!big_id_tablets.empty()) {
569
0
            last_tablet_id = big_id_tablets.top()->tablet_id();
570
0
        }
571
0
        while (!big_id_tablets.empty()) {
572
0
            big_id_tablets.top()->check_tablet_path_exists();
573
0
            big_id_tablets.pop();
574
0
        }
575
576
0
        if (!small_id_tablets.empty() && need_small_id_tablet_size > 0) {
577
0
            while (static_cast<int32_t>(small_id_tablets.size()) > need_small_id_tablet_size) {
578
0
                small_id_tablets.pop();
579
0
            }
580
581
0
            last_tablet_id = small_id_tablets.top()->tablet_id();
582
0
            while (!small_id_tablets.empty()) {
583
0
                small_id_tablets.top()->check_tablet_path_exists();
584
0
                small_id_tablets.pop();
585
0
            }
586
0
        }
587
588
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
589
0
}
590
591
6
void StorageEngine::_adjust_compaction_thread_num() {
592
6
    TEST_SYNC_POINT_RETURN_WITH_VOID("StorageEngine::_adjust_compaction_thread_num.return_void");
593
0
    auto base_compaction_threads_num = get_base_compaction_threads_num(_store_map.size());
594
0
    if (_base_compaction_thread_pool->max_threads() != base_compaction_threads_num) {
595
0
        int old_max_threads = _base_compaction_thread_pool->max_threads();
596
0
        Status status = _base_compaction_thread_pool->set_max_threads(base_compaction_threads_num);
597
0
        if (status.ok()) {
598
0
            VLOG_NOTICE << "update base compaction thread pool max_threads from " << old_max_threads
599
0
                        << " to " << base_compaction_threads_num;
600
0
        }
601
0
    }
602
0
    if (_base_compaction_thread_pool->min_threads() != base_compaction_threads_num) {
603
0
        int old_min_threads = _base_compaction_thread_pool->min_threads();
604
0
        Status status = _base_compaction_thread_pool->set_min_threads(base_compaction_threads_num);
605
0
        if (status.ok()) {
606
0
            VLOG_NOTICE << "update base compaction thread pool min_threads from " << old_min_threads
607
0
                        << " to " << base_compaction_threads_num;
608
0
        }
609
0
    }
610
611
0
    auto cumu_compaction_threads_num = get_cumu_compaction_threads_num(_store_map.size());
612
0
    if (_cumu_compaction_thread_pool->max_threads() != cumu_compaction_threads_num) {
613
0
        int old_max_threads = _cumu_compaction_thread_pool->max_threads();
614
0
        Status status = _cumu_compaction_thread_pool->set_max_threads(cumu_compaction_threads_num);
615
0
        if (status.ok()) {
616
0
            VLOG_NOTICE << "update cumu compaction thread pool max_threads from " << old_max_threads
617
0
                        << " to " << cumu_compaction_threads_num;
618
0
        }
619
0
    }
620
0
    if (_cumu_compaction_thread_pool->min_threads() != cumu_compaction_threads_num) {
621
0
        int old_min_threads = _cumu_compaction_thread_pool->min_threads();
622
0
        Status status = _cumu_compaction_thread_pool->set_min_threads(cumu_compaction_threads_num);
623
0
        if (status.ok()) {
624
0
            VLOG_NOTICE << "update cumu compaction thread pool min_threads from " << old_min_threads
625
0
                        << " to " << cumu_compaction_threads_num;
626
0
        }
627
0
    }
628
629
0
    auto binlog_compaction_threads_num = get_binlog_compaction_threads_num(_store_map.size());
630
0
    if (_binlog_compaction_thread_pool->max_threads() != binlog_compaction_threads_num) {
631
0
        int old_max_threads = _binlog_compaction_thread_pool->max_threads();
632
0
        Status status =
633
0
                _binlog_compaction_thread_pool->set_max_threads(binlog_compaction_threads_num);
634
0
        if (status.ok()) {
635
0
            VLOG_NOTICE << "update binlog compaction thread pool max_threads from "
636
0
                        << old_max_threads << " to " << binlog_compaction_threads_num;
637
0
        }
638
0
    }
639
0
    if (_binlog_compaction_thread_pool->min_threads() != binlog_compaction_threads_num) {
640
0
        int old_min_threads = _binlog_compaction_thread_pool->min_threads();
641
0
        Status status =
642
0
                _binlog_compaction_thread_pool->set_min_threads(binlog_compaction_threads_num);
643
0
        if (status.ok()) {
644
0
            VLOG_NOTICE << "update binlog compaction thread pool min_threads from "
645
0
                        << old_min_threads << " to " << binlog_compaction_threads_num;
646
0
        }
647
0
    }
648
0
}
649
650
7
void StorageEngine::_compaction_tasks_producer_callback() {
651
7
    LOG(INFO) << "try to start compaction producer process!";
652
653
7
    std::vector<DataDir*> data_dirs = get_stores();
654
655
7
    int round = 0;
656
7
    CompactionType compaction_type;
657
658
    // Used to record the time when the score metric was last updated.
659
    // The update of the score metric is accompanied by the logic of selecting the tablet.
660
    // If there is no slot available, the logic of selecting the tablet will be terminated,
661
    // which causes the score metric update to be terminated.
662
    // In order to avoid this situation, we need to update the score regularly.
663
7
    int64_t last_cumulative_score_update_time = 0;
664
7
    int64_t last_base_score_update_time = 0;
665
7
    static const int64_t check_score_interval_ms = 5000; // 5 secs
666
667
7
    int64_t interval = config::generate_compaction_tasks_interval_ms;
668
7
    do {
669
7
        int64_t cur_time = UnixMillis();
670
7
        if (!config::disable_auto_compaction &&
671
7
            (!config::enable_compaction_pause_on_high_memory ||
672
6
             !GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE))) {
673
6
            _adjust_compaction_thread_num();
674
675
6
            bool check_score = false;
676
6
            if (round < config::cumulative_compaction_rounds_for_each_base_compaction_round) {
677
6
                compaction_type = CompactionType::CUMULATIVE_COMPACTION;
678
6
                round++;
679
6
                if (cur_time - last_cumulative_score_update_time >= check_score_interval_ms) {
680
6
                    check_score = true;
681
6
                    last_cumulative_score_update_time = cur_time;
682
6
                }
683
6
            } else {
684
0
                compaction_type = CompactionType::BASE_COMPACTION;
685
0
                round = 0;
686
0
                if (cur_time - last_base_score_update_time >= check_score_interval_ms) {
687
0
                    check_score = true;
688
0
                    last_base_score_update_time = cur_time;
689
0
                }
690
0
            }
691
6
            std::unique_ptr<ThreadPool>& thread_pool =
692
6
                    (compaction_type == CompactionType::CUMULATIVE_COMPACTION)
693
6
                            ? _cumu_compaction_thread_pool
694
6
                            : _base_compaction_thread_pool;
695
6
            bvar::Status<int64_t>& g_compaction_task_num_per_round =
696
6
                    (compaction_type == CompactionType::CUMULATIVE_COMPACTION)
697
6
                            ? g_cumu_compaction_task_num_per_round
698
6
                            : g_base_compaction_task_num_per_round;
699
6
            if (config::compaction_num_per_round != -1) {
700
0
                _compaction_num_per_round = config::compaction_num_per_round;
701
6
            } else if (thread_pool->get_queue_size() == 0) {
702
                // If all tasks in the thread pool queue are executed,
703
                // double the number of tasks generated each time,
704
                // with a maximum of config::max_automatic_compaction_num_per_round tasks per generation.
705
2
                if (_compaction_num_per_round < config::max_automatic_compaction_num_per_round) {
706
1
                    _compaction_num_per_round *= 2;
707
1
                    g_compaction_task_num_per_round.set_value(_compaction_num_per_round);
708
1
                }
709
4
            } else if (thread_pool->get_queue_size() > _compaction_num_per_round / 2) {
710
                // If all tasks in the thread pool is greater than
711
                // half of the tasks submitted in the previous round,
712
                // reduce the number of tasks generated each time by half, with a minimum of 1.
713
3
                if (_compaction_num_per_round > 1) {
714
1
                    _compaction_num_per_round /= 2;
715
1
                    g_compaction_task_num_per_round.set_value(_compaction_num_per_round);
716
1
                }
717
3
            }
718
6
            _update_cumulative_compaction_policy();
719
6
            std::vector<TabletCompactionContext> tablet_compaction_contexts =
720
6
                    _generate_compaction_tasks(compaction_type, data_dirs, check_score);
721
6
            if (tablet_compaction_contexts.empty()) {
722
6
                std::unique_lock<std::mutex> lock(_compaction_producer_sleep_mutex);
723
6
                _wakeup_producer_flag = 0;
724
                // It is necessary to wake up the thread on timeout to prevent deadlock
725
                // in case of no running compaction task.
726
6
                _compaction_producer_sleep_cv.wait_for(
727
6
                        lock, std::chrono::milliseconds(2000),
728
12
                        [this] { return _wakeup_producer_flag == 1; });
729
6
                continue;
730
6
            }
731
732
0
            for (const auto& tablet_compaction_context : tablet_compaction_contexts) {
733
0
                const auto& tablet = tablet_compaction_context.tablet;
734
0
                if (compaction_type == CompactionType::BASE_COMPACTION) {
735
0
                    tablet->set_last_base_compaction_schedule_time(UnixMillis());
736
0
                } else if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
737
0
                    tablet->set_last_cumu_compaction_schedule_time(UnixMillis());
738
0
                } else if (compaction_type == CompactionType::FULL_COMPACTION) {
739
0
                    tablet->set_last_full_compaction_schedule_time(UnixMillis());
740
0
                }
741
0
                Status st = _submit_compaction_task(tablet, compaction_type, false);
742
0
                if (!st.ok()) {
743
0
                    LOG(WARNING) << "failed to submit compaction task for tablet: "
744
0
                                 << tablet->tablet_id() << ", err: " << st;
745
0
                }
746
0
            }
747
0
            interval = config::generate_compaction_tasks_interval_ms;
748
1
        } else {
749
1
            interval = 5000; // 5s to check disable_auto_compaction
750
1
        }
751
752
        // wait some seconds for ut test
753
1
        {
754
1
            std ::vector<std ::any> args {};
755
1
            args.emplace_back(1);
756
1
            doris ::SyncPoint ::get_instance()->process(
757
1
                    "StorageEngine::_compaction_tasks_producer_callback", std ::move(args));
758
1
        }
759
1
        int64_t end_time = UnixMillis();
760
1
        DorisMetrics::instance()->compaction_producer_callback_a_round_time->set_value(end_time -
761
1
                                                                                       cur_time);
762
7
    } while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(interval)));
763
7
}
764
765
0
void StorageEngine::_binlog_compaction_tasks_producer_callback() {
766
0
    LOG(INFO) << "try to start binlog compaction producer process!";
767
768
0
    std::vector<DataDir*> data_dirs = get_stores();
769
770
0
    int64_t last_binlog_score_update_time = 0;
771
0
    static const int64_t check_score_interval_ms = 5000;
772
773
0
    int64_t interval = config::generate_compaction_tasks_interval_ms;
774
0
    do {
775
0
        int64_t cur_time = UnixMillis();
776
0
        if (config::enable_feature_binlog && !config::disable_auto_compaction &&
777
0
            (!config::enable_compaction_pause_on_high_memory ||
778
0
             !GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE))) {
779
0
            _adjust_compaction_thread_num();
780
781
0
            bool check_score = false;
782
0
            if (cur_time - last_binlog_score_update_time >= check_score_interval_ms) {
783
0
                check_score = true;
784
0
                last_binlog_score_update_time = cur_time;
785
0
            }
786
787
0
            std::vector<TabletCompactionContext> tablet_compaction_contexts =
788
0
                    _generate_compaction_tasks(CompactionType::BINLOG_COMPACTION, data_dirs,
789
0
                                               check_score);
790
0
            for (const auto& tablet_compaction_context : tablet_compaction_contexts) {
791
0
                const auto& tablet = tablet_compaction_context.tablet;
792
0
                Status st =
793
0
                        _submit_compaction_task(tablet, CompactionType::BINLOG_COMPACTION, false, 0,
794
0
                                                tablet_compaction_context.prefer_compaction_level);
795
0
                if (!st.ok()) {
796
0
                    LOG(WARNING) << "failed to submit binlog compaction task for tablet: "
797
0
                                 << tablet->tablet_id() << ", err: " << st;
798
0
                }
799
0
            }
800
0
            interval = config::generate_compaction_tasks_interval_ms;
801
0
        } else {
802
0
            interval = 5000;
803
0
        }
804
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(interval)));
805
0
}
806
807
void StorageEngine::get_tablet_rowset_versions(const PGetTabletVersionsRequest* request,
808
0
                                               PGetTabletVersionsResponse* response) {
809
0
    TabletSharedPtr tablet = _tablet_manager->get_tablet(request->tablet_id());
810
0
    if (tablet == nullptr) {
811
0
        response->mutable_status()->set_status_code(TStatusCode::CANCELLED);
812
0
        return;
813
0
    }
814
0
    std::vector<Version> local_versions = tablet->get_all_local_versions();
815
0
    for (const auto& local_version : local_versions) {
816
0
        auto version = response->add_versions();
817
0
        version->set_first(local_version.first);
818
0
        version->set_second(local_version.second);
819
0
    }
820
0
    response->mutable_status()->set_status_code(0);
821
0
}
822
823
bool need_generate_compaction_tasks(int task_cnt_per_disk, int thread_per_disk,
824
9
                                    CompactionType compaction_type, bool all_base) {
825
9
    if (compaction_type == CompactionType::BINLOG_COMPACTION) {
826
0
        return task_cnt_per_disk < thread_per_disk;
827
0
    }
828
829
    // We need to reserve at least one Slot for cumulative compaction.
830
    // So when there is only one Slot, we have to judge whether there is a cumulative compaction
831
    // in the current submitted tasks.
832
    // If so, the last Slot can be assigned to Base compaction,
833
    // otherwise, this Slot needs to be reserved for cumulative compaction.
834
9
    if (task_cnt_per_disk >= thread_per_disk) {
835
        // Return if no available slot
836
2
        return false;
837
7
    } else if (task_cnt_per_disk >= thread_per_disk - 1) {
838
        // Only one slot left, check if it can be assigned to base compaction task.
839
0
        if (compaction_type == CompactionType::BASE_COMPACTION) {
840
0
            if (all_base) {
841
0
                return false;
842
0
            }
843
0
        }
844
0
    }
845
7
    return true;
846
9
}
847
848
4
int get_concurrent_per_disk(int64_t max_score, int thread_per_disk) {
849
4
    if (!config::enable_compaction_priority_scheduling) {
850
1
        return thread_per_disk;
851
1
    }
852
853
3
    double load_average = 0;
854
3
    if (DorisMetrics::instance()->system_metrics() != nullptr) {
855
0
        load_average = DorisMetrics::instance()->system_metrics()->get_load_average_1_min();
856
0
    }
857
3
    int num_cores = doris::CpuInfo::num_cores();
858
3
    bool cpu_usage_high = load_average > num_cores * 0.8;
859
860
3
    auto process_memory_usage = doris::GlobalMemoryArbitrator::process_memory_usage();
861
3
    bool memory_usage_high = static_cast<double>(process_memory_usage) >
862
3
                             static_cast<double>(MemInfo::soft_mem_limit()) * 0.8;
863
864
3
    if (max_score <= config::low_priority_compaction_score_threshold &&
865
3
        (cpu_usage_high || memory_usage_high)) {
866
0
        return config::low_priority_compaction_task_num_per_disk;
867
0
    }
868
869
3
    return thread_per_disk;
870
3
}
871
872
9
int32_t disk_compaction_slot_num(const DataDir& data_dir, CompactionType compaction_type) {
873
9
    if (compaction_type == CompactionType::BINLOG_COMPACTION) {
874
0
        return config::binlog_compaction_task_num_per_disk;
875
0
    }
876
9
    return data_dir.is_ssd_disk() ? config::compaction_task_num_per_fast_disk
877
9
                                  : config::compaction_task_num_per_disk;
878
9
}
879
880
bool has_free_compaction_slot(CompactionSubmitRegistry* registry, DataDir* dir,
881
5
                              CompactionType compaction_type, uint32_t executing_cnt) {
882
5
    int32_t thread_per_disk = disk_compaction_slot_num(*dir, compaction_type);
883
5
    return need_generate_compaction_tasks(
884
5
            executing_cnt, thread_per_disk, compaction_type,
885
5
            !registry->has_compaction_task(dir, CompactionType::CUMULATIVE_COMPACTION));
886
5
}
887
888
std::vector<TabletCompactionContext> StorageEngine::_generate_compaction_tasks(
889
11
        CompactionType compaction_type, std::vector<DataDir*>& data_dirs, bool check_score) {
890
11
    DCHECK(compaction_type == CompactionType::BASE_COMPACTION ||
891
11
           compaction_type == CompactionType::CUMULATIVE_COMPACTION ||
892
11
           compaction_type == CompactionType::BINLOG_COMPACTION);
893
11
    TEST_SYNC_POINT_RETURN_WITH_VALUE("olap_server::_generate_compaction_tasks.return_empty",
894
5
                                      std::vector<TabletCompactionContext> {});
895
5
    _update_cumulative_compaction_policy();
896
5
    auto cumulative_compaction_policies = _snapshot_cumulative_compaction_policy();
897
5
    std::vector<TabletCompactionContext> tablet_compaction_contexts;
898
5
    CompactionScoreStats max_score_stats;
899
5
    bool skipped_capacity_limited_dir = false;
900
901
5
    std::random_device rd;
902
5
    std::mt19937 g(rd());
903
5
    std::shuffle(data_dirs.begin(), data_dirs.end(), g);
904
905
    // Copy _tablet_submitted_xxx_compaction map so that we don't need to hold _tablet_submitted_compaction_mutex
906
    // when traversing the data dir
907
5
    auto compaction_registry_snapshot = _compaction_submit_registry.create_snapshot();
908
5
    for (auto* data_dir : data_dirs) {
909
5
        bool need_pick_tablet = true;
910
5
        uint32_t executing_task_num =
911
5
                compaction_type == CompactionType::BINLOG_COMPACTION
912
5
                        ? compaction_registry_snapshot.count_executing_compaction(
913
0
                                  data_dir, CompactionType::BINLOG_COMPACTION)
914
5
                        : compaction_registry_snapshot.count_executing_cumu_and_base(data_dir);
915
5
        need_pick_tablet = has_free_compaction_slot(&compaction_registry_snapshot, data_dir,
916
5
                                                    compaction_type, executing_task_num);
917
5
        if (!need_pick_tablet && !check_score) {
918
0
            continue;
919
0
        }
920
921
        // Even if need_pick_tablet is false, we still need to call find_best_tablet_to_compaction(),
922
        // So that we can update the max_compaction_score metric.
923
5
        if (data_dir->reach_capacity_limit(0)) {
924
1
            skipped_capacity_limited_dir = true;
925
1
            continue;
926
1
        }
927
928
4
        CompactionScoreStats disk_score_stats;
929
4
        auto tablet_contexts = compaction_registry_snapshot.pick_topn_tablets_for_compaction(
930
4
                _tablet_manager.get(), data_dir, compaction_type, cumulative_compaction_policies,
931
4
                &disk_score_stats);
932
4
        max_score_stats.scanned = max_score_stats.scanned || disk_score_stats.scanned;
933
4
        max_score_stats.max_score = std::max(max_score_stats.max_score, disk_score_stats.max_score);
934
4
        max_score_stats.size_based_max_score = std::max(max_score_stats.size_based_max_score,
935
4
                                                        disk_score_stats.size_based_max_score);
936
4
        max_score_stats.time_series_max_score = std::max(max_score_stats.time_series_max_score,
937
4
                                                         disk_score_stats.time_series_max_score);
938
4
        int concurrent_num = get_concurrent_per_disk(
939
4
                disk_score_stats.max_score, disk_compaction_slot_num(*data_dir, compaction_type));
940
4
        need_pick_tablet = need_generate_compaction_tasks(
941
4
                executing_task_num, concurrent_num, compaction_type,
942
4
                !compaction_registry_snapshot.has_compaction_task(
943
4
                        data_dir, CompactionType::CUMULATIVE_COMPACTION));
944
4
        for (const auto& context : tablet_contexts) {
945
4
            if (context.tablet != nullptr) {
946
4
                if (need_pick_tablet) {
947
3
                    tablet_compaction_contexts.emplace_back(context);
948
3
                }
949
4
            }
950
4
        }
951
4
    }
952
953
5
    if (max_score_stats.scanned) {
954
4
        if (compaction_type == CompactionType::BASE_COMPACTION && max_score_stats.max_score > 0) {
955
0
            DorisMetrics::instance()->tablet_base_max_compaction_score->set_value(
956
0
                    max_score_stats.max_score);
957
4
        } else if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
958
4
            auto update_policy_score = [skipped_capacity_limited_dir, check_score](IntGauge* metric,
959
8
                                                                                   int64_t score) {
960
8
                if (skipped_capacity_limited_dir) {
961
2
                    if (score > metric->value()) {
962
1
                        metric->set_value(score);
963
1
                    }
964
6
                } else if (check_score || score > 0) {
965
5
                    metric->set_value(score);
966
5
                }
967
8
            };
968
4
            update_policy_score(DorisMetrics::instance()->tablet_cumulative_max_compaction_score,
969
4
                                max_score_stats.size_based_max_score);
970
4
            update_policy_score(DorisMetrics::instance()->tablet_time_series_max_compaction_score,
971
4
                                max_score_stats.time_series_max_score);
972
4
        } else if (compaction_type == CompactionType::BINLOG_COMPACTION &&
973
0
                   max_score_stats.max_score > 0) {
974
0
            DorisMetrics::instance()->tablet_binlog_max_compaction_score->set_value(
975
0
                    max_score_stats.max_score);
976
0
        }
977
4
    }
978
5
    return tablet_compaction_contexts;
979
11
}
980
981
11
void StorageEngine::_update_cumulative_compaction_policy() {
982
11
    std::lock_guard<std::mutex> lock(_cumulative_compaction_policy_mtx);
983
11
    if (_cumulative_compaction_policies.empty()) {
984
7
        _cumulative_compaction_policies[CUMULATIVE_SIZE_BASED_POLICY] =
985
7
                CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
986
7
                        CUMULATIVE_SIZE_BASED_POLICY);
987
7
        _cumulative_compaction_policies[CUMULATIVE_TIME_SERIES_POLICY] =
988
7
                CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
989
7
                        CUMULATIVE_TIME_SERIES_POLICY);
990
7
    }
991
11
}
992
993
5
CumuCompactionPolicyTable StorageEngine::_snapshot_cumulative_compaction_policy() {
994
5
    std::lock_guard<std::mutex> lock(_cumulative_compaction_policy_mtx);
995
5
    return _cumulative_compaction_policies;
996
5
}
997
998
std::shared_ptr<CumulativeCompactionPolicy> StorageEngine::_get_cumulative_compaction_policy(
999
0
        std::string_view compaction_policy) {
1000
0
    std::lock_guard<std::mutex> lock(_cumulative_compaction_policy_mtx);
1001
0
    return _cumulative_compaction_policies.at(compaction_policy);
1002
0
}
1003
1004
void StorageEngine::_pop_tablet_from_submitted_compaction(TabletSharedPtr tablet,
1005
7
                                                          CompactionType compaction_type) {
1006
7
    _compaction_submit_registry.remove(tablet, compaction_type, [this]() {
1007
7
        std::unique_lock<std::mutex> lock(_compaction_producer_sleep_mutex);
1008
7
        _wakeup_producer_flag = 1;
1009
7
        _compaction_producer_sleep_cv.notify_one();
1010
7
    });
1011
7
}
1012
1013
Status StorageEngine::_submit_compaction_task(TabletSharedPtr tablet,
1014
                                              CompactionType compaction_type, bool force,
1015
21
                                              int trigger_method, int8_t prefer_compaction_level) {
1016
21
    bool already_exist = _compaction_submit_registry.insert(tablet, compaction_type);
1017
21
    if (already_exist) {
1018
0
        return Status::AlreadyExist<false>(
1019
0
                "compaction task has already been submitted, tablet_id={}, compaction_type={}.",
1020
0
                tablet->tablet_id(), compaction_type);
1021
0
    }
1022
21
    tablet->compaction_stage = CompactionStage::PENDING;
1023
21
    std::shared_ptr<CompactionMixin> compaction;
1024
21
    int64_t permits = 0;
1025
21
    Status st = Tablet::prepare_compaction_and_calculate_permits(
1026
21
            compaction_type, tablet, compaction, permits, prefer_compaction_level);
1027
21
    if (st.ok() && permits > 0) {
1028
21
        if (!force) {
1029
21
            if (compaction_type == CompactionType::BINLOG_COMPACTION) {
1030
0
                if (!_permit_limiter.try_request(permits, compaction_type)) {
1031
0
                    _pop_tablet_from_submitted_compaction(tablet, compaction_type);
1032
0
                    tablet->compaction_stage = CompactionStage::NOT_SCHEDULED;
1033
0
                    return Status::OK();
1034
0
                }
1035
21
            } else {
1036
21
                _permit_limiter.request(permits);
1037
21
            }
1038
21
        }
1039
        // Register task with CompactionTaskTracker as PENDING
1040
21
        auto* tracker = CompactionTaskTracker::instance();
1041
21
        int64_t compaction_id = compaction->compaction_id();
1042
21
        {
1043
21
            CompactionTaskInfo info;
1044
21
            info.compaction_id = compaction_id;
1045
21
            info.tablet_id = tablet->tablet_id();
1046
21
            info.table_id = tablet->get_table_id();
1047
21
            info.partition_id = tablet->partition_id();
1048
21
            switch (compaction_type) {
1049
0
            case CompactionType::BASE_COMPACTION:
1050
0
                info.compaction_type = CompactionProfileType::BASE;
1051
0
                break;
1052
21
            case CompactionType::CUMULATIVE_COMPACTION:
1053
21
                info.compaction_type = CompactionProfileType::CUMULATIVE;
1054
21
                break;
1055
0
            case CompactionType::FULL_COMPACTION:
1056
0
                info.compaction_type = CompactionProfileType::FULL;
1057
0
                break;
1058
0
            case CompactionType::BINLOG_COMPACTION:
1059
0
                info.compaction_type = CompactionProfileType::BINLOG;
1060
0
                break;
1061
0
            default:
1062
0
                DCHECK(false) << "invalid compaction type: " << compaction_type;
1063
21
            }
1064
21
            info.status = CompactionTaskStatus::PENDING;
1065
21
            info.trigger_method = static_cast<TriggerMethod>(trigger_method);
1066
21
            info.scheduled_time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1067
21
                                             std::chrono::system_clock::now().time_since_epoch())
1068
21
                                             .count();
1069
21
            info.permits = permits;
1070
21
            info.backend_id = BackendOptions::get_backend_id();
1071
21
            info.compaction_score = tablet->get_real_compaction_score();
1072
21
            info.input_rowsets_count = compaction->input_rowsets_count();
1073
21
            info.input_row_num = compaction->input_row_num_value();
1074
21
            info.input_data_size = compaction->input_rowsets_data_size();
1075
21
            info.input_index_size = compaction->input_rowsets_index_size();
1076
21
            info.input_total_size = compaction->input_rowsets_total_size();
1077
21
            info.input_segments_num = compaction->input_segments_num_value();
1078
21
            info.input_version_range = compaction->input_version_range_str();
1079
21
            info.is_vertical = compaction->is_vertical();
1080
21
            tracker->register_task(std::move(info));
1081
21
        }
1082
0
        std::unique_ptr<ThreadPool>* thread_pool = nullptr;
1083
21
        const char* compaction_type_name = "UNKNOWN";
1084
21
        switch (compaction_type) {
1085
21
        case CompactionType::CUMULATIVE_COMPACTION:
1086
21
            thread_pool = &_cumu_compaction_thread_pool;
1087
21
            compaction_type_name = "CUMU";
1088
21
            break;
1089
0
        case CompactionType::BINLOG_COMPACTION:
1090
0
            thread_pool = &_binlog_compaction_thread_pool;
1091
0
            compaction_type_name = "BINLOG";
1092
0
            break;
1093
0
        case CompactionType::BASE_COMPACTION:
1094
0
        case CompactionType::FULL_COMPACTION:
1095
0
            thread_pool = &_base_compaction_thread_pool;
1096
0
            compaction_type_name = "BASE";
1097
0
            break;
1098
0
        default:
1099
0
            DCHECK(false) << "invalid compaction type: " << compaction_type;
1100
21
        }
1101
21
        VLOG_CRITICAL << "compaction thread pool. type: " << compaction_type_name
1102
0
                      << ", num_threads: " << thread_pool->get()->num_threads()
1103
0
                      << ", num_threads_pending_start: "
1104
0
                      << thread_pool->get()->num_threads_pending_start()
1105
0
                      << ", num_active_threads: " << thread_pool->get()->num_active_threads()
1106
0
                      << ", max_threads: " << thread_pool->get()->max_threads()
1107
0
                      << ", min_threads: " << thread_pool->get()->min_threads()
1108
0
                      << ", num_total_queued_tasks: " << thread_pool->get()->get_queue_size();
1109
21
        auto status =
1110
21
                thread_pool->get()->submit_func([=, compaction = std::move(compaction), this]() {
1111
7
                    _handle_compaction(std::move(tablet), std::move(compaction), compaction_type,
1112
7
                                       permits, force, compaction_id);
1113
7
                });
1114
21
        if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) [[likely]] {
1115
21
            DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
1116
21
                    _cumu_compaction_thread_pool->get_queue_size());
1117
21
        } else if (compaction_type == CompactionType::BASE_COMPACTION) {
1118
0
            DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
1119
0
                    _base_compaction_thread_pool->get_queue_size());
1120
0
        }
1121
21
        if (!status.ok()) {
1122
            // Cleanup tracker on submit failure
1123
0
            tracker->remove_task(compaction_id);
1124
0
            if (!force) {
1125
0
                _permit_limiter.release(permits, compaction_type);
1126
0
            }
1127
0
            _pop_tablet_from_submitted_compaction(tablet, compaction_type);
1128
0
            tablet->compaction_stage = CompactionStage::NOT_SCHEDULED;
1129
0
            return Status::InternalError(
1130
0
                    "failed to submit compaction task to thread pool, "
1131
0
                    "tablet_id={}, compaction_type={}.",
1132
0
                    tablet->tablet_id(), compaction_type);
1133
0
        }
1134
21
        return Status::OK();
1135
21
    } else {
1136
0
        _pop_tablet_from_submitted_compaction(tablet, compaction_type);
1137
0
        tablet->compaction_stage = CompactionStage::NOT_SCHEDULED;
1138
0
        if (!st.ok()) {
1139
0
            return Status::InternalError(
1140
0
                    "failed to prepare compaction task and calculate permits, "
1141
0
                    "tablet_id={}, compaction_type={}, "
1142
0
                    "permit={}, current_permit={}, status={}",
1143
0
                    tablet->tablet_id(), compaction_type, permits, _permit_limiter.usage(),
1144
0
                    st.to_string());
1145
0
        }
1146
0
        return st;
1147
0
    }
1148
21
}
1149
1150
void StorageEngine::_handle_compaction(TabletSharedPtr tablet,
1151
                                       std::shared_ptr<CompactionMixin> compaction,
1152
                                       CompactionType compaction_type, int64_t permits, bool force,
1153
7
                                       int64_t compaction_id) {
1154
7
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) [[likely]] {
1155
7
        DorisMetrics::instance()->cumulative_compaction_task_running_total->increment(1);
1156
7
        DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
1157
7
                _cumu_compaction_thread_pool->get_queue_size());
1158
7
    } else if (compaction_type == CompactionType::BASE_COMPACTION) {
1159
0
        DorisMetrics::instance()->base_compaction_task_running_total->increment(1);
1160
0
        DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
1161
0
                _base_compaction_thread_pool->get_queue_size());
1162
0
    } else if (compaction_type == CompactionType::BINLOG_COMPACTION) {
1163
0
        DorisMetrics::instance()->binlog_compaction_task_running_total->increment(1);
1164
0
        DorisMetrics::instance()->binlog_compaction_task_pending_total->set_value(
1165
0
                _binlog_compaction_thread_pool->get_queue_size());
1166
0
    }
1167
7
    bool is_large_task = true;
1168
7
    Defer defer {[&]() {
1169
7
        DBUG_EXECUTE_IF("StorageEngine._submit_compaction_task.sleep", { sleep(5); })
1170
        // Idempotent cleanup: remove task from tracker
1171
7
        CompactionTaskTracker::instance()->remove_task(compaction_id);
1172
7
        if (!force) {
1173
7
            _permit_limiter.release(permits, compaction_type);
1174
7
        }
1175
7
        _pop_tablet_from_submitted_compaction(tablet, compaction_type);
1176
7
        tablet->compaction_stage = CompactionStage::NOT_SCHEDULED;
1177
7
        if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
1178
7
            std::lock_guard<std::mutex> lock(_cumu_compaction_delay_mtx);
1179
7
            _cumu_compaction_thread_pool_used_threads--;
1180
7
            if (!is_large_task) {
1181
0
                _cumu_compaction_thread_pool_small_tasks_running--;
1182
0
            }
1183
7
            DorisMetrics::instance()->cumulative_compaction_task_running_total->increment(-1);
1184
7
            DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
1185
7
                    _cumu_compaction_thread_pool->get_queue_size());
1186
7
        } else if (compaction_type == CompactionType::BASE_COMPACTION) {
1187
0
            DorisMetrics::instance()->base_compaction_task_running_total->increment(-1);
1188
0
            DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
1189
0
                    _base_compaction_thread_pool->get_queue_size());
1190
0
        } else if (compaction_type == CompactionType::BINLOG_COMPACTION) {
1191
0
            DorisMetrics::instance()->binlog_compaction_task_running_total->increment(-1);
1192
0
            DorisMetrics::instance()->binlog_compaction_task_pending_total->set_value(
1193
0
                    _binlog_compaction_thread_pool->get_queue_size());
1194
0
        }
1195
7
    }};
1196
7
    do {
1197
7
        if (compaction->compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1198
7
            std::lock_guard<std::mutex> lock(_cumu_compaction_delay_mtx);
1199
7
            _cumu_compaction_thread_pool_used_threads++;
1200
7
            if (config::large_cumu_compaction_task_min_thread_num > 1 &&
1201
7
                _cumu_compaction_thread_pool->max_threads() >=
1202
0
                        config::large_cumu_compaction_task_min_thread_num) {
1203
                // Determine if this is a large task based on configured thresholds
1204
0
                is_large_task = (compaction->calc_input_rowsets_total_size() >
1205
0
                                         config::large_cumu_compaction_task_bytes_threshold ||
1206
0
                                 compaction->calc_input_rowsets_row_num() >
1207
0
                                         config::large_cumu_compaction_task_row_num_threshold);
1208
1209
                // Small task. No delay needed
1210
0
                if (!is_large_task) {
1211
0
                    _cumu_compaction_thread_pool_small_tasks_running++;
1212
0
                    break;
1213
0
                }
1214
                // Deal with large task
1215
0
                if (_should_delay_large_task()) {
1216
0
                    LOG_WARNING(
1217
0
                            "failed to do CumulativeCompaction, cumu thread pool is "
1218
0
                            "intensive, delay large task.")
1219
0
                            .tag("tablet_id", tablet->tablet_id())
1220
0
                            .tag("input_rows", compaction->calc_input_rowsets_row_num())
1221
0
                            .tag("input_rowsets_total_size",
1222
0
                                 compaction->calc_input_rowsets_total_size())
1223
0
                            .tag("config::large_cumu_compaction_task_bytes_threshold",
1224
0
                                 config::large_cumu_compaction_task_bytes_threshold)
1225
0
                            .tag("config::large_cumu_compaction_task_row_num_threshold",
1226
0
                                 config::large_cumu_compaction_task_row_num_threshold)
1227
0
                            .tag("remaining threads", _cumu_compaction_thread_pool_used_threads)
1228
0
                            .tag("small_tasks_running",
1229
0
                                 _cumu_compaction_thread_pool_small_tasks_running);
1230
                    // Delay this task and sleep 5s for this tablet
1231
0
                    long now = duration_cast<std::chrono::milliseconds>(
1232
0
                                       std::chrono::system_clock::now().time_since_epoch())
1233
0
                                       .count();
1234
0
                    tablet->set_last_cumu_compaction_failure_time(now);
1235
0
                    return;
1236
0
                }
1237
0
            }
1238
7
        }
1239
7
    } while (false);
1240
7
    if (!tablet->can_do_compaction(tablet->data_dir()->path_hash(), compaction_type)) {
1241
0
        LOG(INFO) << "Tablet state has been changed, no need to begin this compaction "
1242
0
                     "task, tablet_id="
1243
0
                  << tablet->tablet_id() << ", tablet_state=" << tablet->tablet_state();
1244
0
        return;
1245
0
    }
1246
7
    tablet->compaction_stage = CompactionStage::EXECUTING;
1247
    // Update tracker to RUNNING
1248
7
    {
1249
7
        RunningStats rs;
1250
7
        rs.start_time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1251
7
                                   std::chrono::system_clock::now().time_since_epoch())
1252
7
                                   .count();
1253
7
        rs.permits = permits;
1254
7
        CompactionTaskTracker::instance()->update_to_running(compaction_id, rs);
1255
7
    }
1256
7
    TEST_SYNC_POINT_RETURN_WITH_VOID("olap_server::execute_compaction");
1257
1
    tablet->execute_compaction(*compaction);
1258
1
}
1259
1260
Status StorageEngine::submit_compaction_task(TabletSharedPtr tablet, CompactionType compaction_type,
1261
0
                                             bool force, bool eager, int trigger_method) {
1262
0
    if (!eager) {
1263
0
        DCHECK(compaction_type == CompactionType::BASE_COMPACTION ||
1264
0
               compaction_type == CompactionType::CUMULATIVE_COMPACTION);
1265
0
        auto compaction_registry_snapshot = _compaction_submit_registry.create_snapshot();
1266
0
        auto stores = get_stores();
1267
1268
0
        bool is_busy = std::none_of(
1269
0
                stores.begin(), stores.end(),
1270
0
                [&compaction_registry_snapshot, compaction_type](auto* data_dir) {
1271
0
                    return has_free_compaction_slot(
1272
0
                            &compaction_registry_snapshot, data_dir, compaction_type,
1273
0
                            compaction_registry_snapshot.count_executing_cumu_and_base(data_dir));
1274
0
                });
1275
0
        if (is_busy) {
1276
0
            LOG_EVERY_N(WARNING, 100)
1277
0
                    << "Too busy to submit a compaction task, tablet=" << tablet->get_table_id();
1278
0
            return Status::OK();
1279
0
        }
1280
0
    }
1281
0
    _update_cumulative_compaction_policy();
1282
    // alter table tableName set ("compaction_policy"="time_series")
1283
    // if atler table's compaction  policy, we need to modify tablet compaction policy shared ptr
1284
0
    if (tablet->get_cumulative_compaction_policy() == nullptr ||
1285
0
        tablet->get_cumulative_compaction_policy()->name() !=
1286
0
                tablet->tablet_meta()->compaction_policy()) {
1287
0
        tablet->set_cumulative_compaction_policy(
1288
0
                _get_cumulative_compaction_policy(tablet->tablet_meta()->compaction_policy()));
1289
0
    }
1290
0
    tablet->set_skip_compaction(false);
1291
0
    int8_t prefer_compaction_level = -1;
1292
0
    if (compaction_type == CompactionType::BINLOG_COMPACTION) {
1293
0
        tablet->calc_compaction_score(compaction_type, &prefer_compaction_level);
1294
0
        if (prefer_compaction_level < 0) {
1295
0
            return Status::Error<ErrorCode::BINLOG_COMPACTION_NO_SUITABLE_VERSION>(
1296
0
                    "failed to init binlog compaction due to no suitable version");
1297
0
        }
1298
0
    }
1299
0
    return _submit_compaction_task(tablet, compaction_type, force, trigger_method,
1300
0
                                   prefer_compaction_level);
1301
0
}
1302
1303
Status StorageEngine::_handle_seg_compaction(std::shared_ptr<SegcompactionWorker> worker,
1304
                                             SegCompactionCandidatesSharedPtr segments,
1305
11
                                             uint64_t submission_time) {
1306
    // note: be aware that worker->_writer maybe released when the task is cancelled
1307
11
    uint64_t exec_queue_time = GetCurrentTimeMicros() - submission_time;
1308
11
    LOG(INFO) << "segcompaction thread pool queue time(ms): " << exec_queue_time / 1000;
1309
11
    worker->compact_segments(segments);
1310
    // return OK here. error will be reported via BetaRowsetWriter::_segcompaction_status
1311
11
    return Status::OK();
1312
11
}
1313
1314
Status StorageEngine::submit_seg_compaction_task(std::shared_ptr<SegcompactionWorker> worker,
1315
11
                                                 SegCompactionCandidatesSharedPtr segments) {
1316
11
    uint64_t submission_time = GetCurrentTimeMicros();
1317
11
    return _seg_compaction_thread_pool->submit_func([this, worker, segments, submission_time] {
1318
11
        static_cast<void>(_handle_seg_compaction(worker, segments, submission_time));
1319
11
    });
1320
11
}
1321
1322
0
Status StorageEngine::process_index_change_task(const TAlterInvertedIndexReq& request) {
1323
0
    auto tablet_id = request.tablet_id;
1324
0
    TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1325
0
    DBUG_EXECUTE_IF("StorageEngine::process_index_change_task_tablet_nullptr",
1326
0
                    { tablet = nullptr; })
1327
0
    if (tablet == nullptr) {
1328
0
        LOG(WARNING) << "tablet: " << tablet_id << " not exist";
1329
0
        return Status::InternalError("tablet not exist, tablet_id={}.", tablet_id);
1330
0
    }
1331
1332
0
    IndexBuilderSharedPtr index_builder = std::make_shared<IndexBuilder>(
1333
0
            *this, tablet, request.columns, request.alter_inverted_indexes, request.is_drop_op);
1334
0
    RETURN_IF_ERROR(_handle_index_change(index_builder));
1335
0
    return Status::OK();
1336
0
}
1337
1338
0
Status StorageEngine::_handle_index_change(IndexBuilderSharedPtr index_builder) {
1339
0
    RETURN_IF_ERROR(index_builder->init());
1340
0
    RETURN_IF_ERROR(index_builder->do_build_inverted_index());
1341
0
    return Status::OK();
1342
0
}
1343
1344
0
void StorageEngine::_cooldown_tasks_producer_callback() {
1345
0
    int64_t interval = config::generate_cooldown_task_interval_sec;
1346
    // the cooldown replica may be slow to upload it's meta file, so we should wait
1347
    // until it has done uploaded
1348
0
    int64_t skip_failed_interval = interval * 10;
1349
0
    do {
1350
        // these tables are ordered by priority desc
1351
0
        std::vector<TabletSharedPtr> tablets;
1352
0
        std::vector<RowsetSharedPtr> rowsets;
1353
        // TODO(luwei) : a more efficient way to get cooldown tablets
1354
0
        auto cur_time = time(nullptr);
1355
        // we should skip all the tablets which are not running and those pending to do cooldown
1356
        // also tablets once failed to do follow cooldown
1357
0
        auto skip_tablet = [this, skip_failed_interval,
1358
0
                            cur_time](const TabletSharedPtr& tablet) -> bool {
1359
0
            bool is_skip =
1360
0
                    cur_time - tablet->last_failed_follow_cooldown_time() < skip_failed_interval ||
1361
0
                    TABLET_RUNNING != tablet->tablet_state();
1362
0
            if (is_skip) {
1363
0
                return is_skip;
1364
0
            }
1365
0
            std::lock_guard<std::mutex> lock(_running_cooldown_mutex);
1366
0
            return _running_cooldown_tablets.find(tablet->tablet_id()) !=
1367
0
                   _running_cooldown_tablets.end();
1368
0
        };
1369
0
        _tablet_manager->get_cooldown_tablets(&tablets, &rowsets, std::move(skip_tablet));
1370
0
        LOG(INFO) << "cooldown producer get tablet num: " << tablets.size();
1371
0
        int max_priority = cast_set<int>(tablets.size());
1372
0
        int index = 0;
1373
0
        for (const auto& tablet : tablets) {
1374
0
            {
1375
0
                std::lock_guard<std::mutex> lock(_running_cooldown_mutex);
1376
0
                _running_cooldown_tablets.insert(tablet->tablet_id());
1377
0
            }
1378
0
            PriorityThreadPool::Task task;
1379
0
            RowsetSharedPtr rowset = std::move(rowsets[index++]);
1380
0
            task.work_function = [tablet, rowset, task_size = tablets.size(), this]() {
1381
0
                Status st = tablet->cooldown(rowset);
1382
0
                {
1383
0
                    std::lock_guard<std::mutex> lock(_running_cooldown_mutex);
1384
0
                    _running_cooldown_tablets.erase(tablet->tablet_id());
1385
0
                }
1386
0
                if (!st.ok()) {
1387
0
                    LOG(WARNING) << "failed to cooldown, tablet: " << tablet->tablet_id()
1388
0
                                 << " err: " << st;
1389
0
                } else {
1390
0
                    LOG(INFO) << "succeed to cooldown, tablet: " << tablet->tablet_id()
1391
0
                              << " cooldown progress ("
1392
0
                              << task_size - _cooldown_thread_pool->get_queue_size() << "/"
1393
0
                              << task_size << ")";
1394
0
                }
1395
0
            };
1396
0
            task.priority = max_priority--;
1397
0
            bool submited = _cooldown_thread_pool->offer(std::move(task));
1398
1399
0
            if (!submited) {
1400
0
                LOG(INFO) << "failed to submit cooldown task";
1401
0
            }
1402
0
        }
1403
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
1404
0
}
1405
1406
0
void StorageEngine::_remove_unused_remote_files_callback() {
1407
0
    while (!_stop_background_threads_latch.wait_for(
1408
0
            std::chrono::seconds(config::remove_unused_remote_files_interval_sec))) {
1409
0
        LOG(INFO) << "begin to remove unused remote files";
1410
0
        do_remove_unused_remote_files();
1411
0
    }
1412
0
}
1413
1414
static void collect_tablet_unused_remote_files(
1415
        Tablet* t, TConfirmUnusedRemoteFilesRequest& req,
1416
        std::unordered_map<int64_t, std::pair<StorageResource, std::vector<io::FileInfo>>>& buffer,
1417
0
        int64_t& num_files_in_buffer, PendingRowsetSet& pending_remote_rowsets) {
1418
0
    auto storage_resource = get_resource_by_storage_policy_id(t->storage_policy_id());
1419
0
    if (!storage_resource) {
1420
0
        LOG(WARNING) << "encounter error when remove unused remote files, tablet_id="
1421
0
                     << t->tablet_id() << " : " << storage_resource.error();
1422
0
        return;
1423
0
    }
1424
1425
    // TODO(plat1ko): Support path v1
1426
0
    if (storage_resource->path_version > 0) {
1427
0
        return;
1428
0
    }
1429
1430
0
    std::vector<io::FileInfo> files;
1431
    // FIXME(plat1ko): What if user reset resource in storage policy to another resource?
1432
    //  Maybe we should also list files in previously uploaded resources.
1433
0
    bool exists = true;
1434
0
    auto st = storage_resource->fs->list(storage_resource->remote_tablet_path(t->tablet_id()), true,
1435
0
                                         &files, &exists);
1436
0
    if (!st.ok()) {
1437
0
        LOG(WARNING) << "encounter error when remove unused remote files, tablet_id="
1438
0
                     << t->tablet_id() << " : " << st;
1439
0
        return;
1440
0
    }
1441
0
    if (!exists || files.empty()) {
1442
0
        return;
1443
0
    }
1444
    // get all cooldowned rowsets
1445
0
    RowsetIdUnorderedSet cooldowned_rowsets;
1446
0
    UniqueId cooldown_meta_id;
1447
0
    {
1448
0
        std::shared_lock rlock(t->get_header_lock());
1449
0
        for (const auto& [_, rs_meta] : t->tablet_meta()->all_rs_metas()) {
1450
0
            if (!rs_meta->is_local()) {
1451
0
                cooldowned_rowsets.insert(rs_meta->rowset_id());
1452
0
            }
1453
0
        }
1454
0
        if (cooldowned_rowsets.empty()) {
1455
0
            return;
1456
0
        }
1457
0
        cooldown_meta_id = t->tablet_meta()->cooldown_meta_id();
1458
0
    }
1459
0
    auto [cooldown_term, cooldown_replica_id] = t->cooldown_conf();
1460
0
    if (cooldown_replica_id != t->replica_id()) {
1461
0
        return;
1462
0
    }
1463
    // {cooldown_replica_id}.{cooldown_term}.meta
1464
0
    std::string remote_meta_path =
1465
0
            cooldown_tablet_meta_filename(cooldown_replica_id, cooldown_term);
1466
    // filter out the paths that should be reserved
1467
0
    auto filter = [&](io::FileInfo& info) {
1468
0
        std::string_view filename = info.file_name;
1469
0
        if (filename.ends_with(".meta")) {
1470
0
            return filename == remote_meta_path;
1471
0
        }
1472
0
        auto rowset_id = extract_rowset_id(filename);
1473
0
        if (rowset_id.hi == 0) {
1474
0
            return false;
1475
0
        }
1476
0
        return cooldowned_rowsets.contains(rowset_id) || pending_remote_rowsets.contains(rowset_id);
1477
0
    };
1478
0
    files.erase(std::remove_if(files.begin(), files.end(), std::move(filter)), files.end());
1479
0
    if (files.empty()) {
1480
0
        return;
1481
0
    }
1482
0
    files.shrink_to_fit();
1483
0
    num_files_in_buffer += files.size();
1484
0
    buffer.insert({t->tablet_id(), {*storage_resource, std::move(files)}});
1485
0
    auto& info = req.confirm_list.emplace_back();
1486
0
    info.__set_tablet_id(t->tablet_id());
1487
0
    info.__set_cooldown_replica_id(cooldown_replica_id);
1488
0
    info.__set_cooldown_meta_id(cooldown_meta_id.to_thrift());
1489
0
}
1490
1491
static void confirm_and_remove_unused_remote_files(
1492
        const TConfirmUnusedRemoteFilesRequest& req,
1493
        std::unordered_map<int64_t, std::pair<StorageResource, std::vector<io::FileInfo>>>& buffer,
1494
0
        const int64_t num_files_in_buffer) {
1495
0
    TConfirmUnusedRemoteFilesResult result;
1496
0
    LOG(INFO) << "begin to confirm unused remote files. num_tablets=" << buffer.size()
1497
0
              << " num_files=" << num_files_in_buffer;
1498
0
    auto st = MasterServerClient::instance()->confirm_unused_remote_files(req, &result);
1499
0
    if (!st.ok()) {
1500
0
        LOG(WARNING) << st;
1501
0
        return;
1502
0
    }
1503
0
    for (auto id : result.confirmed_tablets) {
1504
0
        if (auto it = buffer.find(id); LIKELY(it != buffer.end())) {
1505
0
            auto& storage_resource = it->second.first;
1506
0
            auto& files = it->second.second;
1507
0
            std::vector<io::Path> paths;
1508
0
            paths.reserve(files.size());
1509
            // delete unused files
1510
0
            LOG(INFO) << "delete unused files. root_path=" << storage_resource.fs->root_path()
1511
0
                      << " tablet_id=" << id;
1512
0
            io::Path dir = storage_resource.remote_tablet_path(id);
1513
0
            for (auto& file : files) {
1514
0
                auto file_path = dir / file.file_name;
1515
0
                LOG(INFO) << "delete unused file: " << file_path.native();
1516
0
                paths.push_back(std::move(file_path));
1517
0
            }
1518
0
            st = storage_resource.fs->batch_delete(paths);
1519
0
            if (!st.ok()) {
1520
0
                LOG(WARNING) << "failed to delete unused files, tablet_id=" << id << " : " << st;
1521
0
            }
1522
0
            buffer.erase(it);
1523
0
        }
1524
0
    }
1525
0
}
1526
1527
0
void StorageEngine::do_remove_unused_remote_files() {
1528
0
    auto tablets = tablet_manager()->get_all_tablet([](Tablet* t) {
1529
0
        return t->tablet_meta()->cooldown_meta_id().initialized() && t->is_used() &&
1530
0
               t->tablet_state() == TABLET_RUNNING &&
1531
0
               t->cooldown_conf_unlocked().cooldown_replica_id == t->replica_id();
1532
0
    });
1533
0
    TConfirmUnusedRemoteFilesRequest req;
1534
0
    req.__isset.confirm_list = true;
1535
    // tablet_id -> [storage_resource, unused_remote_files]
1536
0
    using unused_remote_files_buffer_t =
1537
0
            std::unordered_map<int64_t, std::pair<StorageResource, std::vector<io::FileInfo>>>;
1538
0
    unused_remote_files_buffer_t buffer;
1539
0
    int64_t num_files_in_buffer = 0;
1540
    // assume a filename is 0.1KB, buffer size should not larger than 100MB
1541
0
    constexpr int64_t max_files_in_buffer = 1000000;
1542
1543
    // batch confirm to reduce FE's overhead
1544
0
    auto next_confirm_time = std::chrono::steady_clock::now() +
1545
0
                             std::chrono::seconds(config::confirm_unused_remote_files_interval_sec);
1546
0
    for (auto& t : tablets) {
1547
0
        if (t.use_count() <= 1 // this means tablet has been dropped
1548
0
            || t->cooldown_conf_unlocked().cooldown_replica_id != t->replica_id() ||
1549
0
            t->tablet_state() != TABLET_RUNNING) {
1550
0
            continue;
1551
0
        }
1552
0
        collect_tablet_unused_remote_files(t.get(), req, buffer, num_files_in_buffer,
1553
0
                                           _pending_remote_rowsets);
1554
0
        if (num_files_in_buffer > 0 && (num_files_in_buffer > max_files_in_buffer ||
1555
0
                                        std::chrono::steady_clock::now() > next_confirm_time)) {
1556
0
            confirm_and_remove_unused_remote_files(req, buffer, num_files_in_buffer);
1557
0
            buffer.clear();
1558
0
            req.confirm_list.clear();
1559
0
            num_files_in_buffer = 0;
1560
0
            next_confirm_time =
1561
0
                    std::chrono::steady_clock::now() +
1562
0
                    std::chrono::seconds(config::confirm_unused_remote_files_interval_sec);
1563
0
        }
1564
0
    }
1565
0
    if (num_files_in_buffer > 0) {
1566
0
        confirm_and_remove_unused_remote_files(req, buffer, num_files_in_buffer);
1567
0
    }
1568
0
}
1569
1570
0
void StorageEngine::_cold_data_compaction_producer_callback() {
1571
0
    while (!_stop_background_threads_latch.wait_for(
1572
0
            std::chrono::seconds(config::cold_data_compaction_interval_sec))) {
1573
0
        if (config::disable_auto_compaction ||
1574
0
            GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE)) {
1575
0
            continue;
1576
0
        }
1577
1578
0
        std::unordered_set<int64_t> copied_tablet_submitted;
1579
0
        {
1580
0
            std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1581
0
            copied_tablet_submitted = _cold_compaction_tablet_submitted;
1582
0
        }
1583
0
        int64_t n = config::cold_data_compaction_thread_num - copied_tablet_submitted.size();
1584
0
        if (n <= 0) {
1585
0
            continue;
1586
0
        }
1587
0
        auto tablets = _tablet_manager->get_all_tablet([&copied_tablet_submitted](Tablet* t) {
1588
0
            return t->tablet_meta()->cooldown_meta_id().initialized() && t->is_used() &&
1589
0
                   t->tablet_state() == TABLET_RUNNING &&
1590
0
                   !copied_tablet_submitted.contains(t->tablet_id()) &&
1591
0
                   !t->tablet_meta()->tablet_schema()->disable_auto_compaction();
1592
0
        });
1593
0
        std::vector<std::pair<TabletSharedPtr, int64_t>> tablet_to_compact;
1594
0
        tablet_to_compact.reserve(n + 1);
1595
0
        std::vector<std::pair<TabletSharedPtr, int64_t>> tablet_to_follow;
1596
0
        tablet_to_follow.reserve(n + 1);
1597
1598
0
        for (auto& t : tablets) {
1599
0
            if (t->replica_id() == t->cooldown_conf_unlocked().cooldown_replica_id) {
1600
0
                auto score = t->calc_cold_data_compaction_score();
1601
0
                if (score < config::cold_data_compaction_score_threshold) {
1602
0
                    continue;
1603
0
                }
1604
0
                tablet_to_compact.emplace_back(t, score);
1605
0
                if (tablet_to_compact.size() > n) {
1606
0
                    std::sort(tablet_to_compact.begin(), tablet_to_compact.end(),
1607
0
                              [](auto& a, auto& b) { return a.second > b.second; });
1608
0
                    tablet_to_compact.pop_back();
1609
0
                }
1610
0
                continue;
1611
0
            }
1612
            // else, need to follow
1613
0
            {
1614
0
                std::lock_guard lock(_running_cooldown_mutex);
1615
0
                if (_running_cooldown_tablets.contains(t->table_id())) {
1616
                    // already in cooldown queue
1617
0
                    continue;
1618
0
                }
1619
0
            }
1620
            // TODO(plat1ko): some avoidance strategy if failed to follow
1621
0
            auto score = t->calc_cold_data_compaction_score();
1622
0
            tablet_to_follow.emplace_back(t, score);
1623
1624
0
            if (tablet_to_follow.size() > n) {
1625
0
                std::sort(tablet_to_follow.begin(), tablet_to_follow.end(),
1626
0
                          [](auto& a, auto& b) { return a.second > b.second; });
1627
0
                tablet_to_follow.pop_back();
1628
0
            }
1629
0
        }
1630
1631
0
        for (auto& [tablet, score] : tablet_to_compact) {
1632
0
            LOG(INFO) << "submit cold data compaction. tablet_id=" << tablet->tablet_id()
1633
0
                      << " score=" << score;
1634
0
            static_cast<void>(
1635
0
                    _cold_data_compaction_thread_pool->submit_func([t = std::move(tablet), this]() {
1636
0
                        _handle_cold_data_compaction(std::move(t));
1637
0
                    }));
1638
0
        }
1639
1640
0
        for (auto& [tablet, score] : tablet_to_follow) {
1641
0
            LOG(INFO) << "submit to follow cooldown meta. tablet_id=" << tablet->tablet_id()
1642
0
                      << " score=" << score;
1643
0
            static_cast<void>(_cold_data_compaction_thread_pool->submit_func(
1644
0
                    [t = std::move(tablet), this]() { _follow_cooldown_meta(std::move(t)); }));
1645
0
        }
1646
0
    }
1647
0
}
1648
1649
0
void StorageEngine::_handle_cold_data_compaction(TabletSharedPtr t) {
1650
0
    auto compaction = std::make_shared<ColdDataCompaction>(*this, t);
1651
0
    {
1652
0
        std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1653
0
        _cold_compaction_tablet_submitted.insert(t->tablet_id());
1654
0
    }
1655
0
    Defer defer {[&] {
1656
0
        std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1657
0
        _cold_compaction_tablet_submitted.erase(t->tablet_id());
1658
0
    }};
1659
0
    std::unique_lock cold_compaction_lock(t->get_cold_compaction_lock(), std::try_to_lock);
1660
0
    if (!cold_compaction_lock.owns_lock()) {
1661
0
        LOG(WARNING) << "try cold_compaction_lock failed, tablet_id=" << t->tablet_id();
1662
0
        return;
1663
0
    }
1664
0
    _update_cumulative_compaction_policy();
1665
0
    if (t->get_cumulative_compaction_policy() == nullptr ||
1666
0
        t->get_cumulative_compaction_policy()->name() != t->tablet_meta()->compaction_policy()) {
1667
0
        t->set_cumulative_compaction_policy(
1668
0
                _get_cumulative_compaction_policy(t->tablet_meta()->compaction_policy()));
1669
0
    }
1670
1671
0
    auto st = compaction->prepare_compact();
1672
0
    if (!st.ok()) {
1673
0
        LOG(WARNING) << "failed to prepare cold data compaction. tablet_id=" << t->tablet_id()
1674
0
                     << " err=" << st;
1675
0
        return;
1676
0
    }
1677
1678
0
    st = compaction->execute_compact();
1679
0
    if (!st.ok()) {
1680
0
        LOG(WARNING) << "failed to execute cold data compaction. tablet_id=" << t->tablet_id()
1681
0
                     << " err=" << st;
1682
0
        return;
1683
0
    }
1684
0
}
1685
1686
0
void StorageEngine::_follow_cooldown_meta(TabletSharedPtr t) {
1687
0
    {
1688
0
        std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1689
0
        _cold_compaction_tablet_submitted.insert(t->tablet_id());
1690
0
    }
1691
0
    auto st = t->cooldown();
1692
0
    {
1693
0
        std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1694
0
        _cold_compaction_tablet_submitted.erase(t->tablet_id());
1695
0
    }
1696
0
    if (!st.ok()) {
1697
        // The cooldown of the replica may be relatively slow
1698
        // resulting in a short period of time where following cannot be successful
1699
0
        LOG_EVERY_N(WARNING, 5) << "failed to cooldown. tablet_id=" << t->tablet_id()
1700
0
                                << " err=" << st;
1701
0
    }
1702
0
}
1703
1704
void StorageEngine::add_async_publish_task(int64_t partition_id, int64_t tablet_id,
1705
                                           int64_t publish_version, int64_t transaction_id,
1706
2.05k
                                           bool is_recovery, int64_t commit_tso) {
1707
2.05k
    if (!is_recovery) {
1708
2.05k
        bool exists = false;
1709
2.05k
        {
1710
2.05k
            std::shared_lock<std::shared_mutex> rlock(_async_publish_lock);
1711
2.05k
            if (auto tablet_iter = _async_publish_tasks.find(tablet_id);
1712
2.05k
                tablet_iter != _async_publish_tasks.end()) {
1713
2.05k
                if (auto iter = tablet_iter->second.find(publish_version);
1714
2.05k
                    iter != tablet_iter->second.end()) {
1715
20
                    exists = true;
1716
20
                }
1717
2.05k
            }
1718
2.05k
        }
1719
2.05k
        if (exists) {
1720
20
            return;
1721
20
        }
1722
2.03k
        TabletSharedPtr tablet = tablet_manager()->get_tablet(tablet_id);
1723
2.03k
        if (tablet == nullptr) {
1724
0
            LOG(INFO) << "tablet may be dropped when add async publish task, tablet_id: "
1725
0
                      << tablet_id;
1726
0
            return;
1727
0
        }
1728
2.03k
        PendingPublishInfoPB pending_publish_info_pb;
1729
2.03k
        pending_publish_info_pb.set_partition_id(partition_id);
1730
2.03k
        pending_publish_info_pb.set_transaction_id(transaction_id);
1731
2.03k
        pending_publish_info_pb.set_commit_tso(commit_tso);
1732
2.03k
        static_cast<void>(TabletMetaManager::save_pending_publish_info(
1733
2.03k
                tablet->data_dir(), tablet->tablet_id(), publish_version,
1734
2.03k
                pending_publish_info_pb.SerializeAsString()));
1735
2.03k
    }
1736
2.05k
    LOG(INFO) << "add pending publish task, tablet_id: " << tablet_id
1737
2.03k
              << " version: " << publish_version << " txn_id:" << transaction_id
1738
2.03k
              << " is_recovery: " << is_recovery;
1739
2.03k
    std::unique_lock<std::shared_mutex> wlock(_async_publish_lock);
1740
2.03k
    _async_publish_tasks[tablet_id][publish_version] = {transaction_id, partition_id, commit_tso};
1741
2.03k
}
1742
1743
3
int64_t StorageEngine::get_pending_publish_min_version(int64_t tablet_id) {
1744
3
    std::shared_lock<std::shared_mutex> rlock(_async_publish_lock);
1745
3
    auto iter = _async_publish_tasks.find(tablet_id);
1746
3
    if (iter == _async_publish_tasks.end()) {
1747
0
        return INT64_MAX;
1748
0
    }
1749
3
    if (iter->second.empty()) {
1750
0
        return INT64_MAX;
1751
0
    }
1752
3
    return iter->second.begin()->first;
1753
3
}
1754
1755
10
void StorageEngine::_process_async_publish() {
1756
    // tablet, publish_version
1757
10
    std::vector<std::pair<TabletSharedPtr, int64_t>> need_removed_tasks;
1758
10
    {
1759
10
        std::unique_lock<std::shared_mutex> wlock(_async_publish_lock);
1760
10
        for (auto tablet_iter = _async_publish_tasks.begin();
1761
20
             tablet_iter != _async_publish_tasks.end();) {
1762
10
            if (tablet_iter->second.empty()) {
1763
1
                tablet_iter = _async_publish_tasks.erase(tablet_iter);
1764
1
                continue;
1765
1
            }
1766
9
            int64_t tablet_id = tablet_iter->first;
1767
9
            TabletSharedPtr tablet = tablet_manager()->get_tablet(tablet_id);
1768
9
            if (!tablet) {
1769
1
                LOG(WARNING) << "tablet does not exist when async publush, tablet_id: "
1770
1
                             << tablet_id;
1771
1
                tablet_iter = _async_publish_tasks.erase(tablet_iter);
1772
1
                continue;
1773
1
            }
1774
1775
8
            auto task_iter = tablet_iter->second.begin();
1776
8
            int64_t version = task_iter->first;
1777
8
            int64_t transaction_id = std::get<0>(task_iter->second);
1778
8
            int64_t partition_id = std::get<1>(task_iter->second);
1779
8
            int64_t commit_tso = std::get<2>(task_iter->second);
1780
8
            int64_t max_version = tablet->max_version().second;
1781
1782
8
            if (version <= max_version) {
1783
6
                need_removed_tasks.emplace_back(tablet, version);
1784
6
                tablet_iter->second.erase(task_iter);
1785
6
                tablet_iter++;
1786
6
                continue;
1787
6
            }
1788
2
            if (version != max_version + 1) {
1789
1
                int32_t max_version_config = tablet->max_version_config();
1790
                // Keep only the most recent versions
1791
31
                while (tablet_iter->second.size() > max_version_config) {
1792
30
                    need_removed_tasks.emplace_back(tablet, version);
1793
30
                    task_iter = tablet_iter->second.erase(task_iter);
1794
30
                    version = task_iter->first;
1795
30
                }
1796
1
                tablet_iter++;
1797
1
                continue;
1798
1
            }
1799
1800
1
            auto async_publish_task = std::make_shared<AsyncTabletPublishTask>(
1801
1
                    *this, tablet, partition_id, transaction_id, version, commit_tso);
1802
1
            static_cast<void>(_tablet_publish_txn_thread_pool->submit_func(
1803
1
                    [=]() { async_publish_task->handle(); }));
1804
1
            tablet_iter->second.erase(task_iter);
1805
1
            need_removed_tasks.emplace_back(tablet, version);
1806
1
            tablet_iter++;
1807
1
        }
1808
10
    }
1809
37
    for (auto& [tablet, publish_version] : need_removed_tasks) {
1810
37
        static_cast<void>(TabletMetaManager::remove_pending_publish_info(
1811
37
                tablet->data_dir(), tablet->tablet_id(), publish_version));
1812
37
    }
1813
10
}
1814
1815
0
void StorageEngine::_async_publish_callback() {
1816
0
    while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(30))) {
1817
0
        _process_async_publish();
1818
0
    }
1819
0
}
1820
1821
0
void StorageEngine::_check_tablet_delete_bitmap_score_callback() {
1822
0
    LOG(INFO) << "try to start check tablet delete bitmap score!";
1823
0
    while (!_stop_background_threads_latch.wait_for(
1824
0
            std::chrono::seconds(config::check_tablet_delete_bitmap_interval_seconds))) {
1825
0
        if (!config::enable_check_tablet_delete_bitmap_score) {
1826
0
            return;
1827
0
        }
1828
0
        uint64_t max_delete_bitmap_score = 0;
1829
0
        uint64_t max_base_rowset_delete_bitmap_score = 0;
1830
0
        _tablet_manager->get_topn_tablet_delete_bitmap_score(&max_delete_bitmap_score,
1831
0
                                                             &max_base_rowset_delete_bitmap_score);
1832
0
        if (max_delete_bitmap_score > 0) {
1833
0
            _tablet_max_delete_bitmap_score_metrics->set_value(max_delete_bitmap_score);
1834
0
        }
1835
0
        if (max_base_rowset_delete_bitmap_score > 0) {
1836
0
            _tablet_max_base_rowset_delete_bitmap_score_metrics->set_value(
1837
0
                    max_base_rowset_delete_bitmap_score);
1838
0
        }
1839
0
    }
1840
0
}
1841
} // namespace doris