Coverage Report

Created: 2026-01-29 19:05

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 <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 "olap/base_tablet.h"
41
#include "olap/iterators.h"
42
#include "olap/olap_common.h"
43
#include "olap/olap_define.h"
44
#include "olap/rowid_conversion.h"
45
#include "olap/rowset/rowset.h"
46
#include "olap/rowset/rowset_meta.h"
47
#include "olap/rowset/rowset_writer.h"
48
#include "olap/rowset/segment_v2/segment_writer.h"
49
#include "olap/storage_engine.h"
50
#include "olap/tablet.h"
51
#include "olap/tablet_fwd.h"
52
#include "olap/tablet_meta.h"
53
#include "olap/tablet_reader.h"
54
#include "olap/utils.h"
55
#include "util/slice.h"
56
#include "vec/core/block.h"
57
#include "vec/olap/block_reader.h"
58
#include "vec/olap/vertical_block_reader.h"
59
#include "vec/olap/vertical_merge_iterator.h"
60
61
namespace doris {
62
#include "common/compile_check_begin.h"
63
Status Merger::vmerge_rowsets(BaseTabletSPtr tablet, ReaderType reader_type,
64
                              const TabletSchema& cur_tablet_schema,
65
                              const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
66
1.40k
                              RowsetWriter* dst_rowset_writer, Statistics* stats_output) {
67
1.40k
    if (!cur_tablet_schema.cluster_key_uids().empty()) {
68
0
        return Status::InternalError(
69
0
                "mow table with cluster keys does not support non vertical compaction");
70
0
    }
71
1.40k
    vectorized::BlockReader reader;
72
1.40k
    TabletReader::ReaderParams reader_params;
73
1.40k
    reader_params.tablet = tablet;
74
1.40k
    reader_params.reader_type = reader_type;
75
76
1.40k
    TabletReadSource read_source;
77
1.40k
    read_source.rs_splits.reserve(src_rowset_readers.size());
78
1.51k
    for (const RowsetReaderSharedPtr& rs_reader : src_rowset_readers) {
79
1.51k
        read_source.rs_splits.emplace_back(rs_reader);
80
1.51k
    }
81
1.40k
    read_source.fill_delete_predicates();
82
1.40k
    reader_params.set_read_source(std::move(read_source));
83
84
1.40k
    reader_params.version = dst_rowset_writer->version();
85
86
1.40k
    TabletSchemaSPtr merge_tablet_schema = std::make_shared<TabletSchema>();
87
1.40k
    merge_tablet_schema->copy_from(cur_tablet_schema);
88
89
    // Merge the columns in delete predicate that not in latest schema in to current tablet schema
90
1.40k
    for (auto& del_pred_rs : reader_params.delete_predicates) {
91
24
        merge_tablet_schema->merge_dropped_columns(*del_pred_rs->tablet_schema());
92
24
    }
93
1.40k
    reader_params.tablet_schema = merge_tablet_schema;
94
1.40k
    if (!tablet->tablet_schema()->cluster_key_uids().empty()) {
95
0
        reader_params.delete_bitmap = tablet->tablet_meta()->delete_bitmap_ptr();
96
0
    }
97
98
1.40k
    if (stats_output && stats_output->rowid_conversion) {
99
48
        reader_params.record_rowids = true;
100
48
        reader_params.rowid_conversion = stats_output->rowid_conversion;
101
48
        stats_output->rowid_conversion->set_dst_rowset_id(dst_rowset_writer->rowset_id());
102
48
    }
103
104
1.40k
    reader_params.return_columns.resize(cur_tablet_schema.num_columns());
105
1.40k
    std::iota(reader_params.return_columns.begin(), reader_params.return_columns.end(), 0);
106
1.40k
    reader_params.origin_return_columns = &reader_params.return_columns;
107
1.40k
    RETURN_IF_ERROR(reader.init(reader_params));
108
109
1.40k
    vectorized::Block block = cur_tablet_schema.create_block(reader_params.return_columns);
110
1.40k
    size_t output_rows = 0;
111
1.40k
    bool eof = false;
112
4.13k
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
113
2.72k
        auto tablet_state = tablet->tablet_state();
114
2.72k
        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
2.72k
        RETURN_NOT_OK_STATUS_WITH_WARN(reader.next_block_with_aggregation(&block, &eof),
122
2.72k
                                       "failed to read next block when merging rowsets of tablet " +
123
2.72k
                                               std::to_string(tablet->tablet_id()));
124
2.72k
        RETURN_NOT_OK_STATUS_WITH_WARN(dst_rowset_writer->add_block(&block),
125
2.72k
                                       "failed to write block when merging rowsets of tablet " +
126
2.72k
                                               std::to_string(tablet->tablet_id()));
127
128
2.72k
        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
2.72k
        output_rows += block.rows();
136
2.72k
        block.clear_column_data();
137
2.72k
    }
138
1.40k
    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
1.40k
    if (stats_output != nullptr) {
144
1.40k
        stats_output->output_rows = output_rows;
145
1.40k
        stats_output->merged_rows = reader.merged_rows();
146
1.40k
        stats_output->filtered_rows = reader.filtered_rows();
147
1.40k
        stats_output->bytes_read_from_local = reader.stats().file_cache_stats.bytes_read_from_local;
148
1.40k
        stats_output->bytes_read_from_remote =
149
1.40k
                reader.stats().file_cache_stats.bytes_read_from_remote;
150
1.40k
        stats_output->cached_bytes_total = reader.stats().file_cache_stats.bytes_write_into_cache;
151
1.40k
        if (config::is_cloud_mode()) {
152
1.35k
            stats_output->cloud_local_read_time =
153
1.35k
                    reader.stats().file_cache_stats.local_io_timer / 1000;
154
1.35k
            stats_output->cloud_remote_read_time =
155
1.35k
                    reader.stats().file_cache_stats.remote_io_timer / 1000;
156
1.35k
        }
157
1.40k
    }
158
159
1.40k
    RETURN_NOT_OK_STATUS_WITH_WARN(dst_rowset_writer->flush(),
160
1.40k
                                   "failed to flush rowset when merging rowsets of tablet " +
161
1.40k
                                           std::to_string(tablet->tablet_id()));
162
163
1.40k
    return Status::OK();
164
1.40k
}
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
10.3k
                                    std::vector<uint32_t>* key_group_cluster_key_idxes) {
171
10.3k
    size_t num_key_cols = tablet_schema.num_key_columns();
172
10.3k
    size_t total_cols = tablet_schema.num_columns();
173
10.3k
    std::vector<uint32_t> key_columns;
174
46.0k
    for (auto i = 0; i < num_key_cols; ++i) {
175
35.7k
        key_columns.emplace_back(i);
176
35.7k
    }
177
    // in unique key, sequence & delete sign column should merge with key columns
178
10.3k
    int32_t sequence_col_idx = -1;
179
10.3k
    int32_t delete_sign_idx = -1;
180
    // in key column compaction, seq_col real index is _num_key_columns
181
    // and delete_sign column is _block->columns() - 1
182
10.3k
    if (tablet_schema.keys_type() == KeysType::UNIQUE_KEYS) {
183
4.10k
        if (tablet_schema.has_sequence_col()) {
184
202
            sequence_col_idx = tablet_schema.sequence_col_idx();
185
202
            key_columns.emplace_back(sequence_col_idx);
186
202
        }
187
4.10k
        delete_sign_idx = tablet_schema.field_index(DELETE_SIGN);
188
4.10k
        if (delete_sign_idx != -1) {
189
4.10k
            key_columns.emplace_back(delete_sign_idx);
190
4.10k
        }
191
4.10k
        if (!tablet_schema.cluster_key_uids().empty()) {
192
506
            for (const auto& cid : tablet_schema.cluster_key_uids()) {
193
506
                auto idx = tablet_schema.field_index(cid);
194
506
                DCHECK(idx >= 0) << "could not find cluster key column with unique_id=" << cid
195
0
                                 << " in tablet schema, table_id=" << tablet_schema.table_id();
196
506
                if (idx >= num_key_cols) {
197
248
                    key_columns.emplace_back(idx);
198
248
                }
199
506
            }
200
            // tablet schema unique ids: [1, 2, 5, 3, 6, 4], [1 2] is key columns
201
            // cluster key unique ids: [3, 1, 4]
202
            // the key_columns should be [0, 1, 3, 5]
203
            // the key_group_cluster_key_idxes should be [2, 1, 3]
204
506
            for (const auto& cid : tablet_schema.cluster_key_uids()) {
205
506
                auto idx = tablet_schema.field_index(cid);
206
2.81k
                for (auto i = 0; i < key_columns.size(); ++i) {
207
2.81k
                    if (idx == key_columns[i]) {
208
506
                        key_group_cluster_key_idxes->emplace_back(i);
209
506
                        break;
210
506
                    }
211
2.81k
                }
212
506
            }
213
174
        }
214
4.10k
    }
215
10.3k
    VLOG_NOTICE << "sequence_col_idx=" << sequence_col_idx
216
67
                << ", delete_sign_idx=" << delete_sign_idx;
217
    // for duplicate no keys
218
10.3k
    if (!key_columns.empty()) {
219
10.3k
        column_groups->emplace_back(key_columns);
220
10.3k
    }
221
222
10.3k
    std::vector<uint32_t> value_columns;
223
224
89.3k
    for (size_t i = num_key_cols; i < total_cols; ++i) {
225
79.0k
        if (i == sequence_col_idx || i == delete_sign_idx ||
226
79.0k
            key_columns.end() != std::find(key_columns.begin(), key_columns.end(), i)) {
227
4.54k
            continue;
228
4.54k
        }
229
230
74.4k
        if (!value_columns.empty() &&
231
74.4k
            value_columns.size() % config::vertical_compaction_num_columns_per_group == 0) {
232
9.32k
            column_groups->push_back(value_columns);
233
9.32k
            value_columns.clear();
234
9.32k
        }
235
74.4k
        value_columns.push_back(cast_set<uint32_t>(i));
236
74.4k
    }
237
238
10.3k
    if (!value_columns.empty()) {
239
9.76k
        column_groups->push_back(value_columns);
240
9.76k
    }
241
10.3k
}
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,
246
        vectorized::RowSourcesBuffer* row_source_buf,
