Coverage Report

Created: 2026-08-07 08:08

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