Coverage Report

Created: 2026-03-12 14:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/merger.cpp
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
#include "storage/merger.h"
19
20
#include <gen_cpp/olap_file.pb.h>
21
#include <gen_cpp/types.pb.h>
22
#include <stddef.h>
23
#include <unistd.h>
24
25
#include <algorithm>
26
#include <iterator>
27
#include <memory>
28
#include <mutex>
29
#include <numeric>
30
#include <ostream>
31
#include <shared_mutex>
32
#include <string>
33
#include <utility>
34
#include <vector>
35
36
#include "cloud/config.h"
37
#include "common/config.h"
38
#include "common/logging.h"
39
#include "common/status.h"
40
#include "core/block/block.h"
41
#include "storage/iterator/block_reader.h"
42
#include "storage/iterator/vertical_block_reader.h"
43
#include "storage/iterator/vertical_merge_iterator.h"
44
#include "storage/iterators.h"
45
#include "storage/olap_common.h"
46
#include "storage/olap_define.h"
47
#include "storage/rowid_conversion.h"
48
#include "storage/rowset/rowset.h"
49
#include "storage/rowset/rowset_meta.h"
50
#include "storage/rowset/rowset_writer.h"
51
#include "storage/segment/segment_writer.h"
52
#include "storage/storage_engine.h"
53
#include "storage/tablet/base_tablet.h"
54
#include "storage/tablet/tablet.h"
55
#include "storage/tablet/tablet_fwd.h"
56
#include "storage/tablet/tablet_meta.h"
57
#include "storage/tablet/tablet_reader.h"
58
#include "storage/utils.h"
59
#include "util/slice.h"
60
61
namespace doris {
62
#include "common/compile_check_begin.h"
63
Status Merger::vmerge_rowsets(BaseTabletSPtr tablet, ReaderType reader_type,
64
                              const TabletSchema& cur_tablet_schema,
65
                              const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
66
1.41k
                              RowsetWriter* dst_rowset_writer, Statistics* stats_output) {
67
1.41k
    if (!cur_tablet_schema.cluster_key_uids().empty()) {
68
0
        return Status::InternalError(
69
0
                "mow table with cluster keys does not support non vertical compaction");
70
0
    }
71
1.41k
    BlockReader reader;
72
1.41k
    TabletReader::ReaderParams reader_params;
73
1.41k
    reader_params.tablet = tablet;
74
1.41k
    reader_params.reader_type = reader_type;
75
76
1.41k
    TabletReadSource read_source;
77
1.41k
    read_source.rs_splits.reserve(src_rowset_readers.size());
78
1.52k
    for (const RowsetReaderSharedPtr& rs_reader : src_rowset_readers) {
79
1.52k
        read_source.rs_splits.emplace_back(rs_reader);
80
1.52k
    }
81
1.41k
    read_source.fill_delete_predicates();
82
1.41k
    reader_params.set_read_source(std::move(read_source));
83
84
1.41k
    reader_params.version = dst_rowset_writer->version();
85
86
1.41k
    TabletSchemaSPtr merge_tablet_schema = std::make_shared<TabletSchema>();
87
1.41k
    merge_tablet_schema->copy_from(cur_tablet_schema);
88
89
    // Merge the columns in delete predicate that not in latest schema in to current tablet schema
90
1.41k
    for (auto& del_pred_rs : reader_params.delete_predicates) {
91
24
        merge_tablet_schema->merge_dropped_columns(*del_pred_rs->tablet_schema());
92
24
    }
93
1.41k
    reader_params.tablet_schema = merge_tablet_schema;
94
1.41k
    if (!tablet->tablet_schema()->cluster_key_uids().empty()) {
95
0
        reader_params.delete_bitmap = tablet->tablet_meta()->delete_bitmap_ptr();
96
0
    }
97
98
1.41k
    if (stats_output && stats_output->rowid_conversion) {
99
48
        reader_params.record_rowids = true;
100
48
        reader_params.rowid_conversion = stats_output->rowid_conversion;
101
48
        stats_output->rowid_conversion->set_dst_rowset_id(dst_rowset_writer->rowset_id());
102
48
    }
103
104
1.41k
    reader_params.return_columns.resize(cur_tablet_schema.num_columns());
105
1.41k
    std::iota(reader_params.return_columns.begin(), reader_params.return_columns.end(), 0);
106
1.41k
    reader_params.origin_return_columns = &reader_params.return_columns;
107
1.41k
    RETURN_IF_ERROR(reader.init(reader_params));
108
109
1.41k
    Block block = cur_tablet_schema.create_block(reader_params.return_columns);
110
1.41k
    size_t output_rows = 0;
111
1.41k
    bool eof = false;
112
4.15k
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
113
2.73k
        auto tablet_state = tablet->tablet_state();
114
2.73k
        if (tablet_state != TABLET_RUNNING && tablet_state != TABLET_NOTREADY) {
115
0
            tablet->clear_cache();
116
0
            return Status::Error<INTERNAL_ERROR>("tablet {} is not used any more",
117
0
                                                 tablet->tablet_id());
118
0
        }
119
120
        // Read one block from block reader
121
2.73k
        RETURN_NOT_OK_STATUS_WITH_WARN(reader.next_block_with_aggregation(&block, &eof),
122
2.73k
                                       "failed to read next block when merging rowsets of tablet " +
123
2.73k
                                               std::to_string(tablet->tablet_id()));
124
2.73k
        RETURN_NOT_OK_STATUS_WITH_WARN(dst_rowset_writer->add_block(&block),
125
2.73k
                                       "failed to write block when merging rowsets of tablet " +
126
2.73k
                                               std::to_string(tablet->tablet_id()));
127
128
2.73k
        if (reader_params.record_rowids && block.rows() > 0) {
129
578
            std::vector<uint32_t> segment_num_rows;
130
578
            RETURN_IF_ERROR(dst_rowset_writer->get_segment_num_rows(&segment_num_rows));
131
578
            stats_output->rowid_conversion->add(reader.current_block_row_locations(),
132
578
                                                segment_num_rows);
133
578
        }
134
135
2.73k
        output_rows += block.rows();
136
2.73k
        block.clear_column_data();
137
2.73k
    }
138
1.41k
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
139
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
140
0
                                             tablet->tablet_id());
