Coverage Report

Created: 2026-08-14 04:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/sink/vrow_distribution.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 "exec/sink/vrow_distribution.h"
19
20
#include <gen_cpp/FrontendService.h>
21
#include <gen_cpp/FrontendService_types.h>
22
#include <glog/logging.h>
23
24
#include <cstdint>
25
#include <memory>
26
#include <string>
27
28
#include "common/cast_set.h"
29
#include "common/logging.h"
30
#include "common/status.h"
31
#include "core/assert_cast.h"
32
#include "core/column/column.h"
33
#include "core/column/column_const.h"
34
#include "core/column/column_nullable.h"
35
#include "core/column/column_vector.h"
36
#include "core/data_type/data_type.h"
37
#include "exec/sink/writer/vtablet_writer.h"
38
#include "runtime/cluster_info.h"
39
#include "runtime/exec_env.h"
40
#include "runtime/query_context.h"
41
#include "runtime/runtime_state.h"
42
#include "service/backend_options.h"
43
#include "util/client_cache.h"
44
#include "util/debug_points.h"
45
#include "util/thrift_rpc_helper.h"
46
47
namespace doris {
48
49
45.4k
std::pair<VExprContextSPtrs, VExprSPtrs> VRowDistribution::_get_partition_function() {
50
45.4k
    return {_vpartition->get_part_func_ctx(), _vpartition->get_partition_function()};
51
45.4k
}
52
53
Status VRowDistribution::_save_missing_values(
54
        const Block& input_block,
55
        std::vector<std::vector<std::string>>& col_strs, // non-const ref for move
56
        int col_size, Block* block, const std::vector<uint32_t>& filter,
57
186
        const std::vector<const NullMap*>& col_null_maps) {
58
    // de-duplication for new partitions but save all rows.
59
186
    RETURN_IF_ERROR(
60
186
            _batching_block->add_rows(&input_block, filter.data(), filter.data() + filter.size()));
61
186
    std::vector<TNullableStringLiteral> cur_row_values;
62
19.4k
    for (int row = 0; row < col_strs[0].size(); ++row) {
63
19.2k
        cur_row_values.clear();
64
38.4k
        for (int col = 0; col < col_size; ++col) {
65
19.2k
            TNullableStringLiteral node;
66
            // OlapTableBlockConvertor::_validate_data() materializes destination slots so won't be const.
67
19.2k
            const auto* null_map = col_null_maps[col]; // null map for this col
68
19.2k
            node.__set_is_null((null_map && (*null_map)[filter[row]])
69
19.2k
                                       ? true
70
19.2k
                                       : node.is_null); // if not, dont change(default false)
71
19.2k
            if (!node.is_null) {
72
19.2k
                node.__set_value(col_strs[col][row]);
73
19.2k
            }
74
19.2k
            cur_row_values.push_back(node);
75
19.2k
        }
76
19.2k
        if (!_deduper.contains(cur_row_values)) {
77
361
            _deduper.insert(cur_row_values);
78
361
            _partitions_need_create.emplace_back(cur_row_values);
79
361
        }
80
19.2k
    }
81
82
    // to avoid too large mem use
83
186
    if (_batching_block->rows() > _batch_size) {
84
2
        _deal_batched = true;
85
2
    }
86
186
    _batching_rows = _batching_block->rows();
87
186
    VLOG_NOTICE << "pushed some batching lines, now numbers = " << _batching_rows;
88
89
186
    return Status::OK();
90
186
}
91
92
175
void VRowDistribution::clear_batching_stats() {
93
175
    _partitions_need_create.clear();
94
175
    _batching_rows = 0;
95
175
    _batching_bytes = 0;
96
175
}
97
98
175
Status VRowDistribution::automatic_create_partition() {
99
175
    MonotonicStopWatch timer;
100
175
    if (_state->enable_profile() && _state->profile_level() >= 2) {
101
0
        timer.start();
102
0
    }
103
104
175
    SCOPED_TIMER(_add_partition_request_timer);
105
175
    TCreatePartitionRequest request;
106
175
    TCreatePartitionResult result;
107
175
    bool injected = false;
108
175
    std::string be_endpoint = BackendOptions::get_be_endpoint();
109
175
    request.__set_txn_id(_txn_id);
110
175
    request.__set_db_id(_vpartition->db_id());
111
175
    request.__set_table_id(_vpartition->table_id());
112
175
    request.__set_partitionValues(_partitions_need_create);
113
175
    request.__set_be_endpoint(be_endpoint);
114
175
    request.__set_load_to_single_tablet(_tablet_finder->is_find_tablet_every_sink());
115
175
    request.__set_enable_adaptive_random_bucket(_tablet_finder->is_adaptive_random_bucket());
116
175
    if (_state && _state->get_query_ctx()) {
117
        // Pass query_id to FE so it can determine if this is a multi-instance load by checking Coordinator
118
175
        request.__set_query_id(_state->get_query_ctx()->query_id());
119
175
    }
120
121
175
    DBUG_EXECUTE_IF("VRowDistribution.automatic_create_partition.inject_result", {
122
175
        DBUG_RUN_CALLBACK(&request, &result);
123
175
        injected = true;
124
175
    });
125
126
175
    VLOG_NOTICE << "automatic partition rpc begin request " << request;
127
175
    if (!injected) {
128
173
        std::shared_ptr<TNetworkAddress> master_addr;
129
173
        if (_vpartition->get_master_address() == nullptr) {
130
173
            auto* cluster_info = ExecEnv::GetInstance()->cluster_info();
131
173
            if (cluster_info == nullptr) {
132
0
                return Status::InternalError("cluster_info is null");
133
0
            }
134
173
            master_addr = std::make_shared<TNetworkAddress>(cluster_info->master_fe_addr);
135
173
        } else {
136
0
            master_addr = _vpartition->get_master_address();
137
0
        }
138
173
        int time_out = _state->execution_timeout() * 1000;
139
173
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
140
173
                master_addr->hostname, master_addr->port,
141
173
                [&request, &result](FrontendServiceConnection& client) {
142
173
                    client->createPartition(result, request);
143
173
                },
144
173
                time_out));
145
173
    }