247
        const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
248
        RowsetWriter* dst_rowset_writer, uint32_t max_rows_per_segment, Statistics* stats_output,
249
        std::vector<uint32_t> key_group_cluster_key_idxes, int64_t batch_size,
250
29.4k
        CompactionSampleInfo* sample_info, bool enable_sparse_optimization) {
251
    // build tablet reader
252
29.4k
    VLOG_NOTICE << "vertical compact one group, max_rows_per_segment=" << max_rows_per_segment;
253
29.4k
    vectorized::VerticalBlockReader reader(row_source_buf);
254
29.4k
    TabletReader::ReaderParams reader_params;
255
29.4k
    reader_params.is_key_column_group = is_key;
256
29.4k
    reader_params.key_group_cluster_key_idxes = key_group_cluster_key_idxes;
257
29.4k
    reader_params.tablet = tablet;
258
29.4k
    reader_params.reader_type = reader_type;
259
29.4k
    reader_params.enable_sparse_optimization = enable_sparse_optimization;
260
261
29.4k
    TabletReadSource read_source;
262
29.4k
    read_source.rs_splits.reserve(src_rowset_readers.size());
263
216k
    for (const RowsetReaderSharedPtr& rs_reader : src_rowset_readers) {
264
216k
        read_source.rs_splits.emplace_back(rs_reader);
265
216k
    }
266
29.4k
    read_source.fill_delete_predicates();
267
29.4k
    reader_params.set_read_source(std::move(read_source));
268
269
29.4k
    reader_params.version = dst_rowset_writer->version();
270
271
29.4k
    TabletSchemaSPtr merge_tablet_schema = std::make_shared<TabletSchema>();
272
29.4k
    merge_tablet_schema->copy_from(tablet_schema);
273
274
29.4k
    for (auto& del_pred_rs : reader_params.delete_predicates) {
275
1.72k
        merge_tablet_schema->merge_dropped_columns(*del_pred_rs->tablet_schema());
276
1.72k
    }
277
278
29.4k
    reader_params.tablet_schema = merge_tablet_schema;
279
29.4k
    bool has_cluster_key = false;
280
29.4k
    if (!tablet->tablet_schema()->cluster_key_uids().empty()) {
281
487
        reader_params.delete_bitmap = tablet->tablet_meta()->delete_bitmap_ptr();
282
487
        has_cluster_key = true;
283
487
    }
284
285
29.4k
    if (is_key && stats_output && stats_output->rowid_conversion) {
286
4.51k
        reader_params.record_rowids = true;
287
4.51k
        reader_params.rowid_conversion = stats_output->rowid_conversion;
288
4.51k
        stats_output->rowid_conversion->set_dst_rowset_id(dst_rowset_writer->rowset_id());
289
4.51k
    }
290
291
29.4k
    reader_params.return_columns = column_group;
292
29.4k
    reader_params.origin_return_columns = &reader_params.return_columns;
293
29.4k
    reader_params.batch_size = batch_size;
294
29.4k
    RETURN_IF_ERROR(reader.init(reader_params, sample_info));
295
296
29.4k
    vectorized::Block block = tablet_schema.create_block(reader_params.return_columns);
297
29.4k
    size_t output_rows = 0;
298
29.4k
    bool eof = false;
299
85.6k
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
300
56.2k
        auto tablet_state = tablet->tablet_state();
301
56.2k
        if (tablet_state != TABLET_RUNNING && tablet_state != TABLET_NOTREADY) {
302
0
            tablet->clear_cache();
303
0
            return Status::Error<INTERNAL_ERROR>("tablet {} is not used any more",
304
0
                                                 tablet->tablet_id());
305
0
        }
306
        // Read one block from block reader
307
56.2k
        RETURN_NOT_OK_STATUS_WITH_WARN(reader.next_block_with_aggregation(&block, &eof),
308
56.2k
                                       "failed to read next block when merging rowsets of tablet " +
309
56.2k
                                               std::to_string(tablet->tablet_id()));
310
56.2k
        RETURN_NOT_OK_STATUS_WITH_WARN(
311
56.2k
                dst_rowset_writer->add_columns(&block, column_group, is_key, max_rows_per_segment,
312
56.2k
                                               has_cluster_key),
313
56.2k
                "failed to write block when merging rowsets of tablet " +
314
56.2k
                        std::to_string(tablet->tablet_id()));
315
316
56.2k
        if (is_key && reader_params.record_rowids && block.rows() > 0) {
317
8.53k
            std::vector<uint32_t> segment_num_rows;
318
8.53k
            RETURN_IF_ERROR(dst_rowset_writer->get_segment_num_rows(&segment_num_rows));
319
8.53k
            stats_output->rowid_conversion->add(reader.current_block_row_locations(),
320
8.53k
                                                segment_num_rows);
321
8.53k
        }
322
56.2k
        output_rows += block.rows();
323
56.2k
        block.clear_column_data();
324
56.2k
    }
