Coverage Report

Created: 2026-04-10 04:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/compaction/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 "storage/compaction/cumulative_compaction_policy.h"
19
20
#include <algorithm>
21
#include <list>
22
#include <ostream>
23
#include <string>
24
25
#include "common/config.h"
26
#include "common/logging.h"
27
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
28
#include "storage/olap_common.h"
29
#include "storage/tablet/tablet.h"
30
#include "storage/tablet/tablet_meta.h"
31
#include "util/debug_points.h"
32
#include "util/defer_op.h"
33
34
namespace doris {
35
36
SizeBasedCumulativeCompactionPolicy::SizeBasedCumulativeCompactionPolicy(
37
        int64_t promotion_size, double promotion_ratio, int64_t promotion_min_size,
38
        int64_t promotion_version_count, int64_t compaction_min_size)
39
583
        : _promotion_size(promotion_size),
40
583
          _promotion_ratio(promotion_ratio),
41
583
          _promotion_min_size(promotion_min_size),
42
583
          _promotion_version_count(promotion_version_count),
43
583
          _compaction_min_size(compaction_min_size) {}
44
45
void SizeBasedCumulativeCompactionPolicy::calculate_cumulative_point(
46
        Tablet* tablet, const RowsetMetaMapContainer& all_metas, int64_t current_cumulative_point,
47
69
        int64_t* ret_cumulative_point) {
48
69
    *ret_cumulative_point = Tablet::K_INVALID_CUMULATIVE_POINT;
49
69
    if (current_cumulative_point != Tablet::K_INVALID_CUMULATIVE_POINT) {
50
        // only calculate the point once.
51
        // after that, cumulative point will be updated along with compaction process.
52
21
        return;
53
21
    }
54
    // empty return
55
48
    if (all_metas.empty()) {
56
0
        return;
57
0
    }
58
59
48
    std::list<RowsetMetaSharedPtr> existing_rss;
60
3.05k
    for (const auto& [_, rs] : all_metas) {
61
3.05k
        existing_rss.emplace_back(rs);
62
3.05k
    }
63
64
    // sort the existing rowsets by version in ascending order
65
18.5k
    existing_rss.sort([](const RowsetMetaSharedPtr& a, const RowsetMetaSharedPtr& b) {
66
        // simple because 2 versions are certainly not overlapping
67
18.5k
        return a->version().first < b->version().first;
68
18.5k
    });
69
70
    // calculate promotion size
71
48
    auto base_rowset_meta = existing_rss.begin();
72
73
48
    if (tablet->tablet_state() == TABLET_RUNNING) {
74
        // check base rowset first version must be zero
75
        // for tablet which state is not TABLET_RUNNING, there may not have base version.
76
48
        CHECK((*base_rowset_meta)->start_version() == 0);
77
78
48
        int64_t promotion_size = 0;
79
48
        _calc_promotion_size(tablet, *base_rowset_meta, &promotion_size);
80
81
48
        int64_t prev_version = -1;
82
98
        for (const RowsetMetaSharedPtr& rs : existing_rss) {
83
98
            if (rs->version().first > prev_version + 1) {
84
                // There is a hole, do not continue
85
0
                break;
86
0
            }
87
88
98
            bool is_delete = rs->has_delete_predicate();
89
90
            // break the loop if segments in this rowset is overlapping.
91
98
            if (!is_delete && rs->is_segments_overlapping()) {
92
12
                *ret_cumulative_point = rs->version().first;
93
12
                break;
94
12
            }
95
96
            // check the rowset is whether less than promotion size
97
86
            if (!is_delete && rs->version().first != 0 && rs->total_disk_size() < promotion_size) {
98
35
                *ret_cumulative_point = rs->version().first;
99
35
                break;
100
35
            }
101
102
            // include one situation: When the segment is not deleted, and is singleton delta, and is NONOVERLAPPING, ret_cumulative_point increase
103
51
            prev_version = rs->version().second;
104
51
            *ret_cumulative_point = prev_version + 1;
105
51
        }
106
48
        VLOG_NOTICE
107
0
                << "cumulative compaction size_based policy, calculate cumulative point value = "
108
0
                << *ret_cumulative_point << ", calc promotion size value = " << promotion_size
109
0
                << " tablet = " << tablet->tablet_id();
110
48
    } else if (tablet->tablet_state() == TABLET_NOTREADY) {
111
        // tablet under alter process
112
        // we choose version next to the base version as cumulative point
113
0
        for (const RowsetMetaSharedPtr& rs : existing_rss) {
114
0
            if (rs->version().first > 0) {
115
0
                *ret_cumulative_point = rs->version().first;
116
0
                break;
117
0
            }
118
0
        }
119
0
    }
120
48
}
121
122
void SizeBasedCumulativeCompactionPolicy::_calc_promotion_size(Tablet* tablet,
123
                                                               RowsetMetaSharedPtr base_rowset_meta,
124
79
                                                               int64_t* promotion_size) {
125
79
    int64_t base_size = base_rowset_meta->total_disk_size();
126
79
    *promotion_size = int64_t(cast_set<double>(base_size) * _promotion_ratio);
127
128
    // promotion_size is between _promotion_size and _promotion_min_size
129
79
    if (*promotion_size >= _promotion_size) {
130
8
        *promotion_size = _promotion_size;
131
71
    } else if (*promotion_size <= _promotion_min_size) {
132
71
        *promotion_size = _promotion_min_size;
133
71
    }
134
79
    _refresh_tablet_promotion_size(tablet, *promotion_size);
135
79
}
136
137
void SizeBasedCumulativeCompactionPolicy::_refresh_tablet_promotion_size(Tablet* tablet,
138
79
                                                                         int64_t promotion_size) {
139
79
    tablet->set_cumulative_promotion_size(promotion_size);
140
79
}
141
142
void SizeBasedCumulativeCompactionPolicy::update_cumulative_point(
143
        Tablet* tablet, const std::vector<RowsetSharedPtr>& input_rowsets,
144
0
        RowsetSharedPtr output_rowset, Version& last_delete_version) {
145
0
    if (tablet->tablet_state() != TABLET_RUNNING) {
146
        // if tablet under alter process, do not update cumulative point
147
0
        return;
148
0
    }
149
    // if rowsets have delete version, move to the last directly
150
0
    if (last_delete_version.first != -1) {
151
0
        tablet->set_cumulative_layer_point(output_rowset->end_version() + 1);
152
0
    } else {
153
        // if rowsets have no delete version, check output_rowset total disk size
154
        // satisfies promotion size.
155
0
        size_t total_size = output_rowset->rowset_meta()->total_disk_size();
156
0
        if (total_size >= tablet->cumulative_promotion_size()) {
157
0
            tablet->set_cumulative_layer_point(output_rowset->end_version() + 1);
158
0
        } else if (tablet->enable_unique_key_merge_on_write() &&
159
0
                   output_rowset->end_version() - output_rowset->start_version() >
160
0
                           _promotion_version_count) {
161
            // for MoW table, if there's too many versions, the delete bitmap will grow to
162
            // a very big size, which may cause the tablet meta too big and the `save_meta`
163
            // operation too slow.
164
            // if the rowset should not promotion according to it's disk size, we should also
165
            // consider it's version count here.
166
0
            tablet->set_cumulative_layer_point(output_rowset->end_version() + 1);
167
0
        }
168
0
    }
169
0
}
170
171
31
uint32_t SizeBasedCumulativeCompactionPolicy::calc_cumulative_compaction_score(Tablet* tablet) {
172
31
    uint32_t score = 0;
173
31
    bool base_rowset_exist = false;
174
31
    const int64_t point = tablet->cumulative_layer_point();
175
31
    int64_t promotion_size = 0;
176
177
31
    std::vector<RowsetMetaSharedPtr> rowset_to_compact;
178
31
    int64_t total_size = 0;
179
180
31
    RowsetMetaSharedPtr first_meta;
181
31
    int64_t first_version = INT64_MAX;
182
    // NOTE: tablet._meta_lock is hold
183
31
    auto& rs_metas = tablet->tablet_meta()->all_rs_metas();
184
    // check the base rowset and collect the rowsets of cumulative part
185
2.26k
    for (const auto& [_, rs_meta] : rs_metas) {
186
2.26k
        if (rs_meta->start_version() < first_version) {
187
570
            first_version = rs_meta->start_version();
188
570
            first_meta = rs_meta;
189
570
        }
190
        // check base rowset
191
2.26k
        if (rs_meta->start_version() == 0) {
192
31
            base_rowset_exist = true;
193
31
        }
194
2.26k
        if (rs_meta->end_version() < point || !rs_meta->is_local()) {
195
            // all_rs_metas() is not sorted, so we use _continue_ other than _break_ here.
196
31
            continue;
197
2.22k
        } else {
198
            // collect the rowsets of cumulative part
199
2.22k
            total_size += rs_meta->total_disk_size();
200
2.22k
            score += rs_meta->get_compaction_score();
201
2.22k
            rowset_to_compact.push_back(rs_meta);
202
2.22k
        }
203
2.26k
    }
204
205
31
    if (first_meta == nullptr) {
206
0
        return 0;
207
0
    }
208
209
    // Use "first"(not base) version to calc promotion size
210
    // because some tablet do not have base version(under alter operation)
211
31
    _calc_promotion_size(tablet, first_meta, &promotion_size);
212
213
    // If base version does not exist, but its state is RUNNING.
214
    // It is abnormal, do not select it and set *score = 0
215
31
    if (!base_rowset_exist && tablet->tablet_state() == TABLET_RUNNING) {
216
0
        LOG(WARNING) << "tablet state is running but have no base version";
217
0
        return 0;
218
0
    }
219
220
    // if total_size is greater than promotion_size, return total score
221
31
    if (total_size >= promotion_size) {
222
0
        return score;
223
0
    }
224
225
    // sort the rowsets of cumulative part
226
31
    std::sort(rowset_to_compact.begin(), rowset_to_compact.end(), RowsetMeta::comparator);
227
228
    // calculate the rowsets to do cumulative compaction
229
    // eg: size of rowset_to_compact are:
230
    // 128, 16, 16, 16
231
    // we will choose [16,16,16] to compact.
232
31
    for (auto& rs_meta : rowset_to_compact) {
233
31
        int64_t current_level = _level_size(rs_meta->total_disk_size());
234
31
        int64_t remain_level = _level_size(total_size - rs_meta->total_disk_size());
235
        // if current level less then remain level, score contains current rowset
236
        // and process return; otherwise, score does not contains current rowset.
237
31
        if (current_level <= remain_level) {
238
31
            return score;
239
31
        }
240
0
        total_size -= rs_meta->total_disk_size();
241
0
        score -= rs_meta->get_compaction_score();
242
0
    }
243
0
    return score;
244
31
}
245
246
int SizeBasedCumulativeCompactionPolicy::pick_input_rowsets(
247
        Tablet* tablet, const std::vector<RowsetSharedPtr>& candidate_rowsets,
248
        const int64_t max_compaction_score, const int64_t min_compaction_score,
249
        std::vector<RowsetSharedPtr>* input_rowsets, Version* last_delete_version,
250
61
        size_t* compaction_score, bool allow_delete) {
251
61
    DBUG_EXECUTE_IF("SizeBasedCumulativeCompactionPolicy::pick_input_rowsets.set_input_rowsets", {
252
61
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
253
61
        if (target_tablet_id == tablet->tablet_id()) {
254
61
            auto start_version = dp->param<int64_t>("start_version", -1);
255
61
            auto end_version = dp->param<int64_t>("end_version", -1);
256
61
            for (auto& rowset : candidate_rowsets) {
257
61
                if (rowset->start_version() >= start_version &&
258
61
                    rowset->end_version() <= end_version) {
259
61
                    input_rowsets->push_back(rowset);
260
61
                }
261
61
            }
262
61
        }
263
61
        return cast_set<uint32_t>(input_rowsets->size());
264
61
    })
265
266
61
    size_t promotion_size = tablet->cumulative_promotion_size();
267
61
    auto max_version = tablet->max_version().first;
268
61
    int transient_size = 0;
269
61
    *compaction_score = 0;
270
61
    int64_t total_size = 0;
271
272
    // DEFER: trim input_rowsets from back if score > max_compaction_score
273
    // This ensures we don't return more rowsets than allowed by max_compaction_score,
274
    // while still collecting enough rowsets to pass min_compaction_score check after level_size removal.
275
    // Must be placed after variable initialization and before collection loop.
276
61
    DEFER({
277
        // Keep at least 1 rowset to avoid removing the only rowset (consistent with fallback branch)
278
61
        while (input_rowsets->size() > 1 &&
279
61
               *compaction_score > static_cast<size_t>(max_compaction_score)) {
280
61
            auto& last_rowset = input_rowsets->back();
281
61
            *compaction_score -= last_rowset->rowset_meta()->get_compaction_score();
282
61
            total_size -= last_rowset->rowset_meta()->total_disk_size();
283
61
            input_rowsets->pop_back();
284
61
        }
285
61
    });
286
287
3.54k
    for (auto& rowset : candidate_rowsets) {
288
        // check whether this rowset is delete version
289
3.54k
        if (!allow_delete && rowset->rowset_meta()->has_delete_predicate()) {
290
3
            *last_delete_version = rowset->version();
291
3
            if (!input_rowsets->empty()) {
292
                // we meet a delete version, and there were other versions before.
293
                // we should compact those version before handling them over to base compaction
294
3
                break;
295
3
            } else {
296
                // we meet a delete version, and no other versions before, skip it and continue
297
0
                input_rowsets->clear();
298
0
                *compaction_score = 0;
299
0
                transient_size = 0;
300
0
                continue;
301
0
            }
302
3
        }
303
3.54k
        if (tablet->tablet_state() == TABLET_NOTREADY) {
304
            // If tablet under alter, keep latest 10 version so that base tablet max version
305
            // not merged in new tablet, and then we can copy data from base tablet
306
0
            if (rowset->version().second < max_version - 10) {
307
0
                continue;
308
0
            }
309
0
        }
310
        // Removed: max_compaction_score check here
311
        // We now collect all candidate rowsets and trim from back at return time via DEFER
312
3.54k
        *compaction_score += rowset->rowset_meta()->get_compaction_score();
313
3.54k
        total_size += rowset->rowset_meta()->total_disk_size();
314
315
3.54k
        transient_size += 1;
316
3.54k
        input_rowsets->push_back(rowset);
317
3.54k
    }
318
61
    DBUG_EXECUTE_IF("SizeBaseCumulativeCompactionPolicy.pick_input_rowsets.return_input_rowsets",
319
61
                    { return transient_size; })
320
321
61
    if (total_size >= promotion_size) {
322
37
        return transient_size;
323
37
    }
324
325
    // if there is delete version, do compaction directly
326
24
    if (last_delete_version->first != -1) {
327
1
        if (input_rowsets->size() == 1) {
328
0
            auto rs_meta = input_rowsets->front()->rowset_meta();
329
            // if there is only one rowset and not overlapping,
330
            // we do not need to do cumulative compaction
331
0
            if (!rs_meta->is_segments_overlapping()) {
332
0
                input_rowsets->clear();
333
0
                *compaction_score = 0;
334
0
            }
335
0
        }
336
1
        return transient_size;
337
1
    }
338
339
23
    auto rs_begin = input_rowsets->begin();
340
23
    size_t new_compaction_score = *compaction_score;
341
46
    while (rs_begin != input_rowsets->end()) {
342
42
        auto& rs_meta = (*rs_begin)->rowset_meta();
343
42
        int64_t current_level = _level_size(rs_meta->total_disk_size());
344
42
        int64_t remain_level = _level_size(total_size - rs_meta->total_disk_size());
345
        // if current level less then remain level, input rowsets contain current rowset
346
        // and process return; otherwise, input rowsets do not contain current rowset.
347
42
        if (current_level <= remain_level) {
348
19
            break;
349
19
        }
350
23
        total_size -= rs_meta->total_disk_size();
351
23
        new_compaction_score -= rs_meta->get_compaction_score();
352
23
        ++rs_begin;
353
23
    }
354
23
    if (rs_begin == input_rowsets->end() && *compaction_score >= max_compaction_score) {
355
        // No suitable level size found in `input_rowsets` but score of `input_rowsets` exceed max compaction score,
356
        // which means `input_rowsets` will never change and this tablet will never execute cumulative compaction.
357
        // MUST execute compaction on these `input_rowsets` to reduce compaction score.
358
2
        RowsetSharedPtr rs_with_max_score;
359
2
        uint32_t max_score = 1;
360
7
        for (auto& rs : *input_rowsets) {
361
7
            if (rs->rowset_meta()->get_compaction_score() > max_score) {
362
1
                max_score = rs->rowset_meta()->get_compaction_score();
363
1
                rs_with_max_score = rs;
364
1
            }
365
7
        }
366
2
        if (rs_with_max_score) {
367
1
            input_rowsets->clear();
368
1
            input_rowsets->push_back(std::move(rs_with_max_score));
369
1
            *compaction_score = max_score;
370
1
            return transient_size;
371
1
        }
372
        // no rowset is OVERLAPPING, return all input rowsets (DEFER will trim to max_compaction_score)
373
1
        return transient_size;
374
2
    }
375
21
    input_rowsets->erase(input_rowsets->begin(), rs_begin);
376
21
    *compaction_score = new_compaction_score;
377
378
21
    VLOG_CRITICAL << "cumulative compaction size_based policy, compaction_score = "
379
0
                  << *compaction_score << ", total_size = " << total_size
380
0
                  << ", calc promotion size value = " << promotion_size
381
0
                  << ", tablet = " << tablet->tablet_id() << ", input_rowset size "
382
0
                  << input_rowsets->size();
383
384
    // empty return
385
21
    if (input_rowsets->empty()) {
386
2
        return transient_size;
387
2
    }
388
389
    // if we have a sufficient number of segments, we should process the compaction.
390
    // otherwise, we check number of segments and total_size whether can do compaction.
391
19
    if (total_size < _compaction_min_size && *compaction_score < min_compaction_score) {
392
4
        input_rowsets->clear();
393
4
        *compaction_score = 0;
394
15
    } else if (total_size >= _compaction_min_size && input_rowsets->size() == 1) {
395
0
        auto rs_meta = input_rowsets->front()->rowset_meta();
396
        // if there is only one rowset and not overlapping,
397
        // we do not need to do compaction
398
0
        if (!rs_meta->is_segments_overlapping()) {
399
0
            input_rowsets->clear();
400
0
            *compaction_score = 0;
401
0
        }
402
0
    }
403
19
    return transient_size;
404
21
}
405
406
150
int64_t SizeBasedCumulativeCompactionPolicy::_level_size(const int64_t size) {
407
150
    if (size < 1024) return 0;
408
70
    int64_t max_level = (int64_t)1
409
70
                        << (sizeof(_promotion_size) * 8 - 1 - __builtin_clzl(_promotion_size / 2));
410
70
    if (size >= max_level) return max_level;
411
69
    return (int64_t)1 << (sizeof(size) * 8 - 1 - __builtin_clzl(size));
412
70
}
413
414
std::shared_ptr<CumulativeCompactionPolicy>
415
CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
416
598
        const std::string_view& compaction_policy) {
417
598
    if (compaction_policy == CUMULATIVE_TIME_SERIES_POLICY) {
418
15
        return std::make_shared<TimeSeriesCumulativeCompactionPolicy>();
419
583
    } else if (compaction_policy == CUMULATIVE_SIZE_BASED_POLICY) {
420
521
        return std::make_shared<SizeBasedCumulativeCompactionPolicy>();
421
521
    }
422
62
    return std::make_shared<SizeBasedCumulativeCompactionPolicy>();
423
598
}
424
} // namespace doris