Coverage Report

Created: 2026-07-31 13:05

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