Coverage Report

Created: 2026-08-10 13:02

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