141
0
    }
142
143
1.41k
    if (stats_output != nullptr) {
144
1.41k
        stats_output->output_rows = output_rows;
145
1.41k
        stats_output->merged_rows = reader.merged_rows();
146
1.41k
        stats_output->filtered_rows = reader.filtered_rows();
147
1.41k
        stats_output->bytes_read_from_local = reader.stats().file_cache_stats.bytes_read_from_local;
148
1.41k
        stats_output->bytes_read_from_remote =
149
1.41k
                reader.stats().file_cache_stats.bytes_read_from_remote;
150
1.41k
        stats_output->cached_bytes_total = reader.stats().file_cache_stats.bytes_write_into_cache;
151
1.41k
        if (config::is_cloud_mode()) {
152
1.37k
            stats_output->cloud_local_read_time =
153
1.37k
                    reader.stats().file_cache_stats.local_io_timer / 1000;
154
1.37k
            stats_output->cloud_remote_read_time =
155
1.37k
                    reader.stats().file_cache_stats.remote_io_timer / 1000;
156
1.37k
        }
157
1.41k
    }
158
159
1.41k
    RETURN_NOT_OK_STATUS_WITH_WARN(dst_rowset_writer->flush(),
160
1.41k
                                   "failed to flush rowset when merging rowsets of tablet " +
161
1.41k
                                           std::to_string(tablet->tablet_id()));
162
163
1.41k
    return Status::OK();