146
147
175
    Status status(Status::create(result.status));
148
175
    VLOG_NOTICE << "automatic partition rpc end response " << result;
149
175
    if (result.status.status_code == TStatusCode::OK) {
150
        // Add new partitions before incremental open because adaptive random bucket builds
151
        // sender/receiver routing params from _vpartition.
152
175
        RETURN_IF_ERROR(_vpartition->add_partitions(result.partitions));
153
361
        for (const auto& part : result.partitions) {
154
361
            _new_partition_ids.insert(part.id);
155
361
            VLOG_TRACE << "record new id: " << part.id;
156
361
        }
157
175
        RETURN_IF_ERROR(_create_partition_callback(_caller, &result));
158
175
    }
159
160
    // Record this request's elapsed time
161
175
    if (_state->enable_profile() && _state->profile_level() >= 2) {
162
0
        int64_t elapsed_ns = timer.elapsed_time();
163
0
        _add_partition_request_times.push_back(elapsed_ns);
164
0
    }
165
175
    return status;
166
175
}
167
168
// for reuse the same create callback of create-partition
169
20
static TCreatePartitionResult cast_as_create_result(const TReplacePartitionResult& arg) {
170
20
    TCreatePartitionResult result;
171
20
    result.status = arg.status;
172
20
    result.nodes = arg.nodes;
173
20
    result.partitions = arg.partitions;
174
20
    result.tablets = arg.tablets;
175
20
    return result;
176
20
}
177
178
// use _partitions and replace them
179
57
Status VRowDistribution::_replace_overwriting_partition() {
180
57
    SCOPED_TIMER(_add_partition_request_timer); // also for replace_partition
181
57
    TReplacePartitionRequest request;
182
57
    TReplacePartitionResult result;
183
57
    bool injected = false;
184
57
    request.__set_overwrite_group_id(_vpartition->get_overwrite_group_id());
185
57
    request.__set_db_id(_vpartition->db_id());
186
57
    request.__set_table_id(_vpartition->table_id());
187
188
    // only request for partitions not recorded for replacement
189
57
    std::set<int64_t> id_deduper;
190
60.0k
    for (const auto* part : _partitions) {
191
60.0k
        if (part != nullptr) {
192
51.3k
            if (_new_partition_ids.contains(part->id)) {
193
                // this is a new partition. dont replace again.
194
46.2k
                VLOG_TRACE << "skip new partition: " << part->id;
195
46.2k
            } else {
196
                // request for replacement
197
5.04k
                id_deduper.insert(part->id);
198
5.04k
            }
199
51.3k
        } else if (_missing_map.empty()) {
200
            // no origin partition. and not allow to create.
201
6
            return Status::InvalidArgument(
202
6
                    "Cannot found origin partitions in auto detect overwriting, stop "
203
6
                    "processing");
204
6
        } // else: part is null and _missing_map is not empty. dealed outside using auto-partition way. nothing to do here.
205
60.0k
    }
206
51
    if (id_deduper.empty()) {
207
31
        return Status::OK(); // no need to request
208
31
    }
209
    // de-duplicate. there's no check in FE
210
20
    std::vector<int64_t> request_part_ids(id_deduper.begin(), id_deduper.end());
211
212
20
    request.__set_partition_ids(request_part_ids);
213
214
20
    std::string be_endpoint = BackendOptions::get_be_endpoint();
215
20
    request.__set_be_endpoint(be_endpoint);
216
20
    request.__set_load_to_single_tablet(_tablet_finder->is_find_tablet_every_sink());
217
20
    request.__set_enable_adaptive_random_bucket(_tablet_finder->is_adaptive_random_bucket());
218
20
    if (_state && _state->get_query_ctx()) {
219
        // Pass query_id to FE so it can determine if this is a multi-instance load by checking Coordinator
220
20
        request.__set_query_id(_state->get_query_ctx()->query_id());
221
20
    }
222
223
20
    DBUG_EXECUTE_IF("VRowDistribution.replace_overwriting_partition.inject_result", {
224
20
        DBUG_RUN_CALLBACK(&request, &result);
225
20
        injected = true;
226
20
    });
227
228
20
    VLOG_NOTICE << "auto detect replace partition request: " << request;
229
20
    if (!injected) {
230
19
        std::shared_ptr<TNetworkAddress> master_addr;
231
19
        if (_vpartition->get_master_address() == nullptr) {
232
19
            auto* cluster_info = ExecEnv::GetInstance()->cluster_info();
233
19
            if (cluster_info == nullptr) {
234
0
                return Status::InternalError("cluster_info is null");
235
0
            }
236
19
            master_addr = std::make_shared<TNetworkAddress>(cluster_info->master_fe_addr);
237
19
        } else {
238
0
            master_addr = _vpartition->get_master_address();
239
0
        }
240
19
        int time_out = _state->execution_timeout() * 1000;
241
19
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
242
19
                master_addr->hostname, master_addr->port,
243
19
                [&request, &result](FrontendServiceConnection& client) {
244
19
                    client->replacePartition(result, request);
245
19
                },
246
19
                time_out));
