Coverage Report

Created: 2026-08-07 08:28

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