164
1.41k
}
165
166
// split columns into several groups, make sure all keys in one group
167
// unique_key should consider sequence&delete column
168
void Merger::vertical_split_columns(const TabletSchema& tablet_schema,
169
                                    std::vector<std::vector<uint32_t>>* column_groups,
170
10.5k
                                    std::vector<uint32_t>* key_group_cluster_key_idxes,
171
10.5k
                                    int32_t num_columns_per_group) {
172
10.5k
    size_t num_key_cols = tablet_schema.num_key_columns();
173
10.5k
    size_t total_cols = tablet_schema.num_columns();
174
48.3k
    std::vector<uint32_t> key_columns;
175
37.7k
    for (auto i = 0; i < num_key_cols; ++i) {
176
37.7k
        key_columns.emplace_back(i);
177
    }
178
10.5k
    // in unique key, sequence & delete sign column should merge with key columns
179
10.5k
    int32_t sequence_col_idx = -1;
180
    int32_t delete_sign_idx = -1;
181
    // in key column compaction, seq_col real index is _num_key_columns
182
10.5k
    // and delete_sign column is _block->columns() - 1
183
4.36k
    if (tablet_schema.keys_type() == KeysType::UNIQUE_KEYS) {
184
205
        if (tablet_schema.has_sequence_col()) {
185
205
            sequence_col_idx = tablet_schema.sequence_col_idx();
186
205
            key_columns.emplace_back(sequence_col_idx);
187
4.36k
        }
188
4.36k
        delete_sign_idx = tablet_schema.field_index(DELETE_SIGN);
189
4.36k
        if (delete_sign_idx != -1) {
190
4.36k
            key_columns.emplace_back(delete_sign_idx);
191
4.36k
        }
192
529
        if (!tablet_schema.cluster_key_uids().empty()) {
193
529
            for (const auto& cid : tablet_schema.cluster_key_uids()) {
194
529
                auto idx = tablet_schema.field_index(cid);
195
0
                DCHECK(idx >= 0) << "could not find cluster key column with unique_id=" << cid
196
529
                                 << " in tablet schema, table_id=" << tablet_schema.table_id();
197
271
                if (idx >= num_key_cols) {
198
271
                    key_columns.emplace_back(idx);
199
529
                }
200
            }
201
            // tablet schema unique ids: [1, 2, 5, 3, 6, 4], [1 2] is key columns
202
            // cluster key unique ids: [3, 1, 4]
203
            // the key_columns should be [0, 1, 3, 5]
204
529
            // the key_group_cluster_key_idxes should be [2, 1, 3]
205
529
            for (const auto& cid : tablet_schema.cluster_key_uids()) {
206
2.98k
                auto idx = tablet_schema.field_index(cid);
207
2.98k
                for (auto i = 0; i < key_columns.size(); ++i) {
208
529
                    if (idx == key_columns[i]) {
209
529
                        key_group_cluster_key_idxes->emplace_back(i);
210
529
                        break;
211
2.98k
                    }
212
529
                }
213
185
            }
214
4.36k
        }
215
10.5k
    }
216
46
    VLOG_NOTICE << "sequence_col_idx=" << sequence_col_idx
217
                << ", delete_sign_idx=" << delete_sign_idx;
218
10.5k
    // for duplicate no keys
219
10.5k
    if (!key_columns.empty()) {
220
10.5k
        column_groups->emplace_back(key_columns);
221
    }
222
10.5k
223
    std::vector<uint32_t> value_columns;
224
94.2k
225
83.7k
    for (size_t i = num_key_cols; i < total_cols; ++i) {
226
83.7k
        if (i == sequence_col_idx || i == delete_sign_idx ||
227
4.82k
            key_columns.end() != std::find(key_columns.begin(), key_columns.end(), i)) {
228
4.82k
            continue;
229
        }
230
78.8k
231
78.8k
        if (!value_columns.empty() && value_columns.size() % num_columns_per_group == 0) {
232
9.96k
            column_groups->push_back(value_columns);
233
9.96k
            value_columns.clear();
234
9.96k
        }
235
78.8k
        value_columns.push_back(cast_set<uint32_t>(i));
236
78.8k
    }
237
238
10.5k
    if (!value_columns.empty()) {
239
9.94k
        column_groups->push_back(value_columns);
240
9.94k
    }
241
10.5k
}
242
243
Status Merger::vertical_compact_one_group(
244
        BaseTabletSPtr tablet, ReaderType reader_type, const TabletSchema& tablet_schema,
245
        bool is_key, const std::vector<uint32_t>& column_group, RowSourcesBuffer* row_source_buf,
246
        const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
247
        RowsetWriter* dst_rowset_writer, uint32_t max_rows_per_segment, Statistics* stats_output,
248
        std::vector<uint32_t> key_group_cluster_key_idxes, int64_t batch_size,
249
30.4k
        CompactionSampleInfo* sample_info, bool enable_sparse_optimization) {
250
    // build tablet reader
251
30.4k
    VLOG_NOTICE << "vertical compact one group, max_rows_per_segment=" << max_rows_per_segment;
252
30.4k
    VerticalBlockReader reader(row_source_buf);
253
30.4k
    TabletReader::ReaderParams reader_params;
254
30.4k
    reader_params.is_key_column_group = is_key;
255
30.4k
    reader_params.key_group_cluster_key_idxes = key_group_cluster_key_idxes;
256
30.4k
    reader_params.tablet = tablet;
257
30.4k
    reader_params.reader_type = reader_type;
258
30.4k
    reader_params.enable_sparse_optimization = enable_sparse_optimization;
259
260
30.4k
    TabletReadSource read_source;
261
30.4k
    read_source.rs_splits.reserve(src_rowset_readers.size());
262
221k
    for (const RowsetReaderSharedPtr& rs_reader : src_rowset_readers) {
263
221k
        read_source.rs_splits.emplace_back(rs_reader);
264
221k
    }
265
30.4k
    read_source.fill_delete_predicates();
266
30.4k
    reader_params.set_read_source(std::move(read_source));
267
268
30.4k
    reader_params.version = dst_rowset_writer->version();
269
270
30.4k
    TabletSchemaSPtr merge_tablet_schema = std::make_shared<TabletSchema>();
271
30.4k
    merge_tablet_schema->copy_from(tablet_schema);
272
273
30.4k
    for (auto& del_pred_rs : reader_params.delete_predicates) {
274
1.91k
        merge_tablet_schema->merge_dropped_columns(*del_pred_rs->tablet_schema());
275
1.91k
    }
276
277
30.4k
    reader_params.tablet_schema = merge_tablet_schema;
278
30.4k
    bool has_cluster_key = false;
279
30.4k
    if (!tablet->tablet_schema()->cluster_key_uids().empty()) {
280
504
        reader_params.delete_bitmap = tablet->tablet_meta()->delete_bitmap_ptr();
281
504
        has_cluster_key = true;
282
504
    }
283
284
30.4k
    if (is_key && stats_output && stats_output->rowid_conversion) {
285
4.81k
        reader_params.record_rowids = true;
286
4.81k
        reader_params.rowid_conversion = stats_output->rowid_conversion;
287
4.81k
        stats_output->rowid_conversion->set_dst_rowset_id(dst_rowset_writer->rowset_id());
288
4.81k
    }
289
290
30.4k
    reader_params.return_columns = column_group;
291
30.4k
    reader_params.origin_return_columns = &reader_params.return_columns;
292
30.4k
    reader_params.batch_size = batch_size;
293
30.4k
    RETURN_IF_ERROR(reader.init(reader_params, sample_info));
294
295
30.4k
    Block block = tablet_schema.create_block(reader_params.return_columns);
296
30.4k
    size_t output_rows = 0;
297
30.4k
    bool eof = false;
298
88.4k
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
299
58.0k
        auto tablet_state = tablet->tablet_state();
300
58.0k
        if (tablet_state != TABLET_RUNNING && tablet_state != TABLET_NOTREADY) {
301
0
            tablet->clear_cache();
302
0
            return Status::Error<INTERNAL_ERROR>("tablet {} is not used any more",
303
0
                                                 tablet->tablet_id());
304
0
        }
305
        // Read one block from block reader
306
58.0k
        RETURN_NOT_OK_STATUS_WITH_WARN(reader.next_block_with_aggregation(&block, &eof),
307
58.0k
                                       "failed to read next block when merging rowsets of tablet " +
308
58.0k
                                               std::to_string(tablet->tablet_id()));
309
58.0k
        RETURN_NOT_OK_STATUS_WITH_WARN(
310
58.0k
                dst_rowset_writer->add_columns(&block, column_group, is_key, max_rows_per_segment,
311
58.0k
                                               has_cluster_key),
312
58.0k
                "failed to write block when merging rowsets of tablet " +
313
58.0k
                        std::to_string(tablet->tablet_id()));
314
315
58.0k
        if (is_key && reader_params.record_rowids && block.rows() > 0) {
316
8.80k
            std::vector<uint32_t> segment_num_rows;
317
8.80k
            RETURN_IF_ERROR(dst_rowset_writer->get_segment_num_rows(&segment_num_rows));
318
8.80k
            stats_output->rowid_conversion->add(reader.current_block_row_locations(),
319
8.80k
                                                segment_num_rows);
320
8.80k
        }
321
58.0k
        output_rows += block.rows();
322
58.0k
        block.clear_column_data();
323
58.0k
    }
