Coverage Report

Created: 2026-06-02 23:11

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