247
19
    }
248
249
20
    Status status(Status::create(result.status));
250
20
    VLOG_NOTICE << "auto detect replace partition result: " << result;
251
20
    if (result.status.status_code == TStatusCode::OK) {
252
        // record new partitions
253
32
        for (const auto& part : result.partitions) {
254
32
            _new_partition_ids.insert(part.id);
255
32
            VLOG_TRACE << "record new id: " << part.id;
256
32
        }
257
        // replace data in _partitions
258
        // Adaptive random bucket builds sender/receiver routing params from _vpartition during
259
        // incremental open, so the replacement must be visible first.
260
20
        RETURN_IF_ERROR(_vpartition->replace_partitions(request_part_ids, result.partitions));
261
        // Reuse the function as the args' structure are same. It adds nodes/locations.
262
20
        auto result_as_create = cast_as_create_result(result);
263
20
        RETURN_IF_ERROR(_create_partition_callback(_caller, &result_as_create));
264
20
    }
265
266
20
    return status;
267
20
}
268
269
void VRowDistribution::_get_tablet_ids(Block* block, int32_t index_idx,
270
40.7k
                                       std::vector<int64_t>& tablet_ids) {
271
40.7k
    tablet_ids.resize(block->rows());
272
33.5M
    for (int row_idx = 0; row_idx < block->rows(); row_idx++) {
273
33.4M
        if (_skip[row_idx]) {
274
20.5k
            continue;
275
20.5k
        }
276
33.4M
        auto& partition = _partitions[row_idx];
277
33.4M
        auto& tablet_index = _tablet_indexes[row_idx];
278
33.4M
        auto& index = partition->indexes[index_idx];
279
280
33.4M
        auto tablet_id = index.tablets[tablet_index];
281
33.4M
        tablet_ids[row_idx] = tablet_id;
282
33.4M
    }
283
40.7k
}
284
285
46.0k
void VRowDistribution::_filter_block_by_skip(Block* block, RowPartTabletIds& row_part_tablet_id) {
286
46.0k
    auto& row_ids = row_part_tablet_id.row_ids;
287
46.0k
    auto& partition_ids = row_part_tablet_id.partition_ids;
288
46.0k
    auto& tablet_ids = row_part_tablet_id.tablet_ids;
289
290
46.0k
    auto rows = block->rows();
291
    // row count of a block should not exceed UINT32_MAX
292
46.0k
    auto rows_uint32 = cast_set<uint32_t>(rows);
293
36.1M
    for (uint32_t i = 0; i < rows_uint32; i++) {
294
36.0M
        if (!_skip[i]) {
295
36.0M
            row_ids.emplace_back(i);
296
36.0M
            partition_ids.emplace_back(_partitions[i]->id);
297
36.0M
            if (!_tablet_finder->is_adaptive_random_bucket()) {
298
33.9M
                tablet_ids.emplace_back(_tablet_ids[i]);
299
33.9M
            }
300
36.0M
        }
301
36.0M
    }
302
46.0k
}
303
304
Status VRowDistribution::_filter_block_by_skip_and_where_clause(
305
35
        Block* block, const VExprContextSPtr& where_clause, RowPartTabletIds& row_part_tablet_id) {
306
    // TODO
307
    //SCOPED_RAW_TIMER(&_stat.where_clause_ns);
308
35
    ColumnPtr filter_column;
309
35
    RETURN_IF_ERROR(where_clause->execute(block, filter_column));
310
311
35
    auto& row_ids = row_part_tablet_id.row_ids;
312
35
    auto& partition_ids = row_part_tablet_id.partition_ids;
313
35
    auto& tablet_ids = row_part_tablet_id.tablet_ids;
314
35
    if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*filter_column)) {
315
29
        auto rows = block->rows();
316
        // row count of a block should not exceed UINT32_MAX
317
29
        auto rows_uint32 = cast_set<uint32_t>(rows);
318
58
        for (uint32_t i = 0; i < rows_uint32; i++) {
319
29
            if (nullable_column->get_bool_inline(i) && !_skip[i]) {
320
12
                row_ids.emplace_back(i);
321
12
                partition_ids.emplace_back(_partitions[i]->id);
322
12
                if (!_tablet_finder->is_adaptive_random_bucket()) {
323
12
                    tablet_ids.emplace_back(_tablet_ids[i]);
324
12
                }
325
12
            }
326
29
        }
327
29
    } else if (const auto* const_column = check_and_get_column<ColumnConst>(*filter_column)) {
328
1
        bool ret = const_column->get_bool(0);
329
1
        if (!ret) {
330
1
            return Status::OK();
331
1
        }
332
        // should we optimize?
333
0
        _filter_block_by_skip(block, row_part_tablet_id);
334
5
    } else {
335
5
        const auto& filter = assert_cast<const ColumnUInt8&>(*filter_column).get_data();
336
5
        auto rows = block->rows();
337
        // row count of a block should not exceed UINT32_MAX
338
5
        auto rows_uint32 = cast_set<uint32_t>(rows);
339
15
        for (uint32_t i = 0; i < rows_uint32; i++) {
340
10
            if (filter[i] != 0 && !_skip[i]) {
341
6
                row_ids.emplace_back(i);
342
6
                partition_ids.emplace_back(_partitions[i]->id);
343
6
                if (!_tablet_finder->is_adaptive_random_bucket()) {
344
6
                    tablet_ids.emplace_back(_tablet_ids[i]);
345
6
                }
346
6
            }
347
10
        }
348
5
    }