324
30.4k
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
325
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
326
0
                                             tablet->tablet_id());
327
0
    }
328
329
30.4k
    if (stats_output != nullptr) {
330
30.3k
        if (is_key) {
331
10.4k
            stats_output->output_rows = output_rows;
332
10.4k
            stats_output->merged_rows = reader.merged_rows();
333
10.4k
            stats_output->filtered_rows = reader.filtered_rows();
334
10.4k
        }
335
30.3k
        stats_output->bytes_read_from_local = reader.stats().file_cache_stats.bytes_read_from_local;
336
30.3k
        stats_output->bytes_read_from_remote =
337
30.3k
                reader.stats().file_cache_stats.bytes_read_from_remote;
338
30.3k
        stats_output->cached_bytes_total = reader.stats().file_cache_stats.bytes_write_into_cache;
339
30.3k
        if (config::is_cloud_mode()) {
340
29.9k
            stats_output->cloud_local_read_time =
341
29.9k
                    reader.stats().file_cache_stats.local_io_timer / 1000;
342
29.9k
            stats_output->cloud_remote_read_time =
343
29.9k
                    reader.stats().file_cache_stats.remote_io_timer / 1000;
344
29.9k
        }
345
30.3k
    }
346
30.4k
    RETURN_IF_ERROR(dst_rowset_writer->flush_columns(is_key));
