Coverage Report

Created: 2026-10-16 15:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/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 <unordered_map>
34
#include <utility>
35
#include <vector>
36
37
#include "cloud/config.h"
38
#include "common/config.h"
39
#include "common/logging.h"
40
#include "common/status.h"
41
#include "core/block/block.h"
42
#include "storage/iterator/block_reader.h"
43
#include "storage/iterator/vertical_block_reader.h"
44
#include "storage/iterator/vertical_merge_iterator.h"
45
#include "storage/iterators.h"
46
#include "storage/olap_common.h"
47
#include "storage/olap_define.h"
48
#include "storage/rowid_conversion.h"
49
#include "storage/rowset/beta_rowset.h"
50
#include "storage/rowset/rowset.h"
51
#include "storage/rowset/rowset_meta.h"
52
#include "storage/rowset/rowset_writer.h"
53
#include "storage/segment/segment.h"
54
#include "storage/segment/segment_writer.h"
55
#include "storage/storage_engine.h"
56
#include "storage/tablet/base_tablet.h"
57
#include "storage/tablet/tablet.h"
58
#include "storage/tablet/tablet_fwd.h"
59
#include "storage/tablet/tablet_meta.h"
60
#include "storage/tablet/tablet_reader.h"
61
#include "storage/types.h"
62
#include "storage/utils.h"
63
#include "util/defer_op.h"
64
#include "util/slice.h"
65
66
namespace doris {
67
#include "common/compile_check_begin.h"
68
Status Merger::vmerge_rowsets(BaseTabletSPtr tablet, ReaderType reader_type,
69
                              const TabletSchema& cur_tablet_schema,
70
                              const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
71
                              RowsetWriter* dst_rowset_writer, Statistics* stats_output,
72
51
                              std::optional<std::pair<int64_t, int64_t>> segment_range) {
73
51
    if (!cur_tablet_schema.cluster_key_uids().empty()) {
74
0
        return Status::InternalError(
75
0
                "mow table with cluster keys does not support non vertical compaction");
76
0
    }
77
51
    BlockReader reader;
78
51
    TabletReader::ReaderParams reader_params;
79
51
    reader_params.tablet = tablet;
80
51
    reader_params.reader_type = reader_type;
81
82
51
    TabletReadSource read_source;
83
51
    read_source.rs_splits.reserve(src_rowset_readers.size());
84
147
    for (const RowsetReaderSharedPtr& rs_reader : src_rowset_readers) {
85
147
        auto& rs_split = read_source.rs_splits.emplace_back(rs_reader);
86
147
        if (segment_range.has_value()) {
87
3
            DCHECK_EQ(src_rowset_readers.size(), 1);
88
3
            rs_split.segment_offsets = segment_range.value();
89
3
        }
90
147
    }
91
51
    read_source.fill_delete_predicates();
92
51
    reader_params.set_read_source(std::move(read_source));
93
94
51
    reader_params.version = dst_rowset_writer->version();
95
96
51
    TabletSchemaSPtr merge_tablet_schema = std::make_shared<TabletSchema>();
97
51
    merge_tablet_schema->copy_from(cur_tablet_schema);
98
99
    // Merge the columns in delete predicate that not in latest schema in to current tablet schema
100
51
    for (auto& del_pred_rs : reader_params.delete_predicates) {
101
24
        merge_tablet_schema->merge_dropped_columns(*del_pred_rs->tablet_schema());
102
24
    }
103
51
    reader_params.tablet_schema = merge_tablet_schema;
104
51
    if (!tablet->tablet_schema()->cluster_key_uids().empty()) {
105
0
        reader_params.delete_bitmap = tablet->tablet_meta()->delete_bitmap_ptr();
106
0
    }
107
108
51
    if (stats_output && stats_output->rowid_conversion) {
109
51
        reader_params.record_rowids = true;
110
51
        reader_params.rowid_conversion = stats_output->rowid_conversion;
111
51
        stats_output->rowid_conversion->set_dst_rowset_id(dst_rowset_writer->rowset_id());
112
51
    }
113
114
51
    reader_params.return_columns.resize(cur_tablet_schema.num_columns());
115
51
    std::iota(reader_params.return_columns.begin(), reader_params.return_columns.end(), 0);
116
51
    reader_params.origin_return_columns = &reader_params.return_columns;
117
51
    RETURN_IF_ERROR(reader.init(reader_params));
118
119
51
    Block block = cur_tablet_schema.create_block(reader_params.return_columns);
120
51
    size_t output_rows = 0;
121
51
    bool eof = false;
122
637
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
123
586
        auto tablet_state = tablet->tablet_state();
124
586
        if (tablet_state != TABLET_RUNNING && tablet_state != TABLET_NOTREADY) {
125
0
            tablet->clear_cache();
126
0
            return Status::Error<INTERNAL_ERROR>("tablet {} is not used any more",
127
0
                                                 tablet->tablet_id());
128
0
        }
129
130
        // Read one block from block reader
131
586
        RETURN_NOT_OK_STATUS_WITH_WARN(reader.next_block_with_aggregation(&block, &eof),
132
586
                                       "failed to read next block when merging rowsets of tablet " +
133
586
                                               std::to_string(tablet->tablet_id()));
134
586
        RETURN_NOT_OK_STATUS_WITH_WARN(dst_rowset_writer->add_block(&block),
135
586
                                       "failed to write block when merging rowsets of tablet " +
136
586
                                               std::to_string(tablet->tablet_id()));
137
138
586
        if (reader_params.record_rowids && block.rows() > 0) {
139
586
            std::vector<uint32_t> segment_num_rows;
140
586
            RETURN_IF_ERROR(dst_rowset_writer->get_segment_num_rows(&segment_num_rows));
141
586
            stats_output->rowid_conversion->add(reader.current_block_row_locations(),
142
586
                                                segment_num_rows);
143
586
        }
144
145
586
        output_rows += block.rows();
146
586
        block.clear_column_data();
147
586
    }
148
51
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
149
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
150
0
                                             tablet->tablet_id());