349
350
34
    return Status::OK();
351
35
}
352
353
Status VRowDistribution::_filter_block(Block* block,
354
45.0k
                                       std::vector<RowPartTabletIds>& row_part_tablet_ids) {
355
91.0k
    for (int i = 0; i < _schema->indexes().size(); i++) {
356
46.0k
        if (!_tablet_finder->is_adaptive_random_bucket()) {
357
40.7k
            _get_tablet_ids(block, i, _tablet_ids);
358
40.7k
        }
359
46.0k
        auto& where_clause = _schema->indexes()[i]->where_clause;
360
46.0k
        if (where_clause != nullptr) {
361
35
            RETURN_IF_ERROR(_filter_block_by_skip_and_where_clause(block, where_clause,
362
35
                                                                   row_part_tablet_ids[i]));
363
46.0k
        } else {
364
46.0k
            _filter_block_by_skip(block, row_part_tablet_ids[i]);
365
46.0k
        }
366
46.0k
    }
367
45.0k
    return Status::OK();
368
45.0k
}
369
370
Status VRowDistribution::_generate_rows_distribution_for_non_auto_partition(
371
44.6k
        Block* block, bool has_filtered_rows, std::vector<RowPartTabletIds>& row_part_tablet_ids) {
372
44.6k
    int num_rows = cast_set<int>(block->rows());
373
374
44.6k
    RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
375
44.6k
                                                 _tablet_indexes, _skip));
