Coverage Report

Created: 2026-06-12 09:27

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