Coverage Report

Created: 2026-07-24 01:26

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