Coverage Report

Created: 2026-08-06 07:53

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