Coverage Report

Created: 2026-11-03 11:16

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