151
0
    }
152
153
51
    if (stats_output != nullptr) {
154
51
        stats_output->output_rows = output_rows;
155
51
        stats_output->merged_rows = reader.merged_rows();
156
51
        stats_output->filtered_rows = reader.filtered_rows();
157
51
        stats_output->bytes_read_from_local = reader.stats().file_cache_stats.bytes_read_from_local;
158
51
        stats_output->bytes_read_from_remote =
159
51
                reader.stats().file_cache_stats.bytes_read_from_remote;
160
51
        stats_output->cached_bytes_total = reader.stats().file_cache_stats.bytes_write_into_cache;
161
51
        if (config::is_cloud_mode()) {
162
0
            stats_output->cloud_local_read_time =
163
0
                    reader.stats().file_cache_stats.local_io_timer / 1000;
164
0
            stats_output->cloud_remote_read_time =
165
0
                    reader.stats().file_cache_stats.remote_io_timer / 1000;
166
0
        }
167
51
    }
168
169
51
    RETURN_NOT_OK_STATUS_WITH_WARN(dst_rowset_writer->flush(),
170
51
                                   "failed to flush rowset when merging rowsets of tablet " +
171
51
                                           std::to_string(tablet->tablet_id()));
172
173
51
    return Status::OK();
174
51
}
175
176
// split columns into several groups, make sure all keys in one group
177
// unique_key should consider sequence&delete column
178
void Merger::vertical_split_columns(const TabletSchema& tablet_schema,
179
                                    std::vector<std::vector<uint32_t>>* column_groups,
180
                                    std::vector<uint32_t>* key_group_cluster_key_idxes,
181
141
                                    int32_t num_columns_per_group) {
182
141
    size_t num_key_cols = tablet_schema.num_key_columns();
183
141
    size_t total_cols = tablet_schema.num_columns();
184
141
    std::vector<uint32_t> key_columns;
185
270
    for (auto i = 0; i < num_key_cols; ++i) {
186
129
        key_columns.emplace_back(i);
187
129
    }
188
    // in unique key, sequence & delete sign column should merge with key columns
189
141
    int32_t sequence_col_idx = -1;
190
141
    int32_t delete_sign_idx = -1;
191
    // in key column compaction, seq_col real index is _num_key_columns
192
    // and delete_sign column is _block->columns() - 1
193
141
    if (tablet_schema.keys_type() == KeysType::UNIQUE_KEYS) {
194
61
        if (tablet_schema.has_sequence_col()) {
195
5
            sequence_col_idx = tablet_schema.sequence_col_idx();
196
5
            key_columns.emplace_back(sequence_col_idx);
197
5
        }
198
61
        delete_sign_idx = tablet_schema.field_index(DELETE_SIGN);
199
61
        if (delete_sign_idx != -1) {
200
54
            key_columns.emplace_back(delete_sign_idx);
201
54
        }
202
61
        if (!tablet_schema.cluster_key_uids().empty()) {
203
1
            for (const auto& cid : tablet_schema.cluster_key_uids()) {
204
1
                auto idx = tablet_schema.field_index(cid);
205
1
                DCHECK(idx >= 0) << "could not find cluster key column with unique_id=" << cid
206
0
                                 << " in tablet schema, table_id=" << tablet_schema.table_id();
207
1
                if (idx >= num_key_cols) {
208
1
                    key_columns.emplace_back(idx);
209
1
                }
210
1
            }
211
            // tablet schema unique ids: [1, 2, 5, 3, 6, 4], [1 2] is key columns
212
            // cluster key unique ids: [3, 1, 4]
213
            // the key_columns should be [0, 1, 3, 5]
214
            // the key_group_cluster_key_idxes should be [2, 1, 3]
215
1
            for (const auto& cid : tablet_schema.cluster_key_uids()) {
216
1
                auto idx = tablet_schema.field_index(cid);
217
3
                for (auto i = 0; i < key_columns.size(); ++i) {
218
3
                    if (idx == key_columns[i]) {
219
1
                        key_group_cluster_key_idxes->emplace_back(i);
220
1
                        break;
221
1
                    }
222
3
                }
223
1
            }
224
1
        }
225
61
    }
226
141
    VLOG_NOTICE << "sequence_col_idx=" << sequence_col_idx
227
73
                << ", delete_sign_idx=" << delete_sign_idx;
228
    // for duplicate no keys
229
141
    if (!key_columns.empty()) {
230
116
        column_groups->emplace_back(key_columns);
231
116
    }
232
233
141
    std::vector<uint32_t> value_columns;
234
235
1.19k
    for (size_t i = num_key_cols; i < total_cols; ++i) {
236
1.05k
        if (i == sequence_col_idx || i == delete_sign_idx ||
237
1.05k
            key_columns.end() != std::find(key_columns.begin(), key_columns.end(), i)) {
238
60
            continue;
239
60
        }
240
241
992
        if (!value_columns.empty() && value_columns.size() % num_columns_per_group == 0) {
242
143
            column_groups->push_back(value_columns);
243
143
            value_columns.clear();
244
143
        }
245
992
        value_columns.push_back(cast_set<uint32_t>(i));
246
992
    }
247
248
141
    if (!value_columns.empty()) {
249
140
        column_groups->push_back(value_columns);
250
140
    }
251
141
}
252
253
Status Merger::vertical_compact_one_group(
254
        BaseTabletSPtr tablet, ReaderType reader_type, const TabletSchema& tablet_schema,
255
        bool is_key, const std::vector<uint32_t>& column_group, RowSourcesBuffer* row_source_buf,
256
        const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
257
        RowsetWriter* dst_rowset_writer, uint32_t max_rows_per_segment, Statistics* stats_output,
258
        std::vector<uint32_t> key_group_cluster_key_idxes, int64_t batch_size,
259
        CompactionSampleInfo* sample_info, VerticalCompactionContextStats* context_stats,
260
371
        bool enable_sparse_optimization, std::optional<std::pair<int64_t, int64_t>> segment_range) {
261
    // build tablet reader
262
371
    VLOG_NOTICE << "vertical compact one group, max_rows_per_segment=" << max_rows_per_segment;
263
371
    VerticalBlockReader reader(row_source_buf, context_stats);
264
371
    TabletReader::ReaderParams reader_params;
265
371
    reader_params.is_key_column_group = is_key;
266
371
    reader_params.key_group_cluster_key_idxes = key_group_cluster_key_idxes;
267
371
    reader_params.tablet = tablet;
268
371
    reader_params.reader_type = reader_type;
269
371
    reader_params.enable_sparse_optimization = enable_sparse_optimization;
270
271
371
    TabletReadSource read_source;
272
371
    read_source.rs_splits.reserve(src_rowset_readers.size());
273
1.13k
    for (const RowsetReaderSharedPtr& rs_reader : src_rowset_readers) {
274
1.13k
        auto& rs_split = read_source.rs_splits.emplace_back(rs_reader);
275
1.13k
        if (segment_range.has_value()) {
276
8
            DCHECK_EQ(src_rowset_readers.size(), 1);
277
8
            rs_split.segment_offsets = segment_range.value();
278
8
        }
279
1.13k
    }
280
371
    read_source.fill_delete_predicates();
281
371
    reader_params.set_read_source(std::move(read_source));
282
283
371
    reader_params.version = dst_rowset_writer->version();
284
285
371
    TabletSchemaSPtr merge_tablet_schema = std::make_shared<TabletSchema>();
286
371
    merge_tablet_schema->copy_from(tablet_schema);
287
288
371
    for (auto& del_pred_rs : reader_params.delete_predicates) {
289
125
        merge_tablet_schema->merge_dropped_columns(*del_pred_rs->tablet_schema());
290
125
    }
291
292
371
    reader_params.tablet_schema = merge_tablet_schema;
293
371
    bool has_cluster_key = false;
294
371
    if (!tablet->tablet_schema()->cluster_key_uids().empty()) {
295
1
        reader_params.delete_bitmap = tablet->tablet_meta()->delete_bitmap_ptr();
296
1
        has_cluster_key = true;
297
1
    }
298
299
371
    if (is_key && stats_output && stats_output->rowid_conversion) {
300
97
        reader_params.record_rowids = true;
301
97
        reader_params.rowid_conversion = stats_output->rowid_conversion;
302
97
        stats_output->rowid_conversion->set_dst_rowset_id(dst_rowset_writer->rowset_id());
303
97
    }
304
305
371
    reader_params.return_columns = column_group;
306
371
    reader_params.origin_return_columns = &reader_params.return_columns;
307
371
    reader_params.batch_size = batch_size;
308
371
    RETURN_IF_ERROR(reader.init(reader_params, sample_info));
309
310
370
    Block block = tablet_schema.create_block(reader_params.return_columns);
311
370
    size_t output_rows = 0;
312
370
    bool eof = false;
313
6.70k
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
314
6.33k
        auto tablet_state = tablet->tablet_state();
315
6.33k
        if (tablet_state != TABLET_RUNNING && tablet_state != TABLET_NOTREADY) {
316
0
            tablet->clear_cache();
317
0
            return Status::Error<INTERNAL_ERROR>("tablet {} is not used any more",
318
0
                                                 tablet->tablet_id());
319
0
        }
320
        // Read one block from block reader
321
6.33k
        RETURN_NOT_OK_STATUS_WITH_WARN(reader.next_block_with_aggregation(&block, &eof),
322
6.33k
                                       "failed to read next block when merging rowsets of tablet " +
323
6.33k
                                               std::to_string(tablet->tablet_id()));
324
6.33k
        RETURN_NOT_OK_STATUS_WITH_WARN(
325
6.33k
                dst_rowset_writer->add_columns(&block, column_group, is_key, max_rows_per_segment,
326
6.33k
                                               has_cluster_key),
327
6.33k
                "failed to write block when merging rowsets of tablet " +
328
6.33k
                        std::to_string(tablet->tablet_id()));
329
330
6.33k
        if (is_key && reader_params.record_rowids && block.rows() > 0) {
331
1.19k
            std::vector<uint32_t> segment_num_rows;
332
1.19k
            RETURN_IF_ERROR(dst_rowset_writer->get_segment_num_rows(&segment_num_rows));
333
1.19k
            stats_output->rowid_conversion->add(reader.current_block_row_locations(),
334
1.19k
                                                segment_num_rows);
335
1.19k
        }
336
6.33k
        output_rows += block.rows();
337
6.33k
        block.clear_column_data();
338
6.33k
    }
