Coverage Report

Created: 2026-07-30 08:12

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