Coverage Report

Created: 2026-07-24 01:26

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