Coverage Report

Created: 2026-08-24 11:39

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