339
370
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
340
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
341
0
                                             tablet->tablet_id());
342
0
    }
343
344
370
    if (stats_output != nullptr) {
345
370
        if (is_key) {
346
126
            stats_output->output_rows = output_rows;
347
126
            stats_output->merged_rows = reader.merged_rows();
348
126
            stats_output->filtered_rows = reader.filtered_rows();
349
126
        }
350
370
        stats_output->bytes_read_from_local = reader.stats().file_cache_stats.bytes_read_from_local;
351
370
        stats_output->bytes_read_from_remote =
352
370
                reader.stats().file_cache_stats.bytes_read_from_remote;
353
370
        stats_output->cached_bytes_total = reader.stats().file_cache_stats.bytes_write_into_cache;
354
370
        if (config::is_cloud_mode()) {
355
0
            stats_output->cloud_local_read_time =
356
0
                    reader.stats().file_cache_stats.local_io_timer / 1000;
357
0
            stats_output->cloud_remote_read_time =
358
0
                    reader.stats().file_cache_stats.remote_io_timer / 1000;
359
0
        }
360
370
    }
361
370
    RETURN_IF_ERROR(dst_rowset_writer->flush_columns(is_key));
362
363
370
    return Status::OK();
364
370
}
365
366
// for segcompaction
367
Status Merger::vertical_compact_one_group(
368
        int64_t tablet_id, ReaderType reader_type, const TabletSchema& tablet_schema, bool is_key,
369
        const std::vector<uint32_t>& column_group, RowSourcesBuffer* row_source_buf,
370
        VerticalBlockReader& src_block_reader, segment_v2::SegmentWriter& dst_segment_writer,
371
        Statistics* stats_output, uint64_t* index_size, KeyBoundsPB& key_bounds,
372
26
        SimpleRowIdConversion* rowid_conversion) {
373
    // TODO: record_rowids
374
26
    Block block = tablet_schema.create_block(column_group);
375
26
    size_t output_rows = 0;
376
26
    bool eof = false;
377
146
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
378
        // Read one block from block reader
379
120
        RETURN_NOT_OK_STATUS_WITH_WARN(src_block_reader.next_block_with_aggregation(&block, &eof),
380
120
                                       "failed to read next block when merging rowsets of tablet " +
381
120
                                               std::to_string(tablet_id));
382
120
        if (!block.rows()) {
383
0
            break;
384
0
        }
385
120
        RETURN_NOT_OK_STATUS_WITH_WARN(dst_segment_writer.append_block(&block, 0, block.rows()),
386
120
                                       "failed to write block when merging rowsets of tablet " +
387
120
                                               std::to_string(tablet_id));
388
389
120
        if (is_key && rowid_conversion != nullptr) {
390
31
            rowid_conversion->add(src_block_reader.current_block_row_locations());
391
31
        }
392
120
        output_rows += block.rows();
393
120
        block.clear_column_data();
394
120
    }
