Coverage Report

Created: 2026-04-23 15:50

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