Coverage Report

Created: 2026-03-16 15:21

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
57.6k
                                                            std::vector<Version>* missing_version) {
49
57.6k
    if (rowsets->empty()) {
50
0
        return;
51
0
    }
52
53
57.6k
    RowsetSharedPtr prev_rowset = rowsets->front();
54
57.6k
    int i = 1;
55
57.6k
    int max_start = 0;
56
57.6k
    int max_length = 1;
57
58
57.6k
    int start = 0;
59
57.6k
    int length = 1;
60
225k
    for (; i < rowsets->size(); ++i) {
61
168k
        RowsetSharedPtr rowset = (*rowsets)[i];
62
168k
        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
168k
        } else {
70
168k
            length++;
71
168k
        }
72
73
168k
        if (length > max_length) {
74
168k
            max_start = start;
75
168k
            max_length = length;
76
168k
        }
77
78
168k
        prev_rowset = rowset;
79
168k
    }
80
57.6k
    *rowsets = {rowsets->begin() + max_start, rowsets->begin() + max_start + max_length};
81
57.6k
}
82
83
CumulativeCompaction::CumulativeCompaction(StorageEngine& engine, const TabletSharedPtr& tablet)
84
60.6k
        : CompactionMixin(engine, tablet,
85
60.6k
                          "CumulativeCompaction:" + std::to_string(tablet->tablet_id())) {}
