Coverage Report

Created: 2026-04-10 16:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/compaction/base_compaction.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 "storage/compaction/base_compaction.h"
19
20
#include <gen_cpp/olap_file.pb.h>
21
22
#include <memory>
23
#include <mutex>
24
#include <ostream>
25
26
#include "common/cast_set.h"
27
#include "common/config.h"
28
#include "common/logging.h"
29
#include "common/metrics/doris_metrics.h"
30
#include "runtime/thread_context.h"
31
#include "storage/compaction/compaction.h"
32
#include "storage/olap_define.h"
33
#include "storage/rowset/rowset_meta.h"
34
#include "storage/tablet/tablet.h"
35
#include "util/thread.h"
36
#include "util/trace.h"
37
38
namespace doris {
39
40
using namespace ErrorCode;
41
42
BaseCompaction::BaseCompaction(StorageEngine& engine, const TabletSharedPtr& tablet)
43
44.6k
        : CompactionMixin(engine, tablet, "BaseCompaction:" + std::to_string(tablet->tablet_id())) {
44
44.6k
}
45
46
44.6k
BaseCompaction::~BaseCompaction() = default;
47
48
44.5k
Status BaseCompaction::prepare_compact() {
49
44.5k
    Status st;
50
44.5k
    Defer defer_set_st([&] {
51
44.5k
        if (!st.ok()) {
52
44.5k
            tablet()->set_last_base_compaction_status(st.to_string());
53
44.5k
            tablet()->set_last_base_compaction_failure_time(UnixMillis());
54
44.5k
        }
55
44.5k
    });
56
57
44.5k
    if (!tablet()->init_succeeded()) {
58
0
        st = Status::Error<INVALID_ARGUMENT, false>("_tablet init failed");
59
0
        return st;
60
0
    }
61
62
44.5k
    std::unique_lock<std::mutex> lock(tablet()->get_base_compaction_lock(), std::try_to_lock);
63
44.5k
    if (!lock.owns_lock()) {
64
0
        st = Status::Error<TRY_LOCK_FAILED, false>("another base compaction is running. tablet={}",
65
0
                                                   _tablet->tablet_id());
66
0
        return st;
67
0
    }
68
69
    // 1. pick rowsets to compact
70
44.5k
    st = pick_rowsets_to_compact();
71
44.5k
    RETURN_IF_ERROR(st);
72
2
    COUNTER_UPDATE(_input_rowsets_counter, _input_rowsets.size());
73
74
2
    st = Status::OK();
75
2
    return st;
76
44.5k
}
77
78
2
Status BaseCompaction::execute_compact() {
79
2
#ifndef __APPLE__
80
2
    if (config::enable_base_compaction_idle_sched) {
81
2
        Thread::set_idle_sched();
82
2
    }
83
2
#endif
84
2
    Status st;
85
2
    Defer defer_set_st([&] {
86
2
        tablet()->set_last_base_compaction_status(st.to_string());
87
2
        if (!st.ok()) {
88
0
            tablet()->set_last_base_compaction_failure_time(UnixMillis());
89
2
        } else {
90
2
            tablet()->set_last_base_compaction_success_time(UnixMillis());
91
2
        }
92
2
    });
93
94
2
    std::unique_lock<std::mutex> lock(tablet()->get_base_compaction_lock(), std::try_to_lock);
95
2
    if (!lock.owns_lock()) {
96
0
        st = Status::Error<TRY_LOCK_FAILED, false>("another base compaction is running. tablet={}",
97
0
                                                   _tablet->tablet_id());
98
0
        return st;
99
0
    }
100
101
2
    SCOPED_ATTACH_TASK(_mem_tracker);
102
103
2
    st = CompactionMixin::execute_compact();
104
2
    RETURN_IF_ERROR(st);
105
106
2
    DCHECK_EQ(_state, CompactionState::SUCCESS);
107
108
2
    DorisMetrics::instance()->base_compaction_deltas_total->increment(_input_rowsets.size());
109
2
    DorisMetrics::instance()->base_compaction_bytes_total->increment(_input_rowsets_total_size);
110
111
2
    st = Status::OK();
112
2
    return st;
113
2
}
114
115
44.5k
void BaseCompaction::_filter_input_rowset() {
116
    // if dup_key and no delete predicate
117
    // we skip big files to save resources
118
44.5k
    if (_tablet->keys_type() != KeysType::DUP_KEYS) {
119
21.9k
        return;
120
21.9k
    }
121
22.6k
    for (auto& rs : _input_rowsets) {
122
21.3k
        if (rs->rowset_meta()->has_delete_predicate()) {
123
4
            return;
124
4
        }
125
21.3k
    }
126
22.6k
    int64_t max_size = config::base_compaction_dup_key_max_file_size_mbytes * 1024 * 1024;
127
    // first find a proper rowset for start
128
22.6k
    auto rs_iter = _input_rowsets.begin();
129
22.6k
    while (rs_iter != _input_rowsets.end()) {
130
21.3k
        if ((*rs_iter)->rowset_meta()->total_disk_size() >= max_size) {
131
0
            rs_iter = _input_rowsets.erase(rs_iter);
132
21.3k
        } else {
133
21.3k
            break;
134
21.3k
        }
135
21.3k
    }
136
22.6k
}
137
138
44.5k
Status BaseCompaction::pick_rowsets_to_compact() {
139
44.5k
    _input_rowsets = tablet()->pick_candidate_rowsets_to_base_compaction();
140
44.5k
    RETURN_IF_ERROR(check_version_continuity(_input_rowsets));
141
44.5k
    _filter_input_rowset();
142
44.5k
    if (_input_rowsets.size() <= 1) {
143
44.5k
        return Status::Error<BE_NO_SUITABLE_VERSION>("_input_rowsets.size() is 1");
144
44.5k
    }
145
146
    // There are two occasions, first is that we set enable_delete_when_cumu_compaction false:
147
    // If there are delete predicate rowsets in tablet, start_version > 0 implies some rowsets before
148
    // delete version cannot apply these delete predicates, which can cause incorrect query result.
149
    // So we must abort this base compaction.
150
    // A typical scenario is that some rowsets before cumulative point are on remote storage.
151
    // For example, consider rowset[0,3] is on remote storage, now we pass [4,4],[5,5],[6,9]
152
    // to do base compaction and rowset[5,5] is delete predicate rowset, if we allow them to do
153
    // such procedure, then we'll get [4,9] while it will lose the delete predicate information in [5,5]
154
    // which rusult in data in [0,3] will not be deleted.
155
    // Another occasion is that we set enable_delete_when_cumu_compaction true:
156
    // Then whatever the _input_rowsets.front()->start_version() > 0 or not, once the output
157
    // rowset's start version is bigger than 2, we'll always remain the delete pred information inside
158
    // the output rowset so the rowsets whose version is less than _input_rowsets.front()->start_version() > 0
159
    // would apply the delete pred in the end.
160
8
    if (!_allow_delete_in_cumu_compaction && _input_rowsets.front()->start_version() > 0) {
161
0
        bool has_delete_predicate = false;
162
0
        for (const auto& rs : _input_rowsets) {
163
0
            if (rs->rowset_meta()->has_delete_predicate()) {
164
0
                has_delete_predicate = true;
165
0
                break;
166
0
            }
167
0
        }
168
0
        if (has_delete_predicate) {
169
0
            return Status::Error<BE_NO_SUITABLE_VERSION>(
170
0
                    "Some rowsets cannot apply delete predicates in base compaction. tablet_id={}",
171
0
                    _tablet->tablet_id());
172
0
        }
173
0
    }
174
175
8
    if (_input_rowsets.size() == 2 && _input_rowsets[0]->end_version() == 1) {
176
2
        return Status::Error<BE_NO_SUITABLE_VERSION>(
177
2
                "the tablet is with rowset: [0-1], [2-y], and [0-1] has no data. in this "
178
2
                "situation, no need to do base compaction.");
179
2
    }
180
181
6
    int score = 0;
182
6
    int rowset_cnt = 0;
183
6
    int64_t max_compaction_score = _tablet->keys_type() == KeysType::UNIQUE_KEYS &&
184
6
                                                   _tablet->enable_unique_key_merge_on_write()
185
6
                                           ? config::mow_base_compaction_max_compaction_score
186
6
                                           : config::base_compaction_max_compaction_score;
187
58
    while (rowset_cnt < _input_rowsets.size()) {
188
54
        score += _input_rowsets[rowset_cnt++]->rowset_meta()->get_compaction_score();
189
54
        if (score > max_compaction_score) {
190
2
            break;
191
2
        }
192
54
    }
193
6
    _input_rowsets.resize(rowset_cnt);
194
195
    // 1. cumulative rowset must reach base_compaction_num_cumulative_deltas threshold
196
6
    if (_input_rowsets.size() > config::base_compaction_min_rowset_num) {
197
2
        VLOG_NOTICE << "satisfy the base compaction policy. tablet=" << _tablet->tablet_id()
198
0
                    << ", num_cumulative_rowsets=" << _input_rowsets.size() - 1
199
0
                    << ", base_compaction_num_cumulative_rowsets="
200
0
                    << config::base_compaction_min_rowset_num;
201
2
        return Status::OK();
202
2
    }
203
204
    // 2. the ratio between base rowset and all input cumulative rowsets reaches the threshold
205
    // `_input_rowsets` has been sorted by end version, so we consider `_input_rowsets[0]` is the base rowset.
206
4
    int64_t base_size = _input_rowsets.front()->data_disk_size();
207
4
    int64_t cumulative_total_size = 0;
208
12
    for (auto it = _input_rowsets.begin() + 1; it != _input_rowsets.end(); ++it) {
209
8
        cumulative_total_size += (*it)->data_disk_size();
210
8
    }
211
212
4
    double min_data_ratio = config::base_compaction_min_data_ratio;
213
4
    if (base_size == 0) {
214
        // base_size == 0 means this may be a base version [0-1], which has no data.
215
        // set to 1 to void divide by zero
216
4
        base_size = 1;
217
4
    }
218
4
    double cumulative_base_ratio =
219
4
            cast_set<double>(cumulative_total_size) / cast_set<double>(base_size);
220
221
4
    if (cumulative_base_ratio > min_data_ratio) {
222
2
        VLOG_NOTICE << "satisfy the base compaction policy. tablet=" << _tablet->tablet_id()
223
0
                    << ", cumulative_total_size=" << cumulative_total_size
224
0
                    << ", base_size=" << base_size
225
0
                    << ", cumulative_base_ratio=" << cumulative_base_ratio
226
0
                    << ", policy_min_data_ratio=" << min_data_ratio;
227
2
        return Status::OK();
228
2
    }
229
230
    // 3. the interval since last base compaction reaches the threshold
231
2
    int64_t base_creation_time = _input_rowsets[0]->creation_time();
232
2
    int64_t interval_threshold = config::base_compaction_interval_seconds_since_last_operation;
233
2
    int64_t interval_since_last_base_compaction = time(nullptr) - base_creation_time;
234
2
    if (interval_since_last_base_compaction > interval_threshold) {
235
0
        VLOG_NOTICE << "satisfy the base compaction policy. tablet=" << _tablet->tablet_id()
236
0
                    << ", interval_since_last_base_compaction="
237
0
                    << interval_since_last_base_compaction
238
0
                    << ", interval_threshold=" << interval_threshold;
239
0
        return Status::OK();
240
0
    }
241
242
2
    return Status::Error<BE_NO_SUITABLE_VERSION>(
243
2
            "don't satisfy the base compaction policy. tablet={}, num_cumulative_rowsets={}, "
244
2
            "cumulative_base_ratio={}, interval_since_last_base_compaction={}",
245
2
            _tablet->tablet_id(), _input_rowsets.size() - 1, cumulative_base_ratio,
246
2
            interval_since_last_base_compaction);
247
2
}
248
249
} // namespace doris