376
44.6k
    if (has_filtered_rows) {
377
668
        for (int i = 0; i < num_rows; i++) {
378
580
            _skip[i] = _skip[i] || _block_convertor->filter_map()[i];
379
580
        }
380
88
    }
381
44.6k
    RETURN_IF_ERROR(_filter_block(block, row_part_tablet_ids));
382
44.6k
    return Status::OK();
383
44.6k
}
384
385
Status VRowDistribution::_deal_missing_map(const Block& input_block, Block* block,
386
                                           const std::vector<uint16_t>& partition_cols_idx,
387
186
                                           int64_t& rows_stat_val) {
388
    // for missing partition keys, calc the missing partition and save in _partitions_need_create
389
186
    auto [part_ctxs, part_exprs] = _get_partition_function();
390
186
    int part_col_num = cast_set<int>(part_exprs.size());
391
    // the two vectors are in column-first-order
392
186
    std::vector<std::vector<std::string>> col_strs;
393
186
    std::vector<const NullMap*> col_null_maps;
394
186
    col_strs.resize(part_col_num);
395
186
    col_null_maps.reserve(part_col_num);
396
397
186
    auto format_options = DataTypeSerDe::get_default_format_options();
398
186
    format_options.timezone = &_state->timezone_obj();
399
400
381
    for (int i = 0; i < part_col_num; ++i) {
401
195
        auto return_type = part_exprs[i]->data_type();
402
        // expose the data column. the return type would be nullable
403
195
        const auto& [range_left_col, col_const] =
404
195
                unpack_if_const(block->get_by_position(partition_cols_idx[i]).column);
405
195
        if (range_left_col->is_nullable()) {
406
56
            col_null_maps.push_back(&(
407
56
                    assert_cast<const ColumnNullable*>(range_left_col.get())->get_null_map_data()));
408
139
        } else {
409
139
            col_null_maps.push_back(nullptr);
410
139
        }
411
19.2k
        for (auto row : _missing_map) {
412
19.2k
            col_strs[i].push_back(return_type->to_string(
413
19.2k
                    *range_left_col, index_check_const(row, col_const), format_options));
414
19.2k
        }
415
195
    }
416
417
    // calc the end value and save them. in the end of sending, we will create partitions for them and deal them.
418
    // NOTE: must save old batching stats before calling _save_missing_values(),
419
    // because _save_missing_values() will update _batching_rows internally.
420
186
    size_t old_bt_rows = _batching_rows;
421
186
    size_t old_bt_bytes = _batching_bytes;
422
423
186
    RETURN_IF_ERROR(_save_missing_values(input_block, col_strs, part_col_num, block, _missing_map,
424
186
                                         col_null_maps));
425
426
186
    size_t new_bt_rows = _batching_block->rows();
427
186
    size_t new_bt_bytes = _batching_block->bytes();
428
186
    rows_stat_val -= new_bt_rows - old_bt_rows;
429
186
    _state->update_num_rows_load_total(old_bt_rows - new_bt_rows);
430
186
    _state->update_num_bytes_load_total(old_bt_bytes - new_bt_bytes);
431
432
186
    return Status::OK();
433
186
}
434
435
Status VRowDistribution::_generate_rows_distribution_for_auto_partition(
436
        const Block& input_block, Block* block, const std::vector<uint16_t>& partition_cols_idx,
437
        bool has_filtered_rows, std::vector<RowPartTabletIds>& row_part_tablet_ids,
438
350
        int64_t& rows_stat_val) {
439
350
    int num_rows = cast_set<int>(block->rows());
440
350
    std::vector<uint16_t> partition_keys = _vpartition->get_partition_keys();
441
442
350
    auto& partition_col = block->get_by_position(partition_keys[0]);
443
350
    _missing_map.clear();
444
350
    _missing_map.reserve(partition_col.column->size());
445
446
350
    RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
447
350
                                                 _tablet_indexes, _skip, &_missing_map));
