Coverage Report

Created: 2026-10-30 14:20

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