Coverage Report

Created: 2026-08-14 16:47

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