395
26
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
396
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
397
0
                                             tablet_id);
398
0
    }
399
400
26
    if (stats_output != nullptr) {
401
26
        if (is_key) {
402
13
            stats_output->output_rows = output_rows;
403
13
            stats_output->merged_rows = src_block_reader.merged_rows();
404
13
            stats_output->filtered_rows = src_block_reader.filtered_rows();
405
13
        }
406
26
        stats_output->bytes_read_from_local =
407
26
                src_block_reader.stats().file_cache_stats.bytes_read_from_local;
408
26
        stats_output->bytes_read_from_remote =
409
26
                src_block_reader.stats().file_cache_stats.bytes_read_from_remote;
410
26
        stats_output->cached_bytes_total =
411
26
                src_block_reader.stats().file_cache_stats.bytes_write_into_cache;
412
26
    }
413
414
    // segcompaction produce only one segment at once
415
26
    RETURN_IF_ERROR(dst_segment_writer.finalize_columns_data());
416
26
    RETURN_IF_ERROR(dst_segment_writer.finalize_columns_index(index_size));
417
418
26
    if (is_key) {
419
13
        Slice min_key = dst_segment_writer.min_encoded_key();
420
13
        Slice max_key = dst_segment_writer.max_encoded_key();
421
13
        DCHECK_LE(min_key.compare(max_key), 0);
422
13
        key_bounds.set_min_key(min_key.to_string());
423
13
        key_bounds.set_max_key(max_key.to_string());
424
13
    }