347
348
30.4k
    return Status::OK();
349
30.4k
}
350
351
// for segcompaction
352
Status Merger::vertical_compact_one_group(
353
        int64_t tablet_id, ReaderType reader_type, const TabletSchema& tablet_schema, bool is_key,
354
        const std::vector<uint32_t>& column_group, RowSourcesBuffer* row_source_buf,
355
        VerticalBlockReader& src_block_reader, segment_v2::SegmentWriter& dst_segment_writer,
356
        Statistics* stats_output, uint64_t* index_size, KeyBoundsPB& key_bounds,
357
22
        SimpleRowIdConversion* rowid_conversion) {
358
    // TODO: record_rowids
359
22
    Block block = tablet_schema.create_block(column_group);
360
22
    size_t output_rows = 0;
361
22
    bool eof = false;
362
138
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
363
        // Read one block from block reader
364
116
        RETURN_NOT_OK_STATUS_WITH_WARN(src_block_reader.next_block_with_aggregation(&block, &eof),
365
116
                                       "failed to read next block when merging rowsets of tablet " +
366
116
                                               std::to_string(tablet_id));
367
116
        if (!block.rows()) {
368
0
            break;
369
0
        }
370
116
        RETURN_NOT_OK_STATUS_WITH_WARN(dst_segment_writer.append_block(&block, 0, block.rows()),
371
116
                                       "failed to write block when merging rowsets of tablet " +
372
116
                                               std::to_string(tablet_id));
373
374
116
        if (is_key && rowid_conversion != nullptr) {
375
30
            rowid_conversion->add(src_block_reader.current_block_row_locations());
376
30
        }
377
116
        output_rows += block.rows();
378
116
        block.clear_column_data();
379
116
    }
380
22
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
381
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
382
0
                                             tablet_id);
383
0
    }
384
385
22
    if (stats_output != nullptr) {
386
22
        if (is_key) {
387
11
            stats_output->output_rows = output_rows;
388
11
            stats_output->merged_rows = src_block_reader.merged_rows();
389
11
            stats_output->filtered_rows = src_block_reader.filtered_rows();
390
11
        }
391
22
        stats_output->bytes_read_from_local =
392
22
                src_block_reader.stats().file_cache_stats.bytes_read_from_local;
393
22
        stats_output->bytes_read_from_remote =
394
22
                src_block_reader.stats().file_cache_stats.bytes_read_from_remote;
395
22
        stats_output->cached_bytes_total =
396
22
                src_block_reader.stats().file_cache_stats.bytes_write_into_cache;
397
22
    }
398
399
    // segcompaction produce only one segment at once
400
22
    RETURN_IF_ERROR(dst_segment_writer.finalize_columns_data());
401
22
    RETURN_IF_ERROR(dst_segment_writer.finalize_columns_index(index_size));
402
403
22
    if (is_key) {
404
11
        Slice min_key = dst_segment_writer.min_encoded_key();
405
11
        Slice max_key = dst_segment_writer.max_encoded_key();
406
11
        DCHECK_LE(min_key.compare(max_key), 0);
407
11
        key_bounds.set_min_key(min_key.to_string());
408
11
        key_bounds.set_max_key(max_key.to_string());
409
11
    }
