Coverage Report

Created: 2026-03-14 13:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/compaction/cumulative_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/cumulative_compaction.h"
19
20
#include <cpp/sync_point.h>
21
#include <gen_cpp/AgentService_types.h>
22
#include <gen_cpp/Types_types.h>
23
24
#include <memory>
25
#include <mutex>
26
#include <ostream>
27
#include <vector>
28
29
#include "common/config.h"
30
#include "common/logging.h"
31
#include "common/metrics/doris_metrics.h"
32
#include "runtime/exec_env.h"
33
#include "runtime/thread_context.h"
34
#include "storage/compaction/cumulative_compaction_policy.h"
35
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
36
#include "storage/olap_define.h"
37
#include "storage/rowset/rowset_meta.h"
38
#include "storage/storage_engine.h"
39
#include "storage/tablet/tablet.h"
40
#include "util/time.h"
41
#include "util/trace.h"
42
43
namespace doris {
44
#include "common/compile_check_begin.h"
45
using namespace ErrorCode;
46
47
void CumulativeCompaction::find_longest_consecutive_version(std::vector<RowsetSharedPtr>* rowsets,
48
54.7k
                                                            std::vector<Version>* missing_version) {
49
54.7k
    if (rowsets->empty()) {
50
0
        return;
51
0
    }
52
53
54.7k
    RowsetSharedPtr prev_rowset = rowsets->front();
54
54.7k
    int i = 1;
55
54.7k
    int max_start = 0;
56
54.7k
    int max_length = 1;
57
58
54.7k
    int start = 0;
59
54.7k
    int length = 1;
60
212k
    for (; i < rowsets->size(); ++i) {
61
157k
        RowsetSharedPtr rowset = (*rowsets)[i];
62
157k
        if (rowset->start_version() != prev_rowset->end_version() + 1) {
63
6
            if (missing_version != nullptr) {
64
6
                missing_version->push_back(prev_rowset->version());
65
6
                missing_version->push_back(rowset->version());
66
6
            }
67
6
            start = i;
68
6
            length = 1;
69
157k
        } else {
70
157k
            length++;
71
157k
        }
72
73
157k
        if (length > max_length) {
74
157k
            max_start = start;
75
157k
            max_length = length;
76
157k
        }
77
78
157k
        prev_rowset = rowset;
79
157k
    }
80
54.7k
    *rowsets = {rowsets->begin() + max_start, rowsets->begin() + max_start + max_length};
81
54.7k
}
82
83
CumulativeCompaction::CumulativeCompaction(StorageEngine& engine, const TabletSharedPtr& tablet)
84
56.7k
        : CompactionMixin(engine, tablet,
85
56.7k
                          "CumulativeCompaction:" + std::to_string(tablet->tablet_id())) {}
86
87
56.7k
CumulativeCompaction::~CumulativeCompaction() = default;
88
89
56.7k
Status CumulativeCompaction::prepare_compact() {
90
56.7k
    Status st;
91
56.7k
    Defer defer_set_st([&] {
92
56.7k
        if (!st.ok()) {
93
56.6k
            tablet()->set_last_cumu_compaction_status(st.to_string());
94
56.6k
        }
95
56.7k
    });
96
97
56.7k
    if (!tablet()->init_succeeded()) {
98
0
        st = Status::Error<CUMULATIVE_INVALID_PARAMETERS, false>("_tablet init failed");
99
0
        return st;
100
0
    }
101
102
56.7k
    std::unique_lock<std::mutex> lock(tablet()->get_cumulative_compaction_lock(), std::try_to_lock);
103
56.7k
    if (!lock.owns_lock()) {
104
0
        st = Status::Error<TRY_LOCK_FAILED, false>(
105
0
                "The tablet is under cumulative compaction. tablet={}", _tablet->tablet_id());
106
0
        return st;
107
0
    }
108
109
56.7k
    tablet()->calculate_cumulative_point();
110
56.7k
    VLOG_CRITICAL << "after calculate, current cumulative point is "
111
0
                  << tablet()->cumulative_layer_point() << ", tablet=" << _tablet->tablet_id();
112
113
56.7k
    st = pick_rowsets_to_compact();
114
56.7k
    RETURN_IF_ERROR(st);
115
116
56
    COUNTER_UPDATE(_input_rowsets_counter, _input_rowsets.size());
117
118
56
    st = Status::OK();
119
56
    return st;
120
56.7k
}
121
122
35
Status CumulativeCompaction::execute_compact() {
123
35
    DBUG_EXECUTE_IF("CumulativeCompaction::execute_compact.block", {
124
35
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
125
35
        if (target_tablet_id == _tablet->tablet_id()) {
126
35
            LOG(INFO) << "start debug block "
127
35
                      << "CumulativeCompaction::execute_compact.block";
128
35
            while (DebugPoints::instance()->is_enable(
129
35
                    "CumulativeCompaction::execute_compact.block")) {
130
35
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
131
35
            }
132
35
            LOG(INFO) << "end debug block "
133
35
                      << "CumulativeCompaction::execute_compact.block";
134
35
        }
135
35
    })
136
137
35
    Status st;
138
36
    Defer defer_set_st([&] {
139
36
        tablet()->set_last_cumu_compaction_status(st.to_string());
140
36
        if (!st.ok()) {
141
0
            tablet()->set_last_cumu_compaction_failure_time(UnixMillis());
142
36
        } else {
143
            // TIME_SERIES_POLICY, generating an empty rowset doesn't need to update the timestamp.
144
36
            if (!(tablet()->tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY &&
145
36
                  _output_rowset->num_segments() == 0)) {
146
36
                tablet()->set_last_cumu_compaction_success_time(UnixMillis());
147
36
            }
148
36
        }
149
36
    });
150
35
    std::unique_lock<std::mutex> lock(tablet()->get_cumulative_compaction_lock(), std::try_to_lock);
151
35
    if (!lock.owns_lock()) {
152
0
        st = Status::Error<TRY_LOCK_FAILED, false>(
153
0
                "The tablet is under cumulative compaction. tablet={}", _tablet->tablet_id());
154
0
        return st;
155
0
    }
156
157
35
    SCOPED_ATTACH_TASK(_mem_tracker);
158
159
35
    st = CompactionMixin::execute_compact();
160
35
    RETURN_IF_ERROR(st);
161
162
35
    TEST_SYNC_POINT_RETURN_WITH_VALUE(
163
35
            "cumulative_compaction::CumulativeCompaction::execute_compact", Status::OK());
164
165
35
    DCHECK_EQ(_state, CompactionState::SUCCESS);
166
167
35
    tablet()->cumulative_compaction_policy()->update_cumulative_point(
168
35
            tablet(), _input_rowsets, _output_rowset, _last_delete_version);
169
35
    VLOG_CRITICAL << "after cumulative compaction, current cumulative point is "
170
0
                  << tablet()->cumulative_layer_point() << ", tablet=" << _tablet->tablet_id();
171
35
    DorisMetrics::instance()->cumulative_compaction_deltas_total->increment(_input_rowsets.size());
172
35
    DorisMetrics::instance()->cumulative_compaction_bytes_total->increment(
173
35
            _input_rowsets_total_size);
174
175
35
    st = Status::OK();
176
35
    return st;
177
35
}
178
179
56.7k
Status CumulativeCompaction::pick_rowsets_to_compact() {
180
56.7k
    auto candidate_rowsets = tablet()->pick_candidate_rowsets_to_cumulative_compaction();
181
56.7k
    if (candidate_rowsets.empty()) {
182
2.01k
        return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>("candidate_rowsets is empty");
183
2.01k
    }
184
185
    // candidate_rowsets may not be continuous
186
    // So we need to choose the longest continuous path from it.
187
54.7k
    std::vector<Version> missing_versions;
188
54.7k
    find_longest_consecutive_version(&candidate_rowsets, &missing_versions);
189
54.7k
    if (!missing_versions.empty()) {
190
0
        DCHECK(missing_versions.size() % 2 == 0);
191
0
        LOG(WARNING) << "There are missed versions among rowsets. "
192
0
                     << "total missed version size: " << missing_versions.size() / 2
193
0
                     << ", first missed version prev rowset verison=" << missing_versions[0]
194
0
                     << ", first missed version next rowset version=" << missing_versions[1]
195
0
                     << ", tablet=" << _tablet->tablet_id();
196
0
        if (config::enable_auto_clone_on_compaction_missing_version) {
197
0
            int64_t max_version = tablet()->max_version_unlocked();
198
0
            LOG_INFO("cumulative compaction submit missing rowset clone task.")
199
0
                    .tag("tablet_id", _tablet->tablet_id())
200
0
                    .tag("max_version", max_version)
201
0
                    .tag("replica_id", tablet()->replica_id())
202
0
                    .tag("partition_id", _tablet->partition_id())
203
0
                    .tag("table_id", _tablet->table_id());
204
0
            Status st = _engine.submit_clone_task(tablet(), max_version);
205
0
            if (!st) {
206
0
                LOG_WARNING("cumulative compaction failed to submit missing rowset clone task.")
207
0
                        .tag("st", st.msg())
208
0
                        .tag("tablet_id", _tablet->tablet_id())
209
0
                        .tag("max_version", max_version)
210
0
                        .tag("replica_id", tablet()->replica_id())
211
0
                        .tag("partition_id", _tablet->partition_id())
212
0
                        .tag("table_id", _tablet->table_id());
213
0
            }
214
0
        }
215
0
    }
216
217
54.7k
    int64_t max_score = config::cumulative_compaction_max_deltas;
218
54.7k
    int64_t process_memory_usage = doris::GlobalMemoryArbitrator::process_memory_usage();
219
54.7k
    bool memory_usage_high = process_memory_usage > MemInfo::soft_mem_limit() * 8 / 10;
220
54.7k
    if (tablet()->last_compaction_status.is<ErrorCode::MEM_LIMIT_EXCEEDED>() || memory_usage_high) {
221
0
        max_score = std::max(config::cumulative_compaction_max_deltas /
222
0
                                     config::cumulative_compaction_max_deltas_factor,
223
0
                             config::cumulative_compaction_min_deltas + 1);
224
0
    }
225
226
54.7k
    size_t compaction_score = 0;
227
54.7k
    tablet()->cumulative_compaction_policy()->pick_input_rowsets(
228
54.7k
            tablet(), candidate_rowsets, max_score, config::cumulative_compaction_min_deltas,
229
54.7k
            &_input_rowsets, &_last_delete_version, &compaction_score,
230
54.7k
            _allow_delete_in_cumu_compaction);
231
232
    // Cumulative compaction will process with at least 1 rowset.
233
    // So when there is no rowset being chosen, we should return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>():
234
54.7k
    if (_input_rowsets.empty()) {
235
54.6k
        if (_last_delete_version.first != -1) {
236
            // we meet a delete version, should increase the cumulative point to let base compaction handle the delete version.
237
            // plus 1 to skip the delete version.
238
            // NOTICE: after that, the cumulative point may be larger than max version of this tablet, but it doesn't matter.
239
20
            tablet()->set_cumulative_layer_point(_last_delete_version.first + 1);
240
20
            LOG_INFO(
241
20
                    "cumulative compaction meet delete rowset, increase cumu point without "
242
20
                    "other "
243
20
                    "operation.")
244
20
                    .tag("tablet id:", tablet()->tablet_id())
245
20
                    .tag("after cumulative compaction, cumu point:",
246
20
                         tablet()->cumulative_layer_point());
247
20
            return Status::Error<CUMULATIVE_MEET_DELETE_VERSION>(
248
20
                    "cumulative compaction meet delete version");
249
20
        }
250
251
        // we did not meet any delete version. which means compaction_score is not enough to do cumulative compaction.
252
        // We should wait until there are more rowsets to come, and keep the cumulative point unchanged.
253
        // But in order to avoid the stall of compaction because no new rowset arrives later, we should increase
254
        // the cumulative point after waiting for a long time, to ensure that the base compaction can continue.
255
256
        // check both last success time of base and cumulative compaction
257
54.6k
        int64_t now = UnixMillis();
258
54.6k
        int64_t last_cumu = tablet()->last_cumu_compaction_success_time();
259
54.6k
        int64_t last_base = tablet()->last_base_compaction_success_time();
260
54.6k
        if (last_cumu != 0 || last_base != 0) {
261
53.0k
            int64_t interval_threshold = config::pick_rowset_to_compact_interval_sec * 1000;
262
53.0k
            int64_t cumu_interval = now - last_cumu;
263
53.0k
            int64_t base_interval = now - last_base;
264
53.0k
            if (cumu_interval > interval_threshold && base_interval > interval_threshold) {
265
                // before increasing cumulative point, we should make sure all rowsets are non-overlapping.
266
                // if at least one rowset is overlapping, we should compact them first.
267
0
                for (auto& rs : candidate_rowsets) {
268
0
                    if (rs->rowset_meta()->is_segments_overlapping()) {
269
0
                        _input_rowsets = candidate_rowsets;
270
0
                        return Status::OK();
271
0
                    }
272
0
                }
273
274
                // all candidate rowsets are non-overlapping, increase the cumulative point
275
0
                tablet()->set_cumulative_layer_point(candidate_rowsets.back()->start_version() + 1);
276
0
            }
277
53.0k
        } else {
278
            // init the compaction success time for first time
279
1.60k
            if (last_cumu == 0) {
280
1.60k
                tablet()->set_last_cumu_compaction_success_time(now);
281
1.60k
            }
282
283
1.60k
            if (last_base == 0) {
284
1.60k
                tablet()->set_last_base_compaction_success_time(now);
285
1.60k
            }
286
1.60k
        }
287
288
54.6k
        return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>("_input_rowsets is empty");
289
54.6k
    }
290
291
56
    return Status::OK();
292
54.7k
}
293
#include "common/compile_check_end.h"
294
295
} // namespace doris