Coverage Report

Created: 2026-08-14 19:57

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