410
411
22
    return Status::OK();
412
22
}
413
414
int64_t estimate_batch_size(int group_index, BaseTabletSPtr tablet, int64_t way_cnt,
415
30.0k
                            ReaderType reader_type) {
416
30.0k
    auto& sample_info_lock = tablet->get_sample_info_lock(reader_type);
417
30.0k
    auto& sample_infos = tablet->get_sample_infos(reader_type);
418
30.0k
    std::unique_lock<std::mutex> lock(sample_info_lock);
419
30.0k
    CompactionSampleInfo info = sample_infos[group_index];
420
30.0k
    if (way_cnt <= 0) {
421
12.7k
        LOG(INFO) << "estimate batch size for vertical compaction, tablet id: "
422
12.7k
                  << tablet->tablet_id() << " way cnt: " << way_cnt;
423
12.7k
        return 4096 - 32;
424
12.7k
    }
425
17.2k
    int64_t block_mem_limit = config::compaction_memory_bytes_limit / way_cnt;
426
17.2k
    if (tablet->last_compaction_status.is<ErrorCode::MEM_LIMIT_EXCEEDED>()) {
427
0
        block_mem_limit /= 4;
428
0
    }
429
430
17.2k
    int64_t group_data_size = 0;
431
17.2k
    if (info.group_data_size > 0 && info.bytes > 0 && info.rows > 0) {
432
0
        double smoothing_factor = 0.5;
433
0
        group_data_size =
434
0
                int64_t((cast_set<double>(info.group_data_size) * (1 - smoothing_factor)) +
435
0
                        (cast_set<double>(info.bytes / info.rows) * smoothing_factor));
436
0
        sample_infos[group_index].group_data_size = group_data_size;
437
17.2k
    } else if (info.group_data_size > 0 && (info.bytes <= 0 || info.rows <= 0)) {
438
0
        group_data_size = info.group_data_size;
439
17.4k
    } else if (info.group_data_size <= 0 && info.bytes > 0 && info.rows > 0) {
440
9.19k
        group_data_size = info.bytes / info.rows;
441
9.19k
        sample_infos[group_index].group_data_size = group_data_size;
442
9.19k
    } else {
443
8.08k
        LOG(INFO) << "estimate batch size for vertical compaction, tablet id: "
444
8.08k
                  << tablet->tablet_id() << " group data size: " << info.group_data_size
445
8.08k
                  << " row num: " << info.rows << " consume bytes: " << info.bytes;
446
8.08k
        return 1024 - 32;
447
8.08k
    }
448
449
9.19k
    if (group_data_size <= 0) {
450
0
        LOG(WARNING) << "estimate batch size for vertical compaction, tablet id: "
451
0
                     << tablet->tablet_id() << " unexpected group data size: " << group_data_size;
452
0
        return 4096 - 32;
453
0
    }
454
455
9.19k
    sample_infos[group_index].bytes = 0;
456
9.19k
    sample_infos[group_index].rows = 0;
457
458
9.19k
    int64_t batch_size = block_mem_limit / group_data_size;
459
9.19k
    int64_t res = std::max(std::min(batch_size, int64_t(4096 - 32)), int64_t(32L));
460
9.19k
    LOG(INFO) << "estimate batch size for vertical compaction, tablet id: " << tablet->tablet_id()
461
9.19k
              << " group data size: " << info.group_data_size << " row num: " << info.rows
462
9.19k
              << " consume bytes: " << info.bytes << " way cnt: " << way_cnt
463
9.19k
              << " batch size: " << res;
464
9.19k
    return res;
465
9.19k
}
466
467
// steps to do vertical merge:
468
// 1. split columns into column groups
469
// 2. compact groups one by one, generate a row_source_buf when compact key group
470
// and use this row_source_buf to compact value column groups
471
// 3. build output rowset
472
Status Merger::vertical_merge_rowsets(BaseTabletSPtr tablet, ReaderType reader_type,
473
                                      const TabletSchema& tablet_schema,
474
                                      const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
475
                                      RowsetWriter* dst_rowset_writer,
476
                                      uint32_t max_rows_per_segment, int64_t merge_way_num,
477
10.4k
                                      Statistics* stats_output) {
478
10.4k
    LOG(INFO) << "Start to do vertical compaction, tablet_id: " << tablet->tablet_id();
479
10.4k
    std::vector<std::vector<uint32_t>> column_groups;
480
10.4k
    std::vector<uint32_t> key_group_cluster_key_idxes;
481
10.4k
    // If BE config vertical_compaction_num_columns_per_group has been modified from
482
    // its default value (5), use the BE config; otherwise use the tablet meta value.
483
    constexpr int32_t default_num_columns_per_group = 5;
484
10.4k
    int32_t num_columns_per_group =
485
76.7k
            config::vertical_compaction_num_columns_per_group != default_num_columns_per_group
486
76.7k
                    ? config::vertical_compaction_num_columns_per_group
487
76.7k
                    : tablet->tablet_meta()->vertical_compaction_num_columns_per_group();
488
489
    DBUG_EXECUTE_IF("Merger.vertical_merge_rowsets.check_num_columns_per_group", {
490
        auto expected_value = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
491
                "Merger.vertical_merge_rowsets.check_num_columns_per_group", "expected_value", -1);
492
        auto expected_tablet_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
493
10.4k
                "Merger.vertical_merge_rowsets.check_num_columns_per_group", "tablet_id", -1);
494
10.4k
        if (expected_tablet_id != -1 && expected_tablet_id == tablet->tablet_id()) {
495
10.5k
            if (expected_value != -1 && expected_value != num_columns_per_group) {
496
4.35k
                LOG(FATAL) << "DEBUG_POINT CHECK FAILED: expected num_columns_per_group="
497
4.35k
                           << expected_value << " but got " << num_columns_per_group
498
                           << " for tablet_id=" << tablet->tablet_id();
499
4.35k
            } else {
500
4.35k
                LOG(INFO) << "DEBUG_POINT CHECK PASSED: num_columns_per_group="
501
4.35k
                          << num_columns_per_group << ", tablet_id=" << tablet->tablet_id();
502
4.35k
            }
503
4.35k
        }
504
4.35k
    });
