Coverage Report

Created: 2026-10-12 19:06

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
    struct MergeInputRowsetsContext {
114
        MergeInputRowsetsResult result;
115
        std::vector<RowsetReaderSharedPtr> input_rs_readers;
116
    };
117
118
    Status merge_input_rowsets();
119
120
    Status prepare_merge_input_rowsets_execution(MergeInputRowsetsContext* context);
121
122
    Status execute_merge_input_rowsets(MergeInputRowsetsContext* context);
123
124
    Status finish_merge_input_rowsets_execution(MergeInputRowsetsContext* context);
125
    void snapshot_row_binlog_ttl();
126
    bool pick_expired_row_binlog_rowset(const std::vector<RowsetSharedPtr>& candidates);
127
    void filter_row_binlog_ttl_rowsets();
128
129
35
    virtual Status prepare_merge_input_rowsets(MergeInputRowsetsResult* /*result*/) {
130
35
        return Status::OK();
131
35
    }
132
133
    virtual Status do_merge_input_rowsets(
134
            const std::vector<RowsetReaderSharedPtr>& input_rs_readers,
135
            MergeInputRowsetsResult* result);
136
137
35
    virtual void update_output_rowset_after_build(const MergeInputRowsetsResult& /*result*/) {}
138
139
    // Maps one segment-range merge's column-group progress into the whole compaction task.
140
    struct VerticalMergeProgressContext {
141
        int64_t total_ranges;
142
        int64_t range_index;
143
    };
144
145
    Status execute_merge(const std::vector<RowsetReaderSharedPtr>& input_rs_readers,
146
                         int64_t merge_way_num, Merger::Statistics* stats,
147
                         std::optional<std::pair<int64_t, int64_t>> segment_range = std::nullopt,
148
                         VerticalMergeProgressContext progress = {1, 0});
149
150
    // merge inverted index files
151
    Status do_inverted_index_compaction();
152
153
    // mark all columns in columns_to_do_index_compaction to skip index compaction next time.
154
    void mark_skip_index_compaction(const RowsetWriterContext& context,
155
                                    const std::function<void(int64_t, int64_t)>& error_handler);
156
157
    void construct_index_compaction_columns(RowsetWriterContext& ctx);
158
159
    virtual Status construct_output_rowset_writer(RowsetWriterContext& ctx) = 0;
160
161
    Status check_correctness();
162
163
    int64_t get_avg_segment_rows();
164
165
    void init_profile(const std::string& label);
166
167
    void _load_segment_to_cache();
168
169
    int64_t merge_way_num();
170
171
    virtual Status update_delete_bitmap() = 0;
172
173
    int64_t _compaction_id {0};
174
175
    void submit_profile_record(bool success, int64_t start_time_ms,
176
                               const std::string& status_msg = "");
177
178
    // the root tracker for this compaction
179
    std::shared_ptr<MemTrackerLimiter> _mem_tracker;
180
181
    BaseTabletSPtr _tablet;
182
183
    std::vector<RowsetSharedPtr> _input_rowsets;
184
    std::vector<RowsetSharedPtr> _data_input_rowsets;
185
    int64_t _row_binlog_ttl_cutoff_tso {-1};
186
    int64_t _row_binlog_ttl_seconds {0};
187
    int64_t _row_binlog_ttl_visible_version {std::numeric_limits<int64_t>::max()};
188
    int64_t _row_binlog_ttl_filtered_rows {0};
189
    int64_t _input_rowsets_data_size {0};
190
    int64_t _input_rowsets_index_size {0};
191
    int64_t _input_rowsets_total_size {0};
192
    int64_t _input_row_num {0};
193
    int64_t _input_num_segments {0};
194
195
    int64_t _local_read_bytes_total {};
196
    int64_t _remote_read_bytes_total {};
197
198
    int64_t _input_rowsets_cached_data_size {0};
199
    int64_t _input_rowsets_cached_index_size {0};
200
201
    Merger::Statistics _stats;
202
203
    RowsetSharedPtr _output_rowset;
204
    std::unique_ptr<RowsetWriter> _output_rs_writer;
205
206
    enum CompactionState : uint8_t { INITED = 0, SUCCESS = 1 };
207
    CompactionState _state {CompactionState::INITED};
208
209
    bool _is_vertical;
210
    bool _is_ordered_data_compaction {false};
211
    bool _trigger_quick_merge_by_binlog {false};
212
    bool _allow_delete_in_cumu_compaction;
213
    bool _enable_vertical_compact_variant_subcolumns;
214
215
    Version _output_version;
216
217
    int64_t _newest_write_timestamp {-1};
218
    std::unique_ptr<RowIdConversion> _rowid_conversion = nullptr;
219
    TabletSchemaSPtr _cur_tablet_schema;
220
    // The variant path layout of _cur_tablet_schema; empty unless it is an extended schema.
221
    VariantCompactionPathsSPtr _cur_variant_compaction_paths;