448
449
    // the missing vals for auto partition are also skipped.
450
350
    if (has_filtered_rows) {
451
8
        for (int i = 0; i < num_rows; i++) {
452
4
            _skip[i] = _skip[i] || _block_convertor->filter_map()[i];
453
4
        }
454
4
    }
455
350
    RETURN_IF_ERROR(_filter_block(block, row_part_tablet_ids));
456
457
350
    if (!_missing_map.empty()) {
458
178
        RETURN_IF_ERROR(_deal_missing_map(input_block, block, partition_cols_idx,
459
178
                                          rows_stat_val)); // send input block to save
460
178
    }
461
350
    return Status::OK();
462
350
}
463
464
Status VRowDistribution::_generate_rows_distribution_for_auto_overwrite(
465
        const Block& input_block, Block* block, const std::vector<uint16_t>& partition_cols_idx,
466
        bool has_filtered_rows, std::vector<RowPartTabletIds>& row_part_tablet_ids,
467
57
        int64_t& rows_stat_val) {
468
57
    int num_rows = cast_set<int>(block->rows());
469
470
    // for non-auto-partition situation, goes into two 'else' branch. just find the origin partitions, replace them by rpc,
471
    //  and find the new partitions to use.
472
    // for auto-partition's, find and save origins in _partitions and replace them. at meanwhile save the missing values for auto
473
    //  partition. then we find partition again to get replaced partitions in _partitions. this time _missing_map is ignored cuz
474
    //  we already saved missing values.
475
57
    if (_vpartition->is_auto_partition() &&
476
57
        _state->query_options().enable_auto_create_when_overwrite) {
477
        // allow auto create partition for missing rows.
478
33
        std::vector<uint16_t> partition_keys = _vpartition->get_partition_keys();
479
33
        auto partition_col = block->get_by_position(partition_keys[0]);
480
33
        _missing_map.clear();
481
33
        _missing_map.reserve(partition_col.column->size());
482
483
33
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
484
33
                                                     _tablet_indexes, _skip, &_missing_map));
485
486
        // allow and really need to create during auto-detect-overwriting.
487
33
        if (!_missing_map.empty()) {
488
8
            RETURN_IF_ERROR(
489
8
                    _deal_missing_map(input_block, block, partition_cols_idx, rows_stat_val));
490
8
        }
491
33
    } else {
492
24
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
493
24
                                                     _tablet_indexes, _skip));
494
24
    }
495
57
    RETURN_IF_ERROR(_replace_overwriting_partition());
496
497
    // regenerate locations for new partitions & tablets
498
51
    _reset_find_tablets(num_rows);
499
51
    if (_vpartition->is_auto_partition() &&
500
51
        _state->query_options().enable_auto_create_when_overwrite) {
501
        // here _missing_map is just a placeholder
502
33
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
503
33
                                                     _tablet_indexes, _skip, &_missing_map));
504
33
        if (VLOG_TRACE_IS_ON) {
505
0
            std::string tmp;
506
0
            for (auto v : _missing_map) {
507
0
                tmp += std::to_string(v).append(", ");
508
0
            }
509
0
            VLOG_TRACE << "Trace missing map of " << this << ':' << tmp;
510
0
        }
511
33
    } else {
512
18
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
513
18
                                                     _tablet_indexes, _skip));
514
18
    }
515
51
    if (has_filtered_rows) {
516
0
        for (int i = 0; i < num_rows; i++) {
517
0
            _skip[i] = _skip[i] || _block_convertor->filter_map()[i];
518
0
        }
519
0
    }
520
51
    RETURN_IF_ERROR(_filter_block(block, row_part_tablet_ids));
521
51
    return Status::OK();