86
87
60.6k
CumulativeCompaction::~CumulativeCompaction() = default;
88
89
60.6k
Status CumulativeCompaction::prepare_compact() {
90
60.6k
    Status st;
91
60.6k
    Defer defer_set_st([&] {
92
60.6k
        if (!st.ok()) {
93
60.5k
            tablet()->set_last_cumu_compaction_status(st.to_string());
94
60.5k
        }
95
60.6k
    });
96
97
60.6k
    if (!tablet()->init_succeeded()) {
98
0
        st = Status::Error<CUMULATIVE_INVALID_PARAMETERS, false>("_tablet init failed");
99
0
        return st;
100
0
    }
101
102
60.6k
    std::unique_lock<std::mutex> lock(tablet()->get_cumulative_compaction_lock(), std::try_to_lock);
103
60.6k
    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
60.6k
    tablet()->calculate_cumulative_point();
110
60.6k
    VLOG_CRITICAL << "after calculate, current cumulative point is "
111
0
                  << tablet()->cumulative_layer_point() << ", tablet=" << _tablet->tablet_id();
112
113
60.6k
    st = pick_rowsets_to_compact();
114
60.6k
    RETURN_IF_ERROR(st);
115
116
70
    COUNTER_UPDATE(_input_rowsets_counter, _input_rowsets.size());
117
118
70
    st = Status::OK();
119
70
    return st;
120
60.6k
}
121
122
49
Status CumulativeCompaction::execute_compact() {
123
49
    DBUG_EXECUTE_IF("CumulativeCompaction::execute_compact.block", {
124
49
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
125
49
        if (target_tablet_id == _tablet->tablet_id()) {
126
49
            LOG(INFO) << "start debug block "
127
49
                      << "CumulativeCompaction::execute_compact.block";
128
49
            while (DebugPoints::instance()->is_enable(
129
49
                    "CumulativeCompaction::execute_compact.block")) {
130
49
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
131
49
            }
132
49
            LOG(INFO) << "end debug block "
133
49
                      << "CumulativeCompaction::execute_compact.block";
134
49
        }
135
49
    })
136
137
49
    Status st;
138
50
    Defer defer_set_st([&] {
139
50
        tablet()->set_last_cumu_compaction_status(st.to_string());
140
50
        if (!st.ok()) {
141
0
            tablet()->set_last_cumu_compaction_failure_time(UnixMillis());
142
50
        } else {
143
            // TIME_SERIES_POLICY, generating an empty rowset doesn't need to update the timestamp.
144
50
            if (!(tablet()->tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY &&
145
50
                  _output_rowset->num_segments() == 0)) {
146
50
                tablet()->set_last_cumu_compaction_success_time(UnixMillis());
147
50
            }
148
50
        }
149
50
    });
150
49
    std::unique_lock<std::mutex> lock(tablet()->get_cumulative_compaction_lock(), std::try_to_lock);
151
49
    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
49
    SCOPED_ATTACH_TASK(_mem_tracker);
158
159
49
    st = CompactionMixin::execute_compact();
160
49
    RETURN_IF_ERROR(st);
161
162
49
    TEST_SYNC_POINT_RETURN_WITH_VALUE(
163
49
            "cumulative_compaction::CumulativeCompaction::execute_compact", Status::OK());
164
165
49
    DCHECK_EQ(_state, CompactionState::SUCCESS);
166
167
49
    tablet()->cumulative_compaction_policy()->update_cumulative_point(
168
49
            tablet(), _input_rowsets, _output_rowset, _last_delete_version);
169
49
    VLOG_CRITICAL << "after cumulative compaction, current cumulative point is "
170
0
                  << tablet()->cumulative_layer_point() << ", tablet=" << _tablet->tablet_id();
171
49
    DorisMetrics::instance()->cumulative_compaction_deltas_total->increment(_input_rowsets.size());
172
49
    DorisMetrics::instance()->cumulative_compaction_bytes_total->increment(
173
49
            _input_rowsets_total_size);
174
175
49
    st = Status::OK();
176
49
    return st;
177
49
}
178
179
60.6k
Status CumulativeCompaction::pick_rowsets_to_compact() {
180
60.6k
    auto candidate_rowsets = tablet()->pick_candidate_rowsets_to_cumulative_compaction();
181
60.6k
    if (candidate_rowsets.empty()) {
182
3.02k
        return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>("candidate_rowsets is empty");
183
3.02k
    }
184
185
    // candidate_rowsets may not be continuous
186
    // So we need to choose the longest continuous path from it.
187
57.6k
    std::vector<Version> missing_versions;
188
57.6k
    find_longest_consecutive_version(&candidate_rowsets, &missing_versions);
189
57.6k
    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
57.6k
    int64_t max_score = config::cumulative_compaction_max_deltas;
218
57.6k
    int64_t process_memory_usage = doris::GlobalMemoryArbitrator::process_memory_usage();
219
57.6k
    bool memory_usage_high = process_memory_usage > MemInfo::soft_mem_limit() * 8 / 10;
220
57.6k
    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
57.6k
    size_t compaction_score = 0;
227
57.6k
    tablet()->cumulative_compaction_policy()->pick_input_rowsets(
228
57.6k
            tablet(), candidate_rowsets, max_score, config::cumulative_compaction_min_deltas,
229
57.6k
            &_input_rowsets, &_last_delete_version, &compaction_score,
230
57.6k
            _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
57.6k
    if (_input_rowsets.empty()) {
235
57.5k
        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
28
            tablet()->set_cumulative_layer_point(_last_delete_version.first + 1);
240
28
            LOG_INFO(
241
28
                    "cumulative compaction meet delete rowset, increase cumu point without "
242
28
                    "other "
243
28
                    "operation.")
244
28
                    .tag("tablet id:", tablet()->tablet_id())
245
28
                    .tag("after cumulative compaction, cumu point:",
246
28
                         tablet()->cumulative_layer_point());
247
28
            return Status::Error<CUMULATIVE_MEET_DELETE_VERSION>(
248
28
                    "cumulative compaction meet delete version");
249
28
        }
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
57.5k
        int64_t now = UnixMillis();
258
57.5k
        int64_t last_cumu = tablet()->last_cumu_compaction_success_time();
259
57.5k
        int64_t last_base = tablet()->last_base_compaction_success_time();
260
57.5k
        if (last_cumu != 0 || last_base != 0) {
261
55.6k
            int64_t interval_threshold = config::pick_rowset_to_compact_interval_sec * 1000;
262
55.6k
            int64_t cumu_interval = now - last_cumu;
263
55.6k
            int64_t base_interval = now - last_base;
264
55.6k
            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
55.6k
        } else {
278
            // init the compaction success time for first time
279
1.86k
            if (last_cumu == 0) {
280
1.86k
                tablet()->set_last_cumu_compaction_success_time(now);
281
1.86k
            }
282
283
1.86k
            if (last_base == 0) {
284
1.86k
                tablet()->set_last_base_compaction_success_time(now);
285
1.86k
            }
286
1.86k
        }
287
288
57.5k
        return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>("_input_rowsets is empty");
289
57.5k
    }
290
291
70
    return Status::OK();
292
57.6k
}
293
#include "common/compile_check_end.h"
294
295
} // namespace doris