505
4.35k
506
4.35k
    vertical_split_columns(tablet_schema, &column_groups, &key_group_cluster_key_idxes,
507
                           num_columns_per_group);
508
10.4k
509
10.4k
    // Calculate total rows for density calculation after compaction
510
10.4k
    int64_t total_rows = 0;
511
10.5k
    for (const auto& rs_reader : src_rowset_readers) {
512
10.5k
        total_rows += rs_reader->rowset()->rowset_meta()->num_rows();
513
10.5k
    }
514
10.4k
515
10.4k
    // Use historical density for sparse wide table optimization
516
10.4k
    // density = (total_cells - null_cells) / total_cells, smaller means more sparse
517
10.4k
    // When density <= threshold, enable sparse optimization
518
10.4k
    // threshold = 0 means disable, 1 means always enable (default)
519
10.4k
    bool enable_sparse_optimization = false;
520
    if (config::sparse_column_compaction_threshold_percent > 0 &&
521
40.7k
        tablet->keys_type() == KeysType::UNIQUE_KEYS) {
522
30.3k
        double density = tablet->compaction_density.load();
523
30.3k
        enable_sparse_optimization = density <= config::sparse_column_compaction_threshold_percent;
524
30.3k
525
30.3k
        LOG(INFO) << "Vertical compaction sparse optimization check: tablet_id="
526
30.3k
                  << tablet->tablet_id() << ", density=" << density
527
30.3k
                  << ", threshold=" << config::sparse_column_compaction_threshold_percent
528
30.3k
                  << ", total_rows=" << total_rows
529
30.3k
                  << ", num_columns=" << tablet_schema.num_columns()
530
18.4E
                  << ", total_cells=" << total_rows * tablet_schema.num_columns()
531
30.3k
                  << ", enable_sparse_optimization=" << enable_sparse_optimization;
532
30.3k
    }
533
30.3k
534
30.3k
    RowSourcesBuffer row_sources_buf(tablet->tablet_id(), dst_rowset_writer->context().tablet_path,
535
30.3k
                                     reader_type);
536
30.3k
    Merger::Statistics total_stats;
537
30.3k
    if (stats_output != nullptr) {
538
30.3k
        total_stats.rowid_conversion = stats_output->rowid_conversion;
539
30.3k
    }
540
30.3k
    auto& sample_info_lock = tablet->get_sample_info_lock(reader_type);