522
51
}
523
524
void VRowDistribution::_reset_row_part_tablet_ids(
525
45.0k
        std::vector<RowPartTabletIds>& row_part_tablet_ids, int64_t rows) {
526
45.0k
    row_part_tablet_ids.resize(_schema->indexes().size());
527
46.0k
    for (auto& row_part_tablet_id : row_part_tablet_ids) {
528
46.0k
        auto& row_ids = row_part_tablet_id.row_ids;
529
46.0k
        auto& partition_ids = row_part_tablet_id.partition_ids;
530
46.0k
        auto& tablet_ids = row_part_tablet_id.tablet_ids;
531
532
46.0k
        row_ids.clear();
533
46.0k
        partition_ids.clear();
534
46.0k
        tablet_ids.clear();
535
        // This is important for performance.
536
46.0k
        row_ids.reserve(rows);
537
46.0k
        partition_ids.reserve(rows);
538
46.0k
        if (!_tablet_finder->is_adaptive_random_bucket()) {
539
40.7k
            tablet_ids.reserve(rows);
540
40.7k
        }
541
46.0k
    }
542
45.0k
}
543
544
Status VRowDistribution::generate_rows_distribution(
545
        Block& input_block, std::shared_ptr<Block>& block,
546
45.0k
        std::vector<RowPartTabletIds>& row_part_tablet_ids, int64_t& rows_stat_val) {
547
45.0k
    auto input_rows = input_block.rows();
548
45.0k
    _reset_row_part_tablet_ids(row_part_tablet_ids, input_rows);
549
550
    // we store the batching block with value of `input_block`. so just do all of these again.
551
45.0k
    bool has_filtered_rows = false;
552
45.0k
    RETURN_IF_ERROR(_block_convertor->validate_and_convert_block(
553
45.0k
            _state, &input_block, block, *_vec_output_expr_ctxs, input_rows, has_filtered_rows));
554
555
    // batching block rows which need new partitions. deal together at finish.
556
45.0k
    if (!_batching_block) [[unlikely]] {
557
36.3k
        std::unique_ptr<Block> tmp_block = input_block.create_same_struct_block(0);
558
36.3k
        _batching_block = MutableBlock::create_unique(std::move(*tmp_block));
559
36.3k
    }
560
561
45.0k
    auto num_rows = block->rows();
562
45.0k
    _reset_find_tablets(num_rows);
563
564
    // if there's projection of partition calc, we need to calc it first.
565
45.0k
    auto [part_ctxs, part_funcs] = _get_partition_function();
566
45.0k
    std::vector<uint16_t> partition_cols_idx;
567
45.0k
    if (_vpartition->is_projection_partition()) {
568
        // calc the start value of missing partition ranges.
569
556
        auto func_size = part_funcs.size();
570
1.23k
        for (int i = 0; i < func_size; ++i) {
571
676
            int result_idx = -1;
572
            // we just calc left range here. leave right to FE to avoid dup calc.
573
676
            RETURN_IF_ERROR(part_funcs[i]->execute(part_ctxs[i].get(), block.get(), &result_idx));
574
575
676
            VLOG_DEBUG << "Partition-calculated block:\n" << block->dump_data(0, 1);
576
676
            DCHECK(result_idx != -1);
577
578
676
            partition_cols_idx.push_back(cast_set<uint16_t>(result_idx));
579
676
        }
580
581
        // change the column to compare to transformed.
582
556
        _vpartition->set_transformed_slots(partition_cols_idx);
583
556
    }
584
585
45.0k
    Status st = Status::OK();
586
45.0k
    if (_vpartition->is_auto_detect_overwrite() && !_deal_batched) {
587
        // when overwrite, no auto create partition allowed.
588
57
        st = _generate_rows_distribution_for_auto_overwrite(input_block, block.get(),
589
57
                                                            partition_cols_idx, has_filtered_rows,
590
57
                                                            row_part_tablet_ids, rows_stat_val);
591
44.9k
    } else if (_vpartition->is_auto_partition() && !_deal_batched) {
592
350
        st = _generate_rows_distribution_for_auto_partition(input_block, block.get(),
593
350
                                                            partition_cols_idx, has_filtered_rows,
594
350
                                                            row_part_tablet_ids, rows_stat_val);
595
44.6k
    } else { // not auto partition
596
44.6k
        st = _generate_rows_distribution_for_non_auto_partition(block.get(), has_filtered_rows,
597
44.6k
                                                                row_part_tablet_ids);
598
44.6k
    }
599
600
45.0k
    return st;
601
45.0k
}
602
603
// reuse vars for find_tablets
604
45.0k
void VRowDistribution::_reset_find_tablets(int64_t rows) {
605
45.0k
    _tablet_finder->filter_bitmap().Reset(rows);
606
45.0k
    _partitions.assign(rows, nullptr);
607
45.0k
    _skip.assign(rows, false);
608
45.0k
    _tablet_indexes.assign(rows, 0);
609
45.0k
}
610
611
} // namespace doris