425
426
26
    return Status::OK();
427
26
}
428
429
int64_t estimate_batch_size(int group_index, BaseTabletSPtr tablet, int64_t way_cnt,
430
                            ReaderType reader_type, int64_t group_per_row_from_footer,
431
161
                            bool footer_fallback) {
432
161
    auto& sample_info_lock = tablet->get_sample_info_lock(reader_type);
433
161
    auto& sample_infos = tablet->get_sample_infos(reader_type);
434
161
    std::unique_lock<std::mutex> lock(sample_info_lock);
435
161
    CompactionSampleInfo info = sample_infos[group_index];
436
161
    if (way_cnt <= 0) {
437
0
        LOG(INFO) << "estimate batch size for vertical compaction, tablet id: "
438
0
                  << tablet->tablet_id() << " way cnt: " << way_cnt;
439
0
        return 4096 - 32;
440
0
    }
441
161
    int64_t block_mem_limit = config::compaction_memory_bytes_limit / way_cnt;
442
161
    if (tablet->last_compaction_status.is<ErrorCode::MEM_LIMIT_EXCEEDED>()) {
443
0
        block_mem_limit /= 4;
444
0
    }
445
446
161
    int64_t group_data_size = 0;
447
161
    if (info.group_data_size > 0 && info.bytes > 0 && info.rows > 0) {
448
0
        double smoothing_factor = 0.5;
449
0
        group_data_size =
450
0
                int64_t((cast_set<double>(info.group_data_size) * (1 - smoothing_factor)) +
451
0
                        (cast_set<double>(info.bytes / info.rows) * smoothing_factor));
452
0
        sample_infos[group_index].group_data_size = group_data_size;
453
161
    } else if (info.group_data_size > 0 && (info.bytes <= 0 || info.rows <= 0)) {
454
0
        group_data_size = info.group_data_size;
455
161
    } else if (info.group_data_size <= 0 && info.bytes > 0 && info.rows > 0) {
456
6
        group_data_size = info.bytes / info.rows;
457
6
        sample_infos[group_index].group_data_size = group_data_size;
458
155
    } else {
459
        // No historical sampling data available.
460
        // Try to use raw_data_bytes from segment footer for a better estimate.
461
155
        if (!footer_fallback && group_per_row_from_footer > 0) {
462
123
            int64_t batch_size = block_mem_limit / group_per_row_from_footer;
463
123
            int64_t res = std::max(std::min(batch_size, int64_t(4096 - 32)), int64_t(32L));
464
123
            LOG(INFO) << "estimate batch size from footer for vertical compaction, tablet id: "
465
123
                      << tablet->tablet_id()
466
123
                      << " group_per_row_from_footer: " << group_per_row_from_footer
467
123
                      << " way cnt: " << way_cnt << " batch size: " << res;
468
123
            return res;
469
123
        }
470
155
        LOG(INFO) << "estimate batch size for vertical compaction, tablet id: "
471
32
                  << tablet->tablet_id() << " group data size: " << info.group_data_size
472
32
                  << " row num: " << info.rows << " consume bytes: " << info.bytes
473
32
                  << " footer_fallback: " << footer_fallback;
474
32
        return 1024 - 32;
475
155
    }
476
477
6
    if (group_data_size <= 0) {
478
0
        LOG(WARNING) << "estimate batch size for vertical compaction, tablet id: "
479
0
                     << tablet->tablet_id() << " unexpected group data size: " << group_data_size;
480
0
        return 4096 - 32;
481
0
    }
482
483
6
    sample_infos[group_index].bytes = 0;
484
6
    sample_infos[group_index].rows = 0;
485
486
6
    int64_t batch_size = block_mem_limit / group_data_size;
487
6
    int64_t res = std::max(std::min(batch_size, int64_t(4096 - 32)), int64_t(32L));
488
6
    LOG(INFO) << "estimate batch size for vertical compaction, tablet id: " << tablet->tablet_id()
489
6
              << " group data size: " << info.group_data_size << " row num: " << info.rows
490
6
              << " consume bytes: " << info.bytes << " way cnt: " << way_cnt
491
6
              << " batch size: " << res;
492
6
    return res;
493
6
}
494
495
// steps to do vertical merge:
496
// 1. split columns into column groups
497
// 2. compact groups one by one, generate a row_source_buf when compact key group
498
// and use this row_source_buf to compact value column groups
499
// 3. build output rowset
500
Status Merger::vertical_merge_rowsets(BaseTabletSPtr tablet, ReaderType reader_type,
501
                                      const TabletSchema& tablet_schema,
502
                                      const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
503
                                      RowsetWriter* dst_rowset_writer,
504
                                      uint32_t max_rows_per_segment, int64_t merge_way_num,
505
                                      Statistics* stats_output,
506
                                      VerticalCompactionProgressCallback progress_cb,
507
127
                                      std::optional<std::pair<int64_t, int64_t>> segment_range) {
508
127
    LOG(INFO) << "Start to do vertical compaction, tablet_id: " << tablet->tablet_id();
509
127
    VerticalCompactionContextStats context_stats;
510
127
    Defer log_context_stats {[&] {
511
127
        DCHECK_EQ(context_stats.active_segment_contexts, 0);
512
127
        LOG(INFO) << "Vertical compaction segment context statistics, tablet_id: "
513
127
                  << tablet->tablet_id() << ", vertical_compaction_active_segment_contexts_peak: "
514
127
                  << context_stats.active_segment_contexts_peak;
515
127
    }};
516
127
    std::vector<std::vector<uint32_t>> column_groups;
517
127
    std::vector<uint32_t> key_group_cluster_key_idxes;
518
    // If BE config vertical_compaction_num_columns_per_group has been modified from
519
    // its default value (5), use the BE config; otherwise use the tablet meta value.
520
127
    constexpr int32_t default_num_columns_per_group = 5;
521
127
    int32_t num_columns_per_group =
522
127
            config::vertical_compaction_num_columns_per_group != default_num_columns_per_group
523
127
                    ? config::vertical_compaction_num_columns_per_group
524
127
                    : tablet->tablet_meta()->vertical_compaction_num_columns_per_group();
525
526
127
    DBUG_EXECUTE_IF("Merger.vertical_merge_rowsets.check_num_columns_per_group", {
527
127
        auto expected_value = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
528
127
                "Merger.vertical_merge_rowsets.check_num_columns_per_group", "expected_value", -1);
529
127
        auto expected_tablet_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
530
127
                "Merger.vertical_merge_rowsets.check_num_columns_per_group", "tablet_id", -1);
531
127
        if (expected_tablet_id != -1 && expected_tablet_id == tablet->tablet_id()) {
532
127
            if (expected_value != -1 && expected_value != num_columns_per_group) {
533
127
                LOG(FATAL) << "DEBUG_POINT CHECK FAILED: expected num_columns_per_group="
534
127
                           << expected_value << " but got " << num_columns_per_group
535
127
                           << " for tablet_id=" << tablet->tablet_id();
536
127
            } else {
537
127
                LOG(INFO) << "DEBUG_POINT CHECK PASSED: num_columns_per_group="
538
127
                          << num_columns_per_group << ", tablet_id=" << tablet->tablet_id();
539
127
            }
540
127
        }
541
127
    });