222
223
    std::unique_ptr<RuntimeProfile> _profile;
224
225
    bool _enable_inverted_index_compaction {false};
226
227
    RuntimeProfile::Counter* _input_rowsets_data_size_counter = nullptr;
228
    RuntimeProfile::Counter* _input_rowsets_counter = nullptr;
229
    RuntimeProfile::Counter* _input_row_num_counter = nullptr;
230
    RuntimeProfile::Counter* _input_segments_num_counter = nullptr;
231
    RuntimeProfile::Counter* _merged_rows_counter = nullptr;
232
    RuntimeProfile::Counter* _filtered_rows_counter = nullptr;
233
    RuntimeProfile::Counter* _output_rowset_data_size_counter = nullptr;
234
    RuntimeProfile::Counter* _output_row_num_counter = nullptr;
235
    RuntimeProfile::Counter* _output_segments_num_counter = nullptr;
236
    RuntimeProfile::Counter* _merge_rowsets_latency_timer = nullptr;
237
};
238
239
// `StorageEngine` mixin for `Compaction`
240
class CompactionMixin : public Compaction {
241
public:
242
    CompactionMixin(StorageEngine& engine, TabletSharedPtr tablet, const std::string& label);
243
244
    ~CompactionMixin() override;
245
246
    Status execute_compact() override;
247
248
    int64_t get_compaction_permits();
249
250
0
    int64_t initiator() const { return INVALID_COMPACTION_INITIATOR_ID; }
251
252
    int64_t calc_input_rowsets_total_size() const;
253
254
    int64_t calc_input_rowsets_row_num() const;
255
256
protected:
257
    // Convert `_tablet` from `BaseTablet` to `Tablet`
258
    Tablet* tablet();
259
260
    Status construct_output_rowset_writer(RowsetWriterContext& ctx) override;
261
262
    virtual Status modify_rowsets();
263
264
    Status update_delete_bitmap() override;
265
266
    void find_longest_consecutive_version(std::vector<RowsetSharedPtr>* rowsets,
267
                                          std::vector<Version>* missing_version);
268
269
    StorageEngine& _engine;
270
271
private:
272
    Status execute_compact_impl(int64_t permits);
273
274
    Status build_basic_info(bool is_ordered_compaction = false);
275
276
    // Return true if do ordered data compaction successfully
277
    bool handle_ordered_data_compaction();
278
279
    Status do_compact_ordered_rowsets();
280
281
    bool _check_if_includes_input_rowsets(const RowsetIdUnorderedSet& commit_rowset_ids_set) const;
282
283
    void update_compaction_level();
284
285
    PendingRowsetGuard _pending_rs_guard;
286
};
287
288
class CloudCompactionMixin : public Compaction {
289
public:
290
    CloudCompactionMixin(CloudStorageEngine& engine, CloudTabletSPtr tablet,
291
                         const std::string& label);
292
293
61
    ~CloudCompactionMixin() override = default;
294
295
    Status execute_compact() override;
296
297
    int64_t initiator() const;
298
299
    int64_t num_input_rowsets() const;
300
301
protected:
302
356
    CloudTablet* cloud_tablet() { return static_cast<CloudTablet*>(_tablet.get()); }
303
304
    Status update_delete_bitmap() override;
305
306
    virtual Status garbage_collection();
307
308
    Status construct_output_rowset_writer(RowsetWriterContext& ctx) override;
309
310
    // Helper function to apply truncation and log the result
311
    // Returns the number of rowsets that were truncated
312
    size_t apply_txn_size_truncation_and_log(const std::string& compaction_name);
313
314
    // Caller must hold the tablet header lock.
315
    bool should_apply_cumulative_compaction_result(int64_t response_cumulative_compaction_cnt);
316
317
    Status prepare_execute_compact(int64_t permits);
318
319
    Status finish_execute_compact(int64_t execution_start_time_us);
320
321
    int64_t get_compaction_permits();
322
323
    CloudStorageEngine& _engine;
324
325
    std::string _uuid;
326
327
    int64_t _expiration = 0;
328
329
0
    virtual Status rebuild_tablet_schema() { return Status::OK(); }
330
331
private:
332
    Status set_storage_resource_from_input_rowsets(RowsetWriterContext& ctx);
333
334
    Status execute_compact_impl(int64_t permits);
335
336
    Status build_basic_info();
337
338
    virtual Status modify_rowsets();
339
340
    void update_compaction_level();
341
342
    bool should_cache_compaction_output();
343
};
344
345
namespace cloud {
346
347
// Truncate rowsets based on estimated transaction metadata size
348
// Returns the number of rowsets that were truncated (removed from the end)
349
// Only considers rowset meta size (using doris_rowset_meta_to_cloud for estimation)
350
size_t truncate_rowsets_by_txn_size(std::vector<RowsetSharedPtr>& rowsets, int64_t& kept_size_bytes,
351
                                    int64_t& truncated_size_bytes);
352
353
} // namespace cloud
354
355
} // namespace doris