541
30.3k
    auto& sample_infos = tablet->get_sample_infos(reader_type);
542
30.3k
    {
543
30.3k
        std::unique_lock<std::mutex> lock(sample_info_lock);
544
30.3k
        sample_infos.resize(column_groups.size());
545
30.3k
    }
546
30.3k
    // compact group one by one
547
10.4k
    for (auto i = 0; i < column_groups.size(); ++i) {
548
10.4k
        VLOG_NOTICE << "row source size: " << row_sources_buf.total_size();
549
10.4k
        bool is_key = (i == 0);
550
10.4k
        int64_t batch_size = config::compaction_batch_size != -1
551
10.4k
                                     ? config::compaction_batch_size
552
30.3k
                                     : estimate_batch_size(i, tablet, merge_way_num, reader_type);
553
30.3k
        CompactionSampleInfo sample_info;
554
10.4k
        Merger::Statistics group_stats;
555
10.4k
        group_stats.rowid_conversion = total_stats.rowid_conversion;
556
30.3k
        Merger::Statistics* group_stats_ptr = stats_output != nullptr ? &group_stats : nullptr;
557
30.3k
        Status st = vertical_compact_one_group(
558
                tablet, reader_type, tablet_schema, is_key, column_groups[i], &row_sources_buf,
559
                src_rowset_readers, dst_rowset_writer, max_rows_per_segment, group_stats_ptr,
560
                key_group_cluster_key_idxes, batch_size, &sample_info, enable_sparse_optimization);
561
        {
562
10.4k
            std::unique_lock<std::mutex> lock(sample_info_lock);
563
10.4k
            sample_infos[i] = sample_info;
564
10.4k
        }
565
30.4k
        RETURN_IF_ERROR(st);
566
30.4k
        if (stats_output != nullptr) {
567
30.4k
            total_stats.bytes_read_from_local += group_stats.bytes_read_from_local;
568
10.4k
            total_stats.bytes_read_from_remote += group_stats.bytes_read_from_remote;
569
10.4k
            total_stats.cached_bytes_total += group_stats.cached_bytes_total;
570
6.12k
            total_stats.cloud_local_read_time += group_stats.cloud_local_read_time;
571
6.12k
            total_stats.cloud_remote_read_time += group_stats.cloud_remote_read_time;
572
6.12k
            if (is_key) {
573
6.12k
                total_stats.output_rows = group_stats.output_rows;
574
6.12k
                total_stats.merged_rows = group_stats.merged_rows;
575
6.12k
                total_stats.filtered_rows = group_stats.filtered_rows;
576
6.12k
                total_stats.rowid_conversion = group_stats.rowid_conversion;
577
10.4k
            }
578
        }
579
        if (is_key) {
580
18.4E
            RETURN_IF_ERROR(row_sources_buf.flush());
581
10.4k
        }
582
        RETURN_IF_ERROR(row_sources_buf.seek_to_begin());
583
10.4k
    }
584
10.4k
585
10.4k
    // Calculate and store density for next compaction's sparse optimization threshold
586
    // density = (total_cells - total_null_count) / total_cells
587
10.4k
    // Smaller density means more sparse
588
10.4k
    {
589
        std::unique_lock<std::mutex> lock(sample_info_lock);
590
        int64_t total_null_count = 0;
591
        for (const auto& info : sample_infos) {
592
            total_null_count += info.null_count;
593
        }
594
        int64_t total_cells = total_rows * tablet_schema.num_columns();
595
        if (total_cells > 0) {
596
            double density = static_cast<double>(total_cells - total_null_count) /
597
                             static_cast<double>(total_cells);
598
            tablet->compaction_density.store(density);
599
            LOG(INFO) << "Vertical compaction density update: tablet_id=" << tablet->tablet_id()
600
                      << ", total_cells=" << total_cells
601
                      << ", total_null_count=" << total_null_count << ", density=" << density;
602
        }
603
    }
604
605
    // finish compact, build output rowset
606
    VLOG_NOTICE << "finish compact groups";
607
    RETURN_IF_ERROR(dst_rowset_writer->final_flush());
608
609
    if (stats_output != nullptr) {
610
        *stats_output = total_stats;
611
    }
612
613
    return Status::OK();
614
}
615
#include "common/compile_check_end.h"
616
} // namespace doris