542
543
127
    vertical_split_columns(tablet_schema, &column_groups, &key_group_cluster_key_idxes,
544
127
                           num_columns_per_group);
545
546
127
    if (progress_cb) {
547
29
        progress_cb(column_groups.size(), 0);
548
29
    }
549
550
    // Segment-range vertical compaction only sees part of a rowset. Do not use partial rows to
551
    // update tablet-level density or drive sparse optimization.
552
127
    int64_t total_rows = 0;
553
    // Use historical density for sparse wide table optimization
554
    // density = (total_cells - null_cells) / total_cells, smaller means more sparse
555
    // When density <= threshold, enable sparse optimization
556
    // threshold = 0 means disable, 1 means always enable (default)
557
127
    bool enable_sparse_optimization = false;
558
127
    if (!segment_range.has_value()) {
559
351
        for (const auto& rs_reader : src_rowset_readers) {
560
351
            total_rows += rs_reader->rowset()->rowset_meta()->num_rows();
561
351
        }
562
563
123
        if (config::sparse_column_compaction_threshold_percent > 0 &&
564
123
            tablet->keys_type() == KeysType::UNIQUE_KEYS) {
565
46
            double density = tablet->compaction_density.load();
566
46
            enable_sparse_optimization =
567
46
                    density <= config::sparse_column_compaction_threshold_percent;
568
569
46
            LOG(INFO) << "Vertical compaction sparse optimization check: tablet_id="
570
46
                      << tablet->tablet_id() << ", density=" << density
571
46
                      << ", threshold=" << config::sparse_column_compaction_threshold_percent
572
46
                      << ", total_rows=" << total_rows
573
46
                      << ", num_columns=" << tablet_schema.num_columns()
574
46
                      << ", total_cells=" << total_rows * tablet_schema.num_columns()
575
46
                      << ", enable_sparse_optimization=" << enable_sparse_optimization;
576
46
        }
577
123
    }
578
579
127
    RowSourcesBuffer row_sources_buf(tablet->tablet_id(), dst_rowset_writer->context().tablet_path,
580
127
                                     reader_type);
581
127
    Merger::Statistics total_stats;
582
127
    if (stats_output != nullptr) {
583
127
        total_stats.rowid_conversion = stats_output->rowid_conversion;
584
127
    }
585
127
    auto& sample_info_lock = tablet->get_sample_info_lock(reader_type);
586
127
    auto& sample_infos = tablet->get_sample_infos(reader_type);
587
127
    {
588
127
        std::unique_lock<std::mutex> lock(sample_info_lock);
589
127
        sample_infos.resize(column_groups.size());
590
127
    }
591
    // Collect per-column raw_data_bytes from segment footer for first-time batch size estimation.
592
    // raw_data_bytes is the original data size before encoding, close to runtime Block::bytes().
