Coverage Report

Created: 2026-08-10 15:00

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