Coverage Report

Created: 2026-09-15 14:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/compaction/compaction.h
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
#pragma once
19
20
#include <cstdint>
21
// clang20 + -O1 causes warnings about pass-failed
22
// error: loop not unrolled: the optimizer was unable to perform the requested transformation; the transformation might be disabled or specified as part of an unsupported transformation ordering [-Werror,-Wpass-failed=transform-warning]
23
#if defined(__clang__)
24
#pragma clang diagnostic push
25
#pragma clang diagnostic ignored "-Wpass-failed"
26
#endif
27
#include <limits>
28
#include <memory>
29
#if defined(__clang__)
30
#pragma clang diagnostic pop
31
#endif
32
#include <optional>
33
#include <string>
34
#include <utility>
35
#include <vector>
36
37
#include "cloud/cloud_tablet.h"
38
#include "common/status.h"
39
#include "io/io_common.h"
40
#include "runtime/runtime_profile.h"
41
#include "storage/compaction_task_tracker.h"
42
#include "storage/merger.h"
43
#include "storage/olap_common.h"
44
#include "storage/rowid_conversion.h"
45
#include "storage/rowset/pending_rowset_helper.h"
46
#include "storage/rowset/rowset_fwd.h"
47
#include "storage/tablet/tablet_fwd.h"
48
49
namespace doris {
50
51
class MemTrackerLimiter;
52
class RowsetWriter;
53
struct RowsetWriterContext;
54
class StorageEngine;
55
class CloudStorageEngine;
56
57
static constexpr int COMPACTION_DELETE_BITMAP_LOCK_ID = -1;
58
static constexpr int64_t INVALID_COMPACTION_INITIATOR_ID = -100;
59
// This class is a base class for compaction.
60
// The entrance of this class is compact()
61
// Any compaction should go through four procedures.
62
//  1. pick rowsets satisfied to compact
63
//  2. do compaction
64
//  3. modify rowsets
65
//  4. gc output rowset if failed
66
class Compaction {
67
public:
68
    Compaction(BaseTabletSPtr tablet, const std::string& label);
69
    virtual ~Compaction();
70
71
    // Pick input rowsets satisfied to compact
72
    virtual Status prepare_compact() = 0;
73
74
    // Merge input rowsets to output rowset and modify tablet meta
75
    virtual Status execute_compact() = 0;
76
77
0
    RuntimeProfile* runtime_profile() const { return _profile.get(); }
78
79
    virtual ReaderType compaction_type() const = 0;
80
    virtual std::string_view compaction_name() const = 0;
81
82
    // Returns compaction profile type for task tracking.
83
    // Default returns std::nullopt (not tracked). Only base/cumulative/full override.
84
0
    virtual std::optional<CompactionProfileType> profile_type() const { return std::nullopt; }
85
86
    // Accessors for tracker registration
87
27
    int64_t compaction_id() const { return _compaction_id; }
88
22
    int64_t input_rowsets_data_size() const { return _input_rowsets_data_size; }
89
22
    int64_t input_rowsets_index_size() const { return _input_rowsets_index_size; }
90
22
    int64_t input_rowsets_total_size() const { return _input_rowsets_total_size; }
91
22
    int64_t input_row_num_value() const { return _input_row_num; }
92
22
    int64_t input_rowsets_count() const { return static_cast<int64_t>(_input_rowsets.size()); }
93
56
    virtual int64_t input_segments_num_value() const { return _input_num_segments; }
94
22
    bool is_vertical() const { return _is_vertical; }
95
    std::string input_version_range_str() const;
96
97
    // the difference between index change compmaction and other compaction.
98
    // 1. delete predicate should be kept when input is cumu rowset.
99
    // 2. inverted compaction should be skipped.
100
    // 3. compute level should not be changed.
101
2
    virtual bool is_index_change_compaction() { return false; }
102
103
private:
104
    void set_delete_predicate_for_output_rowset();
105
106
protected:
107
    struct MergeInputRowsetsResult {
108
        bool is_segment_grouped = false;
109
        int64_t segment_group_size = 0;
110
        std::vector<int32_t> output_segment_group_sizes;
111
    };
112
113
    Status merge_input_rowsets();
114
115
    void snapshot_row_binlog_ttl();
116
    bool pick_expired_row_binlog_rowset(const std::vector<RowsetSharedPtr>& candidates);
117
    void filter_row_binlog_ttl_rowsets();
118
119
25
    virtual Status prepare_merge_input_rowsets(MergeInputRowsetsResult* /*result*/) {
120
25
        return Status::OK();
121
25
    }
122
123
    virtual Status do_merge_input_rowsets(
124
            const std::vector<RowsetReaderSharedPtr>& input_rs_readers,
125
            MergeInputRowsetsResult* result);
126
127
25
    virtual void update_output_rowset_after_build(const MergeInputRowsetsResult& /*result*/) {}
128
129
    // Maps one segment-range merge's column-group progress into the whole compaction task.
130
    struct VerticalMergeProgressContext {
131
        int64_t total_ranges;
132
        int64_t range_index;
133
    };
134
135
    Status execute_merge(const std::vector<RowsetReaderSharedPtr>& input_rs_readers,
136
                         int64_t merge_way_num, Merger::Statistics* stats,
137
                         std::optional<std::pair<int64_t, int64_t>> segment_range = std::nullopt,
138
                         VerticalMergeProgressContext progress = {1, 0});
139
140
    // merge inverted index files
141
    Status do_inverted_index_compaction();
142
143
    // mark all columns in columns_to_do_index_compaction to skip index compaction next time.
144
    void mark_skip_index_compaction(const RowsetWriterContext& context,
145
                                    const std::function<void(int64_t, int64_t)>& error_handler);
146
147
    void construct_index_compaction_columns(RowsetWriterContext& ctx);
148
149
    virtual Status construct_output_rowset_writer(RowsetWriterContext& ctx) = 0;
150
151
    Status check_correctness();
152
153
    int64_t get_avg_segment_rows();
154
155
    void init_profile(const std::string& label);
156
157
    void _load_segment_to_cache();
158
159
    int64_t merge_way_num();
160
161
    virtual Status update_delete_bitmap() = 0;
162
163
    int64_t _compaction_id {0};
164
165
    void submit_profile_record(bool success, int64_t start_time_ms,
166
                               const std::string& status_msg = "");
167
168
    // the root tracker for this compaction
169
    std::shared_ptr<MemTrackerLimiter> _mem_tracker;
170
171
    BaseTabletSPtr _tablet;
172
173
    std::vector<RowsetSharedPtr> _input_rowsets;
174
    std::vector<RowsetSharedPtr> _data_input_rowsets;
175
    std::optional<int64_t> _row_binlog_ttl_cutoff_tso;
176
    std::optional<int64_t> _row_binlog_ttl_seconds;
177
    int64_t _row_binlog_ttl_reference_tso {0};
178
    int64_t _row_binlog_ttl_visible_version {std::numeric_limits<int64_t>::max()};
179
    int64_t _row_binlog_ttl_filtered_rows {0};
180
    int64_t _input_rowsets_data_size {0};
181
    int64_t _input_rowsets_index_size {0};
182
    int64_t _input_rowsets_total_size {0};
183
    int64_t _input_row_num {0};
184
    int64_t _input_num_segments {0};
185
186
    int64_t _local_read_bytes_total {};
187
    int64_t _remote_read_bytes_total {};
188
189
    int64_t _input_rowsets_cached_data_size {0};
190
    int64_t _input_rowsets_cached_index_size {0};
191
192
    Merger::Statistics _stats;
193
194
    RowsetSharedPtr _output_rowset;
195
    std::unique_ptr<RowsetWriter> _output_rs_writer;
196
197
    enum CompactionState : uint8_t { INITED = 0, SUCCESS = 1 };
198
    CompactionState _state {CompactionState::INITED};
199
200
    bool _is_vertical;
201
    bool _is_ordered_data_compaction {false};
202
    bool _trigger_quick_merge_by_binlog {false};
203
    bool _allow_delete_in_cumu_compaction;
204
    bool _enable_vertical_compact_variant_subcolumns;
205
206
    Version _output_version;
207
208
    int64_t _newest_write_timestamp {-1};
209
    std::unique_ptr<RowIdConversion> _rowid_conversion = nullptr;
210
    TabletSchemaSPtr _cur_tablet_schema;
211
212
    std::unique_ptr<RuntimeProfile> _profile;
213
214
    bool _enable_inverted_index_compaction {false};
215
216
    RuntimeProfile::Counter* _input_rowsets_data_size_counter = nullptr;
217
    RuntimeProfile::Counter* _input_rowsets_counter = nullptr;
218
    RuntimeProfile::Counter* _input_row_num_counter = nullptr;
219
    RuntimeProfile::Counter* _input_segments_num_counter = nullptr;
220
    RuntimeProfile::Counter* _merged_rows_counter = nullptr;
221
    RuntimeProfile::Counter* _filtered_rows_counter = nullptr;
222
    RuntimeProfile::Counter* _output_rowset_data_size_counter = nullptr;
223
    RuntimeProfile::Counter* _output_row_num_counter = nullptr;
224
    RuntimeProfile::Counter* _output_segments_num_counter = nullptr;
225
    RuntimeProfile::Counter* _merge_rowsets_latency_timer = nullptr;
226
};
227
228
// `StorageEngine` mixin for `Compaction`
229
class CompactionMixin : public Compaction {
230
public:
231
    CompactionMixin(StorageEngine& engine, TabletSharedPtr tablet, const std::string& label);
232
233
    ~CompactionMixin() override;
234
235
    Status execute_compact() override;
236
237
    int64_t get_compaction_permits();
238
239
0
    int64_t initiator() const { return INVALID_COMPACTION_INITIATOR_ID; }
240
241
    int64_t calc_input_rowsets_total_size() const;
242
243
    int64_t calc_input_rowsets_row_num() const;
244
245
protected:
246
    // Convert `_tablet` from `BaseTablet` to `Tablet`
247
    Tablet* tablet();
248
249
    Status construct_output_rowset_writer(RowsetWriterContext& ctx) override;
250
251
    virtual Status modify_rowsets();
252
253
    Status update_delete_bitmap() override;
254
255
    void find_longest_consecutive_version(std::vector<RowsetSharedPtr>* rowsets,
256
                                          std::vector<Version>* missing_version);
257
258
    StorageEngine& _engine;
259
260
private:
261
    Status execute_compact_impl(int64_t permits);
262
263
    Status build_basic_info(bool is_ordered_compaction = false);
264
265
    // Return true if do ordered data compaction successfully
266
    bool handle_ordered_data_compaction();
267
268
    Status do_compact_ordered_rowsets();
269
270
    bool _check_if_includes_input_rowsets(const RowsetIdUnorderedSet& commit_rowset_ids_set) const;
271
272
    void update_compaction_level();
273
274
    PendingRowsetGuard _pending_rs_guard;
275
};
276
277
class CloudCompactionMixin : public Compaction {
278
public:
279
    CloudCompactionMixin(CloudStorageEngine& engine, CloudTabletSPtr tablet,
280
                         const std::string& label);
281
282
61
    ~CloudCompactionMixin() override = default;
283
284
    Status execute_compact() override;
285
286
    int64_t initiator() const;
287
288
    int64_t num_input_rowsets() const;
289
290
protected:
291
356
    CloudTablet* cloud_tablet() { return static_cast<CloudTablet*>(_tablet.get()); }
292
293
    Status update_delete_bitmap() override;
294
295
    virtual Status garbage_collection();
296
297
    Status construct_output_rowset_writer(RowsetWriterContext& ctx) override;
298
299
    // Helper function to apply truncation and log the result
300
    // Returns the number of rowsets that were truncated
301
    size_t apply_txn_size_truncation_and_log(const std::string& compaction_name);
302
303
    // Caller must hold the tablet header lock.
304
    bool should_apply_cumulative_compaction_result(int64_t response_cumulative_compaction_cnt);
305
306
    CloudStorageEngine& _engine;
307
308
    std::string _uuid;
309
310
    int64_t _expiration = 0;
311
312
0
    virtual Status rebuild_tablet_schema() { return Status::OK(); }
313
314
private:
315
    Status set_storage_resource_from_input_rowsets(RowsetWriterContext& ctx);
316
317
    Status execute_compact_impl(int64_t permits);
318
319
    Status build_basic_info();
320
321
    virtual Status modify_rowsets();
322
323
    int64_t get_compaction_permits();
324
325
    void update_compaction_level();
326
327
    bool should_cache_compaction_output();
328
};
329
330
namespace cloud {
331
332
// Truncate rowsets based on estimated transaction metadata size
333
// Returns the number of rowsets that were truncated (removed from the end)
334
// Only considers rowset meta size (using doris_rowset_meta_to_cloud for estimation)
335
size_t truncate_rowsets_by_txn_size(std::vector<RowsetSharedPtr>& rowsets, int64_t& kept_size_bytes,
336
                                    int64_t& truncated_size_bytes);
337
338
} // namespace cloud
339
340
} // namespace doris