Coverage Report

Created: 2026-08-03 20:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_cumulative_compaction_policy.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 "cloud/cloud_cumulative_compaction_policy.h"
19
20
#include <algorithm>
21
#include <iterator>
22
#include <list>
23
#include <ostream>
24
#include <string>
25
26
#include "cloud/config.h"
27
#include "common/config.h"
28
#include "common/logging.h"
29
#include "cpp/sync_point.h"
30
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
31
#include "storage/olap_common.h"
32
#include "storage/tablet/tablet.h"
33
#include "storage/tablet/tablet_meta.h"
34
#include "util/defer_op.h"
35
36
namespace doris {
37
38
CloudSizeBasedCumulativeCompactionPolicy::CloudSizeBasedCumulativeCompactionPolicy(
39
        int64_t promotion_size, double promotion_ratio, int64_t promotion_min_size,
40
        int64_t compaction_min_size)
41
250
        : _promotion_size(promotion_size),
42
250
          _promotion_ratio(promotion_ratio),
43
250
          _promotion_min_size(promotion_min_size),
44
250
          _compaction_min_size(compaction_min_size) {}
45
46
34
int64_t CloudSizeBasedCumulativeCompactionPolicy::_level_size(const int64_t size) {
47
34
    if (size < 1024) return 0;
48
20
    int64_t max_level = (int64_t)1
49
20
                        << (sizeof(_promotion_size) * 8 - 1 - __builtin_clzl(_promotion_size / 2));
50
20
    if (size >= max_level) return max_level;
51
14
    return (int64_t)1 << (sizeof(size) * 8 - 1 - __builtin_clzl(size));
52
20
}
53
54
void find_longest_consecutive_empty_rowsets(std::vector<RowsetSharedPtr>* result,
55
18
                                            const std::vector<RowsetSharedPtr>& candidate_rowsets) {
56
18
    std::vector<RowsetSharedPtr> current_sequence;
57
18
    std::vector<RowsetSharedPtr> longest_sequence;
58
59
308
    for (size_t i = 0; i < candidate_rowsets.size(); ++i) {
60
290
        auto& rowset = candidate_rowsets[i];
61
62
        // Check if rowset is empty and has no delete predicate
63
290
        if (rowset->num_segments() == 0 && !rowset->rowset_meta()->has_delete_predicate()) {
64
            // Check if this is consecutive with previous rowset
65
196
            if (current_sequence.empty() ||
66
196
                (current_sequence.back()->end_version() == rowset->start_version() - 1)) {
67
196
                current_sequence.push_back(rowset);
68
196
            } else {
69
                // Start new sequence if not consecutive
70
0
                if (current_sequence.size() > longest_sequence.size()) {
71
0
                    longest_sequence = current_sequence;
72
0
                }
73
0
                current_sequence.clear();
74
0
                current_sequence.push_back(rowset);
75
0
            }
76
196
        } else {
77
            // Non-empty rowset, check if we have a sequence to compare
78
94
            if (current_sequence.size() > longest_sequence.size()) {
79
11
                longest_sequence = current_sequence;
80
11
            }
81
94
            current_sequence.clear();
82
94
        }
83
290
    }
84
85
    // Check final sequence
86
18
    if (current_sequence.size() > longest_sequence.size()) {
87
3
        longest_sequence = current_sequence;
88
3
    }
89
90
18
    *result = longest_sequence;
91
18
}
92
93
int64_t CloudSizeBasedCumulativeCompactionPolicy::pick_input_rowsets(
94
        CloudTablet* tablet, const std::vector<RowsetSharedPtr>& candidate_rowsets,
95
        const int64_t max_compaction_score, const int64_t min_compaction_score,
96
        std::vector<RowsetSharedPtr>* input_rowsets, Version* last_delete_version,
97
16
        size_t* compaction_score, bool allow_delete) {
98
16
    DBUG_EXECUTE_IF(
99
16
            "CloudSizeBasedCumulativeCompactionPolicy::pick_input_rowsets.set_input_rowsets", {
100
16
                auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
101
16
                if (target_tablet_id == tablet->tablet_id()) {
102
16
                    auto start_version = dp->param<int64_t>("start_version", -1);
103
16
                    auto end_version = dp->param<int64_t>("end_version", -1);
104
16
                    for (auto& rowset : candidate_rowsets) {
105
16
                        if (rowset->start_version() >= start_version &&
106
16
                            rowset->end_version() <= end_version) {
107
16
                            input_rowsets->push_back(rowset);
108
16
                        }
109
16
                    }
110
16
                    LOG_INFO(
111
16
                            "[CloudSizeBasedCumulativeCompactionPolicy::pick_input_rowsets.set_"
112
16
                            "input_rowsets] tablet_id={}, start={}, end={}, "
113
16
                            "input_rowsets->size()={}",
114
16
                            target_tablet_id, start_version, end_version, input_rowsets->size());
115
16
                    return input_rowsets->size();
116
16
                }
117
16
            })
118
119
16
    size_t promotion_size = cloud_promotion_size(tablet);
120
16
    auto max_version = tablet->max_version().first;
121
16
    int transient_size = 0;
122
16
    *compaction_score = 0;
123
16
    int64_t total_size = 0;
124
16
    bool skip_trim = false; // Skip trim for Empty Rowset Compaction
125
16
    RowsetSharedPtr last_popped;
126
127
    // DEFER: trim input_rowsets from back if score > max_compaction_score
128
    // This ensures we don't return more rowsets than allowed by max_compaction_score,
129
    // while still collecting enough rowsets to pass min_compaction_score check after level_size removal.
130
    // Must be placed after variable initialization and before collection loop.
131
16
    DEFER({
132
16
        if (skip_trim) {
133
16
            return;
134
16
        }
135
        // Keep at least 1 rowset to avoid removing the only rowset (consistent with fallback branch)
136
16
        while (input_rowsets->size() > 1 &&
137
16
               *compaction_score > static_cast<size_t>(max_compaction_score)) {
138
16
            last_popped = std::move(input_rowsets->back());
139
16
            *compaction_score -= last_popped->rowset_meta()->get_compaction_score();
140
16
            total_size -= last_popped->rowset_meta()->total_disk_size();
141
16
            input_rowsets->pop_back();
142
16
        }
143
        // A single non-overlapping rowset cannot be compacted by itself. Restore the direct
144
        // successor and accept a one-off max-score overshoot to keep the input mergeable.
145
16
        if (input_rowsets->size() == 1 && last_popped != nullptr &&
146
16
            !input_rowsets->front()->rowset_meta()->is_segments_overlapping()) {
147
16
            *compaction_score += last_popped->rowset_meta()->get_compaction_score();
148
16
            total_size += last_popped->rowset_meta()->total_disk_size();
149
16
            input_rowsets->push_back(std::move(last_popped));
150
16
        }
151
16
    });
152
153
288
    for (auto& rowset : candidate_rowsets) {
154
        // check whether this rowset is delete version
155
288
        if (!allow_delete && rowset->rowset_meta()->has_delete_predicate()) {
156
0
            *last_delete_version = rowset->version();
157
0
            if (!input_rowsets->empty()) {
158
                // we meet a delete version, and there were other versions before.
159
                // we should compact those version before handling them over to base compaction
160
0
                break;
161
0
            } else {
162
                // we meet a delete version, and no other versions before, skip it and continue
163
0
                input_rowsets->clear();
164
0
                *compaction_score = 0;
165
0
                transient_size = 0;
166
0
                continue;
167
0
            }
168
0
        }
169
288
        if (tablet->tablet_state() == TABLET_NOTREADY) {
170
            // If tablet under alter, keep latest 10 version so that base tablet max version
171
            // not merged in new tablet, and then we can copy data from base tablet
172
0
            if (rowset->version().second < max_version - 10) {
173
0
                continue;
174
0
            }
175
0
        }
176
        // Removed: max_compaction_score check here
177
        // We now collect all candidate rowsets and trim from back at return time via DEFER
178
288
        *compaction_score += rowset->rowset_meta()->get_compaction_score();
179
288
        total_size += rowset->rowset_meta()->total_disk_size();
180
181
288
        transient_size += 1;
182
288
        input_rowsets->push_back(rowset);
183
288
    }
184
185
    // if there is delete version, do compaction directly
186
16
    if (last_delete_version->first != -1) {
187
0
        if (input_rowsets->size() == 1) {
188
0
            auto rs_meta = input_rowsets->front()->rowset_meta();
189
            // if there is only one rowset and not overlapping,
190
            // we do not need to do cumulative compaction
191
0
            if (!rs_meta->is_segments_overlapping()) {
192
0
                input_rowsets->clear();
193
0
                *compaction_score = 0;
194
0
            }
195
0
        }
196
0
        return transient_size;
197
0
    }
198
199
    // Check if empty rowset compaction strategy is enabled
200
16
    if (config::enable_empty_rowset_compaction && !input_rowsets->empty()) {
201
        // Check if input_rowsets contain consecutive empty rowsets that meet criteria
202
15
        std::vector<RowsetSharedPtr> consecutive_empty_rowsets;
203
15
        find_longest_consecutive_empty_rowsets(&consecutive_empty_rowsets, *input_rowsets);
204
205
15
        if (!consecutive_empty_rowsets.empty() &&
206
15
            consecutive_empty_rowsets.size() >= config::empty_rowset_compaction_min_count &&
207
15
            static_cast<double>(consecutive_empty_rowsets.size()) /
208
5
                            static_cast<double>(input_rowsets->size()) >=
209
5
                    config::empty_rowset_compaction_min_ratio) {
210
            // Prioritize consecutive empty rowset compaction
211
            // Skip trim: empty rowset compaction has very low cost and the goal is to reduce rowset count
212
4
            *input_rowsets = consecutive_empty_rowsets;
213
4
            *compaction_score = consecutive_empty_rowsets.size();
214
4
            skip_trim = true;
215
4
            return consecutive_empty_rowsets.size();
216
4
        }
217
15
    }
218
219
12
    auto rs_begin = input_rowsets->begin();
220
12
    size_t new_compaction_score = *compaction_score;
221
12
    const bool can_handle_exhausted_input =
222
12
            (config::prioritize_query_perf_in_compaction && tablet->keys_type() != DUP_KEYS) ||
223
12
            *compaction_score >= static_cast<size_t>(max_compaction_score);
224
18
    while (rs_begin != input_rowsets->end()) {
225
17
        auto& rs_meta = (*rs_begin)->rowset_meta();
226
17
        int64_t current_level = _level_size(rs_meta->total_disk_size());
227
17
        int64_t remain_level = _level_size(total_size - rs_meta->total_disk_size());
228
        // if current level less then remain level, input rowsets contain current rowset
229
        // and process return; otherwise, input rowsets do not contain current rowset.
230
17
        if (current_level <= remain_level) {
231
7
            break;
232
7
        }
233
234
10
        auto next = std::next(rs_begin);
235
        // Keep the last suffix rowset for the singleton checks unless the exhausted-input
236
        // fallback below can select a useful input.
237
10
        if (next == input_rowsets->end() && !can_handle_exhausted_input) {
238
4
            break;
239
4
        }
240
6
        total_size -= rs_meta->total_disk_size();
241
6
        new_compaction_score -= rs_meta->get_compaction_score();
242
6
        rs_begin = next;
243
6
    }
244
12
    if (rs_begin == input_rowsets->end()) { // No suitable level size found in `input_rowsets`
245
1
        if (config::prioritize_query_perf_in_compaction && tablet->keys_type() != DUP_KEYS) {
246
            // While tablet's key type is not `DUP_KEYS`, compacting rowset in such tablets has a significant
247
            // positive impact on queries and reduces space amplification, so we ignore level limitation and
248
            // pick candidate rowsets as input rowsets.
249
1
            return transient_size;
250
1
        } else if (*compaction_score >= max_compaction_score) {
251
            // Score of `input_rowsets` exceed max compaction score, which means `input_rowsets` will never change and
252
            // this tablet will never execute cumulative compaction. MUST execute compaction on these `input_rowsets`
253
            // to reduce compaction score.
254
0
            RowsetSharedPtr rs_with_max_score;
255
0
            uint32_t max_score = 1;
256
0
            for (auto& rs : *input_rowsets) {
257
0
                if (rs->rowset_meta()->get_compaction_score() > max_score) {
258
0
                    max_score = rs->rowset_meta()->get_compaction_score();
259
0
                    rs_with_max_score = rs;
260
0
                }
261
0
            }
262
0
            if (rs_with_max_score) {
263
0
                input_rowsets->clear();
264
0
                input_rowsets->push_back(std::move(rs_with_max_score));
265
0
                *compaction_score = max_score;
266
0
                return transient_size;
267
0
            }
268
            // no rowset is OVERLAPPING, return all input rowsets (DEFER will trim to max_compaction_score)
269
0
            return transient_size;
270
0
        }
271
1
    }
272
11
    input_rowsets->erase(input_rowsets->begin(), rs_begin);
273
11
    *compaction_score = new_compaction_score;
274
275
11
    VLOG_CRITICAL << "cumulative compaction size_based policy, compaction_score = "
276
0
                  << *compaction_score << ", total_size = " << total_size
277
0
                  << ", calc promotion size value = " << promotion_size
278
0
                  << ", tablet = " << tablet->tablet_id() << ", input_rowset size "
279
0
                  << input_rowsets->size();
280
281
    // empty return
282
11
    if (input_rowsets->empty()) {
283
0
        return transient_size;
284
0
    }
285
286
    // if we have a sufficient number of segments, we should process the compaction.
287
    // otherwise, we check number of segments and total_size whether can do compaction.
288
11
    if (total_size < _compaction_min_size && *compaction_score < min_compaction_score) {
289
1
        input_rowsets->clear();
290
1
        *compaction_score = 0;
291
10
    } else if (total_size >= _compaction_min_size && input_rowsets->size() == 1) {
292
3
        auto rs_meta = input_rowsets->front()->rowset_meta();
293
        // if there is only one rowset and not overlapping,
294
        // we do not need to do compaction
295
3
        if (!rs_meta->is_segments_overlapping()) {
296
1
            input_rowsets->clear();
297
1
            *compaction_score = 0;
298
1
        }
299
3
    }
300
11
    return transient_size;
301
11
}
302
303
18
int64_t CloudSizeBasedCumulativeCompactionPolicy::cloud_promotion_size(CloudTablet* t) const {
304
18
    int64_t promotion_size = int64_t(cast_set<double>(t->base_size()) * _promotion_ratio);
305
    // promotion_size is between _size_based_promotion_size and _size_based_promotion_min_size
306
18
    return promotion_size > _promotion_size       ? _promotion_size
307
18
           : promotion_size < _promotion_min_size ? _promotion_min_size
308
18
                                                  : promotion_size;
309
18
}
310
311
int64_t CloudSizeBasedCumulativeCompactionPolicy::new_cumulative_point(
312
        CloudTablet* tablet, const RowsetSharedPtr& output_rowset, Version& last_delete_version,
313
3
        int64_t last_cumulative_point) {
314
3
    TEST_INJECTION_POINT_RETURN_WITH_VALUE("new_cumulative_point", int64_t(0), output_rowset.get(),
315
3
                                           last_cumulative_point);
316
3
    DBUG_EXECUTE_IF("CloudSizeBasedCumulativeCompactionPolicy::new_cumulative_point", {
317
3
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
318
3
        auto cumu_point = dp->param<int64_t>("cumu_point", -1);
319
3
        if (target_tablet_id == tablet->tablet_id() && cumu_point != -1) {
320
3
            LOG_INFO(
321
3
                    "[CloudSizeBasedCumulativeCompactionPolicy::new_cumulative_point] "
322
3
                    "tablet_id={}, cumu_point={}",
323
3
                    target_tablet_id, cumu_point);
324
3
            return cumu_point;
325
3
        }
326
3
    });
327
    // for MoW table, if there's too many versions, the delete bitmap will grow to
328
    // a very big size, which may cause the tablet meta too big and the `save_meta`
329
    // operation too slow.
330
    // if the rowset should not promotion according to it's disk size, we should also
331
    // consider it's version count here.
332
3
    bool satisfy_promotion_version = tablet->enable_unique_key_merge_on_write() &&
333
3
                                     output_rowset->end_version() - output_rowset->start_version() >
334
2
                                             config::compaction_promotion_version_count;
335
    // if rowsets have delete version, move to the last directly.
336
    // if rowsets have no delete version, check output_rowset total disk size satisfies promotion size.
337
3
    return (last_delete_version.first != -1 ||
338
3
            output_rowset->total_disk_size() >= cloud_promotion_size(tablet) ||
339
3
            satisfy_promotion_version)
340
3
                   ? output_rowset->end_version() + 1
341
3
                   : last_cumulative_point;
342
3
}
343
344
int64_t CloudTimeSeriesCumulativeCompactionPolicy::pick_input_rowsets(
345
        CloudTablet* tablet, const std::vector<RowsetSharedPtr>& candidate_rowsets,
346
        const int64_t max_compaction_score, const int64_t min_compaction_score,
347
        std::vector<RowsetSharedPtr>* input_rowsets, Version* last_delete_version,
348
0
        size_t* compaction_score, bool allow_delete) {
349
0
    int64_t last_cumu = tablet->last_cumu_compaction_success_time();
350
0
    return TimeSeriesCumulativeCompactionPolicy::pick_input_rowsets(
351
0
            tablet, last_cumu, candidate_rowsets, max_compaction_score, min_compaction_score,
352
0
            input_rowsets, last_delete_version, compaction_score, allow_delete);
353
0
}
354
355
int64_t CloudTimeSeriesCumulativeCompactionPolicy::get_compaction_level(
356
        CloudTablet* tablet, const std::vector<RowsetSharedPtr>& input_rowsets,
357
0
        RowsetSharedPtr output_rowset) {
358
0
    return TimeSeriesCumulativeCompactionPolicy::get_compaction_level((BaseTablet*)tablet,
359
0
                                                                      input_rowsets, output_rowset);
360
0
}
361
362
int64_t CloudTimeSeriesCumulativeCompactionPolicy::new_cumulative_point(
363
        CloudTablet* tablet, const RowsetSharedPtr& output_rowset, Version& last_delete_version,
364
0
        int64_t last_cumulative_point) {
365
0
    if (tablet->tablet_state() != TABLET_RUNNING || output_rowset->num_segments() == 0) {
366
0
        return last_cumulative_point;
367
0
    }
368
369
0
    if (tablet->tablet_meta()->time_series_compaction_level_threshold() >= 2 &&
370
0
        output_rowset->rowset_meta()->compaction_level() < 2) {
371
0
        return last_cumulative_point;
372
0
    }
373
374
0
    return output_rowset->end_version() + 1;
375
0
}
376
377
} // namespace doris