593
    // Only collect when needed: skip if manual batch_size override is set, or if ALL groups
594
    // already have historical sampling data. Use per-group granularity so that schema evolution
595
    // (new groups without history) still gets footer-based estimation.
596
127
    struct ColumnRawSizeInfo {
597
127
        int64_t total_raw_bytes = 0;
598
127
        int64_t rows_with_data = 0;
599
127
    };
600
127
    std::unordered_map<int32_t, ColumnRawSizeInfo> column_raw_sizes;
601
127
    bool need_footer_collection = false;
602
127
    if (config::compaction_batch_size == -1) {
603
81
        std::unique_lock<std::mutex> lock(sample_info_lock);
604
84
        for (const auto& info : sample_infos) {
605
84
            if (info.group_data_size <= 0 && info.bytes <= 0 && info.rows <= 0) {
606
78
                need_footer_collection = true;
607
78
                break;
608
78
            }
609
84
        }
610
81
    }
611
127
    if (!segment_range.has_value() && need_footer_collection) {
612
211
        for (const auto& rs_reader : src_rowset_readers) {
613
211
            auto beta_rowset = std::dynamic_pointer_cast<BetaRowset>(rs_reader->rowset());
614
211
            if (!beta_rowset) {
615
0
                continue;
616
0
            }
617
211
            std::vector<segment_v2::SegmentSharedPtr> segments;
618
211
            auto st = beta_rowset->load_segments(&segments);
619
211
            if (!st.ok()) {
620
0
                LOG(WARNING) << "Failed to load segments for footer raw_data_bytes collection"
621
0
                             << ", tablet_id: " << tablet->tablet_id()
622
0
                             << ", rowset_id: " << beta_rowset->rowset_id() << ", status: " << st;
623
0
                continue;
624
0
            }
625
524
            for (int64_t segment_idx = 0; segment_idx < segments.size(); ++segment_idx) {
626
313
                const auto& segment = segments[segment_idx];
627
313
                int64_t row_count = segment->num_rows();
628
313
                auto collect_st = segment->traverse_column_meta_pbs(
629
1.43k
                        [&](const segment_v2::ColumnMetaPB& meta) {
630
1.43k
                            int32_t uid = meta.unique_id();
631
1.43k
                            if (uid >= 0 && meta.has_raw_data_bytes()) {
632
928
                                auto& info = column_raw_sizes[uid];
633
928
                                info.total_raw_bytes += meta.raw_data_bytes();
634
928
                                info.rows_with_data += row_count;
635
928
                            }
636
1.43k
                        });
637
313
                if (!collect_st.ok()) {
638
0
                    LOG(WARNING) << "Failed to traverse column meta for footer collection"
639
0
                                 << ", tablet_id: " << tablet->tablet_id()
640
0
                                 << ", status: " << collect_st;
641
0
                }
642
313
            }
643
211
        }
644
77
    }
645
646
    // Pre-compute per-row estimate for each column group from footer data.
647
127
    std::vector<int64_t> group_per_row_from_footer(column_groups.size(), 0);
648
127
    std::vector<bool> group_footer_fallback(column_groups.size(), segment_range.has_value());
649
498
    for (size_t i = 0; i < column_groups.size(); ++i) {
650
371
        int64_t group_per_row = 0;
651
371
        bool need_fallback = false;
652
410
        for (uint32_t col_ordinal : column_groups[i]) {
653
410
            const auto& col = tablet_schema.column(col_ordinal);
654
410
            int32_t uid = col.unique_id();
655
656
            // Variant columns (root or subcolumn): raw_data_bytes is 0 (TODO in writer),
657
            // cannot estimate from footer, fallback to default for the entire group.
658
410
            if (uid < 0 || col.is_variant_type()) {
659
30
                need_fallback = true;
660
30
                break;
661
30
            }
662
663
            // Any column without footer data (e.g. legacy segments written before
664
            // raw_data_bytes existed) makes the group sample partial and unreliable.
665
            // Fall back to the default for the whole group instead of summing only
666
            // the columns we measured.
667
380
            auto it = column_raw_sizes.find(uid);
668
380
            if (it == column_raw_sizes.end() || it->second.rows_with_data <= 0) {
669
218
                need_fallback = true;
670
218
                break;
671
218
            }
672
673
162
            int64_t raw_per_row = it->second.total_raw_bytes / it->second.rows_with_data;
674
162
            int64_t col_per_row = 0;
675
676
162
            if (col.type() == FieldType::OLAP_FIELD_TYPE_ARRAY ||
677
162
                col.type() == FieldType::OLAP_FIELD_TYPE_MAP ||
678
162
                col.type() == FieldType::OLAP_FIELD_TYPE_STRUCT) {
679
                // Complex types: raw_data_bytes recursively aggregates sub-writers.
680
0
                col_per_row = raw_per_row;
681
162
            } else if (col.is_length_variable_type()) {
682
                // Variable-length scalar (VARCHAR/STRING/HLL/BITMAP/...): raw_per_row
683
                // is the average char payload across all rows; reader still pays an
684
                // 8-byte offset entry per row regardless of null-ness.
685
1
                col_per_row = raw_per_row + 8;
686
1
                if (col.is_nullable()) {
687
0
                    col_per_row += 1; // null map
688
0
                }
689
161
            } else {
690
                // Fixed-width scalar (INT/BIGINT/DOUBLE/DATE/...).
691
                // raw_data_bytes only counts non-null payload (append_nulls() does
692
                // not advance the page builder), but FileColumnIterator::next_batch
693
                // still calls ColumnNullable::insert_many_defaults() for null runs,
694
                // which grows the nested PODArray by N * type_size. So the runtime
695
                // per-row footprint is at least type_size, no matter how sparse.
696
161
                int64_t type_size = field_type_size(col.type());
697
161
                col_per_row = std::max(raw_per_row, type_size);
698
161
                if (col.is_nullable()) {
699
1
                    col_per_row += 1; // null map
700
1
                }
701
161
            }
702
703
162
            group_per_row += col_per_row;
704
162
        }
705
371
        group_per_row_from_footer[i] = group_per_row;
706
371
        group_footer_fallback[i] = need_fallback;
707
371
    }