325
29.4k
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
326
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
327
0
                                             tablet->tablet_id());
328
0
    }
329
330
29.4k
    if (stats_output != nullptr) {
331
29.3k
        if (is_key) {
332
10.3k
            stats_output->output_rows = output_rows;
333
10.3k
            stats_output->merged_rows = reader.merged_rows();
334
10.3k
            stats_output->filtered_rows = reader.filtered_rows();
335
10.3k
        }
336
29.3k
        stats_output->bytes_read_from_local = reader.stats().file_cache_stats.bytes_read_from_local;
337
29.3k
        stats_output->bytes_read_from_remote =
338
29.3k
                reader.stats().file_cache_stats.bytes_read_from_remote;
339
29.3k
        stats_output->cached_bytes_total = reader.stats().file_cache_stats.bytes_write_into_cache;
340
29.3k
        if (config::is_cloud_mode()) {
341
29.0k
            stats_output->cloud_local_read_time =
342
29.0k
                    reader.stats().file_cache_stats.local_io_timer / 1000;
343
29.0k
            stats_output->cloud_remote_read_time =
344
29.0k
                    reader.stats().file_cache_stats.remote_io_timer / 1000;
345
29.0k
        }
346
29.3k
    }
347
29.4k
    RETURN_IF_ERROR(dst_rowset_writer->flush_columns(is_key));