708
709
    // compact group one by one
710
497
    for (auto i = 0; i < column_groups.size(); ++i) {
711
371
        VLOG_NOTICE << "row source size: " << row_sources_buf.total_size();
712
371
        bool is_key = (i == 0);
713
371
        int64_t batch_size = config::compaction_batch_size != -1
714
371
                                     ? config::compaction_batch_size
715
371
                                     : estimate_batch_size(i, tablet, merge_way_num, reader_type,
716
161
                                                           group_per_row_from_footer[i],
717
161
                                                           group_footer_fallback[i]);
718
371
        CompactionSampleInfo sample_info;
719
371
        Merger::Statistics group_stats;
720
371
        group_stats.rowid_conversion = total_stats.rowid_conversion;
721
371
        Merger::Statistics* group_stats_ptr = stats_output != nullptr ? &group_stats : nullptr;
722
371
        Status st = vertical_compact_one_group(
723
371
                tablet, reader_type, tablet_schema, is_key, column_groups[i], &row_sources_buf,
724
371
                src_rowset_readers, dst_rowset_writer, max_rows_per_segment, group_stats_ptr,
725
371
                key_group_cluster_key_idxes, batch_size, &sample_info, &context_stats,
726
371
                enable_sparse_optimization, segment_range);
727
371
        {
728
371
            std::unique_lock<std::mutex> lock(sample_info_lock);
729
371
            sample_infos[i] = sample_info;
730
371
        }
731
371
        RETURN_IF_ERROR(st);
732
370
        if (stats_output != nullptr) {
733
370
            total_stats.bytes_read_from_local += group_stats.bytes_read_from_local;
734
370
            total_stats.bytes_read_from_remote += group_stats.bytes_read_from_remote;
735
370
            total_stats.cached_bytes_total += group_stats.cached_bytes_total;
736
370
            total_stats.cloud_local_read_time += group_stats.cloud_local_read_time;
737
370
            total_stats.cloud_remote_read_time += group_stats.cloud_remote_read_time;
738
370
            if (is_key) {
739
126
                total_stats.output_rows = group_stats.output_rows;
740
126
                total_stats.merged_rows = group_stats.merged_rows;
741
126
                total_stats.filtered_rows = group_stats.filtered_rows;
742
126
                total_stats.rowid_conversion = group_stats.rowid_conversion;
743
126
            }
744
370
        }
745
370
        if (progress_cb) {
746
61
            progress_cb(column_groups.size(), i + 1);
747
61
        }
748
370
        if (is_key) {
749
126
            RETURN_IF_ERROR(row_sources_buf.flush());
750
126
        }
751
370
        RETURN_IF_ERROR(row_sources_buf.seek_to_begin());
752
370
    }
753
754
    // Calculate and store density for next compaction's sparse optimization threshold
755
    // density = (total_cells - total_null_count) / total_cells
756
    // Smaller density means more sparse
757
126
    if (!segment_range.has_value()) {
758
122
        std::unique_lock<std::mutex> lock(sample_info_lock);
759
122
        int64_t total_null_count = 0;
760
362
        for (const auto& info : sample_infos) {
761
362
            total_null_count += info.null_count;
762
362
        }
763
122
        int64_t total_cells = total_rows * tablet_schema.num_columns();
764
122
        if (total_cells > 0) {
765
121
            double density = static_cast<double>(total_cells - total_null_count) /
766
121
                             static_cast<double>(total_cells);
767
121
            tablet->compaction_density.store(density);
768
121
            LOG(INFO) << "Vertical compaction density update: tablet_id=" << tablet->tablet_id()
769
121
                      << ", total_cells=" << total_cells
770
121
                      << ", total_null_count=" << total_null_count << ", density=" << density;
771
121
        }
772
122
    }
773
774
    // finish compact, build output rowset
775
126
    VLOG_NOTICE << "finish compact groups";
776
126
    RETURN_IF_ERROR(dst_rowset_writer->final_flush());
777
778
126
    if (stats_output != nullptr) {
779
126
        *stats_output = total_stats;
780
126
    }
781
782
126
    return Status::OK();
783
126
}
784
#include "common/compile_check_end.h"
785
} // namespace doris