348
349
29.4k
    return Status::OK();
350
29.4k
}
351
352
// for segcompaction
353
Status Merger::vertical_compact_one_group(
354
        int64_t tablet_id, ReaderType reader_type, const TabletSchema& tablet_schema, bool is_key,
355
        const std::vector<uint32_t>& column_group, vectorized::RowSourcesBuffer* row_source_buf,
356
        vectorized::VerticalBlockReader& src_block_reader,
357
        segment_v2::SegmentWriter& dst_segment_writer, Statistics* stats_output,
358
22
        uint64_t* index_size, KeyBoundsPB& key_bounds, SimpleRowIdConversion* rowid_conversion) {
359
    // TODO: record_rowids
360
22
    vectorized::Block block = tablet_schema.create_block(column_group);
361
22
    size_t output_rows = 0;
362
22
    bool eof = false;
363
138
    while (!eof && !ExecEnv::GetInstance()->storage_engine().stopped()) {
364
        // Read one block from block reader
365
116
        RETURN_NOT_OK_STATUS_WITH_WARN(src_block_reader.next_block_with_aggregation(&block, &eof),
366
116
                                       "failed to read next block when merging rowsets of tablet " +
367
116
                                               std::to_string(tablet_id));
368
116
        if (!block.rows()) {
369
0
            break;
370
0
        }
371
116
        RETURN_NOT_OK_STATUS_WITH_WARN(dst_segment_writer.append_block(&block, 0, block.rows()),
372
116
                                       "failed to write block when merging rowsets of tablet " +
373
116
                                               std::to_string(tablet_id));
374
375
116
        if (is_key && rowid_conversion != nullptr) {
376
30
            rowid_conversion->add(src_block_reader.current_block_row_locations());
377
30
        }
378
116
        output_rows += block.rows();
379
116
        block.clear_column_data();
380
116
    }
381
22
    if (ExecEnv::GetInstance()->storage_engine().stopped()) {
382
0
        return Status::Error<INTERNAL_ERROR>("tablet {} failed to do compaction, engine stopped",
383
0
                                             tablet_id);
384
0
    }
385
386
22
    if (stats_output != nullptr) {
387
22
        if (is_key) {
388
11
            stats_output->output_rows = output_rows;
389
11
            stats_output->merged_rows = src_block_reader.merged_rows();
390
11
            stats_output->filtered_rows = src_block_reader.filtered_rows();
391
11
        }
392
22
        stats_output->bytes_read_from_local =
393
22
                src_block_reader.stats().file_cache_stats.bytes_read_from_local;
394
22
        stats_output->bytes_read_from_remote =
395
22
                src_block_reader.stats().file_cache_stats.bytes_read_from_remote;
396
22
        stats_output->cached_bytes_total =
397
22
                src_block_reader.stats().file_cache_stats.bytes_write_into_cache;
398
22
    }
399
400
    // segcompaction produce only one segment at once
401
22
    RETURN_IF_ERROR(dst_segment_writer.finalize_columns_data());
402
22
    RETURN_IF_ERROR(dst_segment_writer.finalize_columns_index(index_size));
403
404
22
    if (is_key) {
405
11
        Slice min_key = dst_segment_writer.min_encoded_key();
406
11
        Slice max_key = dst_segment_writer.max_encoded_key();
407
11
        DCHECK_LE(min_key.compare(max_key), 0);
408
11
        key_bounds.set_min_key(min_key.to_string());
409
11
        key_bounds.set_max_key(max_key.to_string());
410
11
    }
411
412
22
    return Status::OK();
413
22
}
414
415
29.0k
int64_t estimate_batch_size(int group_index, BaseTabletSPtr tablet, int64_t way_cnt) {
416
29.0k
    std::unique_lock<std::mutex> lock(tablet->sample_info_lock);
417
29.0k
    CompactionSampleInfo info = tablet->sample_infos[group_index];
418
29.0k
    if (way_cnt <= 0) {
419
12.6k
        LOG(INFO) << "estimate batch size for vertical compaction, tablet id: "
420
12.6k
                  << tablet->tablet_id() << " way cnt: " << way_cnt;
421
12.6k
        return 4096 - 32;
422
12.6k
    }
423
16.4k
    int64_t block_mem_limit = config::compaction_memory_bytes_limit / way_cnt;
424
16.4k
    if (tablet->last_compaction_status.is<ErrorCode::MEM_LIMIT_EXCEEDED>()) {
425
0
        block_mem_limit /= 4;
426
0
    }
427
428
16.4k
    int64_t group_data_size = 0;
429
16.4k
    if (info.group_data_size > 0 && info.bytes > 0 && info.rows > 0) {
430
0
        double smoothing_factor = 0.5;
431
0
        group_data_size =
432
0
                int64_t((cast_set<double>(info.group_data_size) * (1 - smoothing_factor)) +
433
0
                        (cast_set<double>(info.bytes / info.rows) * smoothing_factor));
434
0
        tablet->sample_infos[group_index].group_data_size = group_data_size;
435
16.4k
    } else if (info.group_data_size > 0 && (info.bytes <= 0 || info.rows <= 0)) {
436
2
        group_data_size = info.group_data_size;
437
16.5k
    } else if (info.group_data_size <= 0 && info.bytes > 0 && info.rows > 0) {
438
8.69k
        group_data_size = info.bytes / info.rows;
439
8.69k
        tablet->sample_infos[group_index].group_data_size = group_data_size;
440
8.69k
    } else {
441
7.76k
        LOG(INFO) << "estimate batch size for vertical compaction, tablet id: "
442
7.76k
                  << tablet->tablet_id() << " group data size: " << info.group_data_size
443
7.76k
                  << " row num: " << info.rows << " consume bytes: " << info.bytes;
444
7.76k
        return 1024 - 32;
445
7.76k
    }
446
447
8.69k
    if (group_data_size <= 0) {
448
0
        LOG(WARNING) << "estimate batch size for vertical compaction, tablet id: "
449
0
                     << tablet->tablet_id() << " unexpected group data size: " << group_data_size;
450
0
        return 4096 - 32;
451
0
    }
452
453
8.69k
    tablet->sample_infos[group_index].bytes = 0;
454
8.69k
    tablet->sample_infos[group_index].rows = 0;
455
456
8.69k
    int64_t batch_size = block_mem_limit / group_data_size;
457
8.69k
    int64_t res = std::max(std::min(batch_size, int64_t(4096 - 32)), int64_t(32L));
458
8.69k
    LOG(INFO) << "estimate batch size for vertical compaction, tablet id: " << tablet->tablet_id()
459
8.69k
              << " group data size: " << info.group_data_size << " row num: " << info.rows
460
8.69k
              << " consume bytes: " << info.bytes << " way cnt: " << way_cnt
461
8.69k
              << " batch size: " << res;
462
8.69k
    return res;
463
8.69k
}
464
465
// steps to do vertical merge:
466
// 1. split columns into column groups
467
// 2. compact groups one by one, generate a row_source_buf when compact key group
468
// and use this row_source_buf to compact value column groups
469
// 3. build output rowset
470
Status Merger::vertical_merge_rowsets(BaseTabletSPtr tablet, ReaderType reader_type,
471
                                      const TabletSchema& tablet_schema,
472
                                      const std::vector<RowsetReaderSharedPtr>& src_rowset_readers,
473
                                      RowsetWriter* dst_rowset_writer,
474
                                      uint32_t max_rows_per_segment, int64_t merge_way_num,
475
10.2k
                                      Statistics* stats_output) {
476
10.2k
    LOG(INFO) << "Start to do vertical compaction, tablet_id: " << tablet->tablet_id();
477
10.2k
    std::vector<std::vector<uint32_t>> column_groups;
478
10.2k
    std::vector<uint32_t> key_group_cluster_key_idxes;
479
10.2k
    vertical_split_columns(tablet_schema, &column_groups, &key_group_cluster_key_idxes);
480
481
    // Calculate total rows for density calculation after compaction
482
10.2k
    int64_t total_rows = 0;
483
76.4k
    for (const auto& rs_reader : src_rowset_readers) {
484
76.4k
        total_rows += rs_reader->rowset()->rowset_meta()->num_rows();
485
76.4k
    }
486
487
    // Use historical density for sparse wide table optimization
488
    // density = (total_cells - null_cells) / total_cells, smaller means more sparse
489
    // When density <= threshold, enable sparse optimization
490
    // threshold = 0 means disable, 1 means always enable (default)
491
10.2k
    bool enable_sparse_optimization = false;
492
10.2k
    if (config::sparse_column_compaction_threshold_percent > 0 &&
493
10.3k
        tablet->keys_type() == KeysType::UNIQUE_KEYS) {
494
4.10k
        double density = tablet->compaction_density.load();
495
4.10k
        enable_sparse_optimization = density <= config::sparse_column_compaction_threshold_percent;
496
497
4.10k
        LOG(INFO) << "Vertical compaction sparse optimization check: tablet_id="
498
4.10k
                  << tablet->tablet_id() << ", density=" << density
499
4.10k
                  << ", threshold=" << config::sparse_column_compaction_threshold_percent
500
4.10k
                  << ", total_rows=" << total_rows
501
4.10k
                  << ", num_columns=" << tablet_schema.num_columns()
502
4.10k
                  << ", total_cells=" << total_rows * tablet_schema.num_columns()
503
4.10k
                  << ", enable_sparse_optimization=" << enable_sparse_optimization;
504
4.10k
    }
505
506
10.2k
    vectorized::RowSourcesBuffer row_sources_buf(
507
10.2k
            tablet->tablet_id(), dst_rowset_writer->context().tablet_path, reader_type);
508
10.2k
    Merger::Statistics total_stats;
509
10.3k
    if (stats_output != nullptr) {
510
10.3k
        total_stats.rowid_conversion = stats_output->rowid_conversion;
511
10.3k
    }
512
10.2k
    {
513
10.2k
        std::unique_lock<std::mutex> lock(tablet->sample_info_lock);
514
10.2k
        tablet->sample_infos.resize(column_groups.size());
515
10.2k
    }
516
    // compact group one by one
517
39.6k
    for (auto i = 0; i < column_groups.size(); ++i) {
518
29.3k
        VLOG_NOTICE << "row source size: " << row_sources_buf.total_size();
519
29.3k
        bool is_key = (i == 0);
520
29.3k
        int64_t batch_size = config::compaction_batch_size != -1
521
29.3k
                                     ? config::compaction_batch_size
522
29.3k
                                     : estimate_batch_size(i, tablet, merge_way_num);
523
29.3k
        CompactionSampleInfo sample_info;
524
29.3k
        Merger::Statistics group_stats;
525
29.3k
        group_stats.rowid_conversion = total_stats.rowid_conversion;
526
18.4E
        Merger::Statistics* group_stats_ptr = stats_output != nullptr ? &group_stats : nullptr;
527
29.3k
        Status st = vertical_compact_one_group(
528
29.3k
                tablet, reader_type, tablet_schema, is_key, column_groups[i], &row_sources_buf,
529
29.3k
                src_rowset_readers, dst_rowset_writer, max_rows_per_segment, group_stats_ptr,
530
29.3k
                key_group_cluster_key_idxes, batch_size, &sample_info, enable_sparse_optimization);
531
29.3k
        {
532
29.3k
            std::unique_lock<std::mutex> lock(tablet->sample_info_lock);
533
29.3k
            tablet->sample_infos[i] = sample_info;
534
29.3k
        }
535
29.3k
        RETURN_IF_ERROR(st);
536
29.3k
        if (stats_output != nullptr) {
537
29.3k
            total_stats.bytes_read_from_local += group_stats.bytes_read_from_local;
538
29.3k
            total_stats.bytes_read_from_remote += group_stats.bytes_read_from_remote;
539
29.3k
            total_stats.cached_bytes_total += group_stats.cached_bytes_total;
540
29.3k
            total_stats.cloud_local_read_time += group_stats.cloud_local_read_time;
541
29.3k
            total_stats.cloud_remote_read_time += group_stats.cloud_remote_read_time;
542
29.3k
            if (is_key) {
543
10.3k
                total_stats.output_rows = group_stats.output_rows;
544
10.3k
                total_stats.merged_rows = group_stats.merged_rows;
545
10.3k
                total_stats.filtered_rows = group_stats.filtered_rows;
546
10.3k
                total_stats.rowid_conversion = group_stats.rowid_conversion;
547
10.3k
            }
548
29.3k
        }
549
29.3k
        if (is_key) {
550
10.2k
            RETURN_IF_ERROR(row_sources_buf.flush());
551
10.2k
        }
552
29.3k
        RETURN_IF_ERROR(row_sources_buf.seek_to_begin());
553
29.3k
    }
554
555
    // Calculate and store density for next compaction's sparse optimization threshold
556
    // density = (total_cells - total_null_count) / total_cells
557
    // Smaller density means more sparse
558
10.2k
    {
559
10.2k
        std::unique_lock<std::mutex> lock(tablet->sample_info_lock);
560
10.2k
        int64_t total_null_count = 0;
561
29.4k
        for (const auto& info : tablet->sample_infos) {
562
29.4k
            total_null_count += info.null_count;
563
29.4k
        }
564
10.2k
        int64_t total_cells = total_rows * tablet_schema.num_columns();
565
10.2k
        if (total_cells > 0) {
566
5.91k
            double density = static_cast<double>(total_cells - total_null_count) /
567
5.91k
                             static_cast<double>(total_cells);
568
5.91k
            tablet->compaction_density.store(density);
569
5.91k
            LOG(INFO) << "Vertical compaction density update: tablet_id=" << tablet->tablet_id()
570
5.91k
                      << ", total_cells=" << total_cells
571
5.91k
                      << ", total_null_count=" << total_null_count << ", density=" << density;
572
5.91k
        }
573
10.2k
    }
574
575
    // finish compact, build output rowset
576
10.2k
    VLOG_NOTICE << "finish compact groups";
577
10.2k
    RETURN_IF_ERROR(dst_rowset_writer->final_flush());
578
579
10.3k
    if (stats_output != nullptr) {
580
10.3k
        *stats_output = total_stats;
581
10.3k
    }
582
583
10.2k
    return Status::OK();
584
10.2k
}
585
#include "common/compile_check_end.h"
586
} // namespace doris