Coverage Report

Created: 2026-07-07 22:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/exchange/local_exchanger.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/exchange/local_exchanger.h"
19
20
#include "common/cast_set.h"
21
#include "common/status.h"
22
#include "exec/exchange/local_exchange_sink_operator.h"
23
#include "exec/exchange/local_exchange_source_operator.h"
24
#include "exec/partitioner/partitioner.h"
25
26
namespace doris {
27
template <typename BlockType>
28
void Exchanger<BlockType>::_enqueue_data_and_set_ready(int channel_id,
29
                                                       LocalExchangeSinkLocalState* local_state,
30
324
                                                       BlockType&& block) {
31
324
    if (local_state == nullptr) {
32
0
        _enqueue_data_and_set_ready(channel_id, std::move(block));
33
0
        return;
34
0
    }
35
    // PartitionedBlock is used by shuffle exchanger.
36
    // PartitionedBlock will be push into multiple queues with different row ranges, so it will be
37
    // referenced multiple times. Otherwise, we only ref the block once because it is only push into
38
    // one queue.
39
324
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
242
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
242
        block.first->record_channel_id(channel_id);
43
242
    } else {
44
82
        block->record_channel_id(channel_id);
45
82
    }
46
47
324
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
260
        local_state->_shared_state->set_ready_to_read(channel_id);
49
260
    }
50
324
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
114
                                                       BlockType&& block) {
31
114
    if (local_state == nullptr) {
32
0
        _enqueue_data_and_set_ready(channel_id, std::move(block));
33
0
        return;
34
0
    }
35
    // PartitionedBlock is used by shuffle exchanger.
36
    // PartitionedBlock will be push into multiple queues with different row ranges, so it will be
37
    // referenced multiple times. Otherwise, we only ref the block once because it is only push into
38
    // one queue.
39
114
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
114
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
114
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
114
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
98
        local_state->_shared_state->set_ready_to_read(channel_id);
49
98
    }
50
114
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS4_
Line
Count
Source
30
82
                                                       BlockType&& block) {
31
82
    if (local_state == nullptr) {
32
0
        _enqueue_data_and_set_ready(channel_id, std::move(block));
33
0
        return;
34
0
    }
35
    // PartitionedBlock is used by shuffle exchanger.
36
    // PartitionedBlock will be push into multiple queues with different row ranges, so it will be
37
    // referenced multiple times. Otherwise, we only ref the block once because it is only push into
38
    // one queue.
39
82
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
        block.first->record_channel_id(channel_id);
43
82
    } else {
44
82
        block->record_channel_id(channel_id);
45
82
    }
46
47
82
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
66
        local_state->_shared_state->set_ready_to_read(channel_id);
49
66
    }
50
82
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
128
                                                       BlockType&& block) {
31
128
    if (local_state == nullptr) {
32
0
        _enqueue_data_and_set_ready(channel_id, std::move(block));
33
0
        return;
34
0
    }
35
    // PartitionedBlock is used by shuffle exchanger.
36
    // PartitionedBlock will be push into multiple queues with different row ranges, so it will be
37
    // referenced multiple times. Otherwise, we only ref the block once because it is only push into
38
    // one queue.
39
128
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
128
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
128
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
128
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
96
        local_state->_shared_state->set_ready_to_read(channel_id);
49
96
    }
50
128
}
51
52
template <typename BlockType>
53
bool Exchanger<BlockType>::_dequeue_data(LocalExchangeSourceLocalState* local_state,
54
                                         BlockType& block, bool* eos, Block* data_block,
55
418
                                         int channel_id) {
56
418
    if (local_state == nullptr) {
57
40
        return _dequeue_data(block, eos, data_block, channel_id);
58
40
    }
59
378
    bool all_finished = _running_sink_operators == 0;
60
378
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
186
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
186
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
186
        } else {
65
66
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
66
            data_block->swap(block->_data_block);
67
66
        }
68
252
        return true;
69
252
    } else if (all_finished) {
70
34
        *eos = true;
71
92
    } else {
72
92
        std::unique_lock l(*_m[channel_id]);
73
92
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
0
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
0
                local_state->_shared_state->sub_mem_usage(channel_id,
77
0
                                                          block.first->_allocated_bytes);
78
0
            } else {
79
0
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
0
                data_block->swap(block->_data_block);
81
0
            }
82
0
            return true;
83
0
        }
84
92
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
92
        local_state->_dependency->block();
86
92
    }
87
126
    return false;
88
378
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
178
                                         int channel_id) {
56
178
    if (local_state == nullptr) {
57
16
        return _dequeue_data(block, eos, data_block, channel_id);
58
16
    }
59
162
    bool all_finished = _running_sink_operators == 0;
60
162
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
90
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
90
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
        } else {
65
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
            data_block->swap(block->_data_block);
67
        }
68
90
        return true;
69
90
    } else if (all_finished) {
70
16
        *eos = true;
71
56
    } else {
72
56
        std::unique_lock l(*_m[channel_id]);
73
56
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
0
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
0
                local_state->_shared_state->sub_mem_usage(channel_id,
77
0
                                                          block.first->_allocated_bytes);
78
            } else {
79
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
                data_block->swap(block->_data_block);
81
            }
82
0
            return true;
83
0
        }
84
56
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
56
        local_state->_dependency->block();
86
56
    }
87
72
    return false;
88
162
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS4_PbPNS_5BlockEi
Line
Count
Source
55
112
                                         int channel_id) {
56
112
    if (local_state == nullptr) {
57
16
        return _dequeue_data(block, eos, data_block, channel_id);
58
16
    }
59
96
    bool all_finished = _running_sink_operators == 0;
60
96
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
66
        } else {
65
66
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
66
            data_block->swap(block->_data_block);
67
66
        }
68
66
        return true;
69
66
    } else if (all_finished) {
70
10
        *eos = true;
71
20
    } else {
72
20
        std::unique_lock l(*_m[channel_id]);
73
20
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
                local_state->_shared_state->sub_mem_usage(channel_id,
77
                                                          block.first->_allocated_bytes);
78
0
            } else {
79
0
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
0
                data_block->swap(block->_data_block);
81
0
            }
82
0
            return true;
83
0
        }
84
20
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
20
        local_state->_dependency->block();
86
20
    }
87
30
    return false;
88
96
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
128
                                         int channel_id) {
56
128
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
120
    bool all_finished = _running_sink_operators == 0;
60
120
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
96
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
96
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
        } else {
65
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
            data_block->swap(block->_data_block);
67
        }
68
96
        return true;
69
96
    } else if (all_finished) {
70
8
        *eos = true;
71
16
    } else {
72
16
        std::unique_lock l(*_m[channel_id]);
73
16
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
0
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
0
                local_state->_shared_state->sub_mem_usage(channel_id,
77
0
                                                          block.first->_allocated_bytes);
78
            } else {
79
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
                data_block->swap(block->_data_block);
81
            }
82
0
            return true;
83
0
        }
84
16
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
16
        local_state->_dependency->block();
86
16
    }
87
24
    return false;
88
120
}
89
90
template <typename BlockType>
91
0
void Exchanger<BlockType>::_enqueue_data_and_set_ready(int channel_id, BlockType&& block) {
92
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
93
0
                  std::is_same_v<BroadcastBlock, BlockType>) {
94
0
        block.first->record_channel_id(channel_id);
95
0
    } else {
96
0
        block->record_channel_id(channel_id);
97
0
    }
98
0
    _data_queue[channel_id].enqueue(std::move(block));
99
0
}
Unexecuted instantiation: _ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE27_enqueue_data_and_set_readyEiOS7_
Unexecuted instantiation: _ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE27_enqueue_data_and_set_readyEiOS4_
Unexecuted instantiation: _ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE27_enqueue_data_and_set_readyEiOS7_
100
101
template <typename BlockType>
102
bool Exchanger<BlockType>::_dequeue_data(BlockType& block, bool* eos, Block* data_block,
103
40
                                         int channel_id) {
104
40
    if (_data_queue[channel_id].try_dequeue(block)) {
105
        if constexpr (!std::is_same_v<PartitionedBlock, BlockType> &&
106
0
                      !std::is_same_v<BroadcastBlock, BlockType>) {
107
0
            data_block->swap(block->_data_block);
108
0
        }
109
0
        return true;
110
0
    }
111
40
    return false;
112
40
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_dequeue_dataERS7_PbPNS_5BlockEi
Line
Count
Source
103
16
                                         int channel_id) {
104
16
    if (_data_queue[channel_id].try_dequeue(block)) {
105
        if constexpr (!std::is_same_v<PartitionedBlock, BlockType> &&
106
                      !std::is_same_v<BroadcastBlock, BlockType>) {
107
            data_block->swap(block->_data_block);
108
        }
109
0
        return true;
110
0
    }
111
16
    return false;
112
16
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataERS4_PbPNS_5BlockEi
Line
Count
Source
103
16
                                         int channel_id) {
104
16
    if (_data_queue[channel_id].try_dequeue(block)) {
105
        if constexpr (!std::is_same_v<PartitionedBlock, BlockType> &&
106
0
                      !std::is_same_v<BroadcastBlock, BlockType>) {
107
0
            data_block->swap(block->_data_block);
108
0
        }
109
0
        return true;
110
0
    }
111
16
    return false;
112
16
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataERS7_PbPNS_5BlockEi
Line
Count
Source
103
8
                                         int channel_id) {
104
8
    if (_data_queue[channel_id].try_dequeue(block)) {
105
        if constexpr (!std::is_same_v<PartitionedBlock, BlockType> &&
106
                      !std::is_same_v<BroadcastBlock, BlockType>) {
107
            data_block->swap(block->_data_block);
108
        }
109
0
        return true;
110
0
    }
111
8
    return false;
112
8
}
113
114
Status ShuffleExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
115
44
                              SinkInfo& sink_info) {
116
44
    if (in_block->empty()) {
117
0
        return Status::OK();
118
0
    }
119
44
    {
120
44
        SCOPED_TIMER(profile.compute_hash_value_timer);
121
44
        RETURN_IF_ERROR(sink_info.partitioner->do_partitioning(state, in_block));
122
44
    }
123
44
    {
124
44
        SCOPED_TIMER(profile.distribute_timer);
125
44
        RETURN_IF_ERROR(_split_rows(state, sink_info.partitioner->get_channel_ids(), in_block,
126
44
                                    *sink_info.channel_id, sink_info.local_state,
127
44
                                    sink_info.shuffle_idx_to_instance_idx));
128
44
    }
129
130
42
    sink_info.local_state->_memory_used_counter->set(
131
42
            sink_info.local_state->_shared_state->mem_usage);
132
42
    return Status::OK();
133
44
}
134
135
8
void ShuffleExchanger::close(SourceInfo&& source_info) {
136
8
    PartitionedBlock partitioned_block;
137
8
    bool eos;
138
8
    Block block;
139
8
    _data_queue[source_info.channel_id].set_eos();
140
8
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
141
8
                         source_info.channel_id)) {
142
        // do nothing
143
0
    }
144
8
}
145
146
Status ShuffleExchanger::get_block(RuntimeState* state, Block* block, bool* eos, Profile&& profile,
147
26
                                   SourceInfo&& source_info) {
148
26
    PartitionedBlock partitioned_block;
149
26
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
150
26
                      source_info.channel_id)) {
151
18
        SCOPED_TIMER(profile.copy_data_timer);
152
18
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
153
18
                block, partitioned_block.first->_data_block);
154
18
        auto& mutable_block = scoped_mutable_block.mutable_block();
155
26
        do {
156
26
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
157
26
                                       partitioned_block.second.offset_start;
158
26
            auto block_wrapper = partitioned_block.first;
159
26
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
160
26
                                                   offset_start + partitioned_block.second.length));
161
26
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
162
24
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
163
24
                               source_info.channel_id));
164
18
    }
165
24
    return Status::OK();
166
26
}
167
168
Status ShuffleExchanger::_split_rows(RuntimeState* state, const std::vector<uint32_t>& channel_ids,
169
                                     Block* block, int channel_id,
170
                                     LocalExchangeSinkLocalState* local_state,
171
44
                                     std::map<int, int>* shuffle_idx_to_instance_idx) {
172
44
    if (local_state == nullptr) {
173
0
        return _split_rows(state, channel_ids, block, channel_id);
174
0
    }
175
44
    const auto rows = cast_set<int32_t>(block->rows());
176
44
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
177
44
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
178
44
    {
179
44
        partition_rows_histogram.assign(_num_partitions + 1, 0);
180
468
        for (int32_t i = 0; i < rows; ++i) {
181
424
            partition_rows_histogram[channel_ids[i]]++;
182
424
        }
183
214
        for (int32_t i = 1; i <= _num_partitions; ++i) {
184
170
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
185
170
        }
186
468
        for (int32_t i = rows - 1; i >= 0; --i) {
187
424
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
188
424
            partition_rows_histogram[channel_ids[i]]--;
189
424
        }
190
44
    }
191
192
44
    Block data_block;
193
44
    std::shared_ptr<BlockWrapper> new_block_wrapper;
194
44
    if (!_free_blocks.try_dequeue(data_block)) {
195
30
        data_block = block->clone_empty();
196
30
    }
197
44
    data_block.swap(*block);
198
44
    new_block_wrapper =
199
44
            BlockWrapper::create_shared(std::move(data_block), local_state->_shared_state, -1);
200
44
    if (new_block_wrapper->_data_block.empty()) {
201
0
        return Status::OK();
202
0
    }
203
    /**
204
     * Data are hash-shuffled and distributed to all instances of
205
     * all BEs. So we need a shuffleId-To-InstanceId mapping.
206
     * For example, row 1 get a hash value 1 which means we should distribute to instance 1 on
207
     * BE 1 and row 2 get a hash value 2 which means we should distribute to instance 1 on BE 3.
208
     */
209
44
    DCHECK(shuffle_idx_to_instance_idx && !shuffle_idx_to_instance_idx->empty());
210
44
    const auto& map = *shuffle_idx_to_instance_idx;
211
44
    int32_t enqueue_rows = 0;
212
168
    for (const auto& it : map) {
213
168
        DCHECK(it.second >= 0 && it.second < _num_partitions)
214
0
                << it.first << " : " << it.second << " " << _num_partitions;
215
168
        uint32_t start = partition_rows_histogram[it.first];
216
168
        uint32_t size = partition_rows_histogram[it.first + 1] - start;
217
168
        if (size > 0) {
218
42
            enqueue_rows += size;
219
42
            _enqueue_data_and_set_ready(
220
42
                    it.second, local_state,
221
42
                    {new_block_wrapper,
222
42
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
223
42
        }
224
168
    }
225
44
    if (enqueue_rows != rows) [[unlikely]] {
226
2
        fmt::memory_buffer debug_string_buffer;
227
2
        fmt::format_to(debug_string_buffer, "Type: {}, Local Exchange Id: {}, Shuffled Map: ",
228
2
                       get_exchange_type_name(get_type()), local_state->parent()->node_id());
229
6
        for (const auto& it : map) {
230
6
            fmt::format_to(debug_string_buffer, "[{}:{}], ", it.first, it.second);
231
6
        }
232
2
        return Status::InternalError(
233
2
                "Rows mismatched! Data may be lost. [Expected enqueue rows={}, Real enqueue "
234
2
                "rows={}, Detail: {}]",
235
2
                rows, enqueue_rows, fmt::to_string(debug_string_buffer));
236
2
    }
237
238
42
    return Status::OK();
239
44
}
240
241
Status ShuffleExchanger::_split_rows(RuntimeState* state, const std::vector<uint32_t>& channel_ids,
242
0
                                     Block* block, int channel_id) {
243
0
    const auto rows = cast_set<int32_t>(block->rows());
244
0
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
245
0
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
246
0
    {
247
0
        partition_rows_histogram.assign(_num_partitions + 1, 0);
248
0
        for (int32_t i = 0; i < rows; ++i) {
249
0
            partition_rows_histogram[channel_ids[i]]++;
250
0
        }
251
0
        for (int32_t i = 1; i <= _num_partitions; ++i) {
252
0
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
253
0
        }
254
0
        for (int32_t i = rows - 1; i >= 0; --i) {
255
0
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
256
0
            partition_rows_histogram[channel_ids[i]]--;
257
0
        }
258
0
    }
259
260
0
    Block data_block;
261
0
    std::shared_ptr<BlockWrapper> new_block_wrapper;
262
0
    if (!_free_blocks.try_dequeue(data_block)) {
263
0
        data_block = block->clone_empty();
264
0
    }
265
0
    data_block.swap(*block);
266
0
    new_block_wrapper = BlockWrapper::create_shared(std::move(data_block), nullptr, -1);
267
0
    if (new_block_wrapper->_data_block.empty()) {
268
0
        return Status::OK();
269
0
    }
270
0
    for (int i = 0; i < _num_partitions; i++) {
271
0
        uint32_t start = partition_rows_histogram[i];
272
0
        uint32_t size = partition_rows_histogram[i + 1] - start;
273
0
        if (size > 0) {
274
0
            _enqueue_data_and_set_ready(
275
0
                    i, {new_block_wrapper,
276
0
                        {.row_idxs = row_idx, .offset_start = start, .length = size}});
277
0
        }
278
0
    }
279
280
0
    return Status::OK();
281
0
}
282
283
Status PassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
284
56
                                  SinkInfo& sink_info) {
285
56
    if (in_block->empty()) {
286
0
        return Status::OK();
287
0
    }
288
56
    Block new_block;
289
56
    if (!_free_blocks.try_dequeue(new_block)) {
290
42
        new_block = {in_block->clone_empty()};
291
42
    }
292
56
    new_block.swap(*in_block);
293
56
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
294
56
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
295
56
            std::move(new_block),
296
56
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, channel_id);
297
298
56
    _enqueue_data_and_set_ready(channel_id, sink_info.local_state, std::move(wrapper));
299
300
56
    sink_info.local_state->_memory_used_counter->set(
301
56
            sink_info.local_state->_shared_state->mem_usage);
302
303
56
    return Status::OK();
304
56
}
305
306
8
void PassthroughExchanger::close(SourceInfo&& source_info) {
307
8
    Block next_block;
308
8
    BlockWrapperSPtr wrapper;
309
8
    bool eos;
310
8
    _data_queue[source_info.channel_id].set_eos();
311
8
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
312
8
                         source_info.channel_id)) {
313
        // do nothing
314
0
    }
315
8
}
316
317
8
void PassToOneExchanger::close(SourceInfo&& source_info) {
318
8
    Block next_block;
319
8
    BlockWrapperSPtr wrapper;
320
8
    bool eos;
321
8
    _data_queue[source_info.channel_id].set_eos();
322
8
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
323
8
                         source_info.channel_id)) {
324
        // do nothing
325
0
    }
326
8
}
327
328
Status PassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
329
72
                                       Profile&& profile, SourceInfo&& source_info) {
330
72
    BlockWrapperSPtr next_block;
331
72
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
332
72
    return Status::OK();
333
72
}
334
335
Status PassToOneExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
336
26
                                SinkInfo& sink_info) {
337
26
    if (in_block->empty()) {
338
0
        return Status::OK();
339
0
    }
340
26
    Block new_block;
341
26
    if (!_free_blocks.try_dequeue(new_block)) {
342
18
        new_block = {in_block->clone_empty()};
343
18
    }
344
26
    new_block.swap(*in_block);
345
346
26
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
347
26
            std::move(new_block),
348
26
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, 0);
349
26
    _enqueue_data_and_set_ready(0, sink_info.local_state, std::move(wrapper));
350
351
26
    sink_info.local_state->_memory_used_counter->set(
352
26
            sink_info.local_state->_shared_state->mem_usage);
353
354
26
    return Status::OK();
355
26
}
356
357
Status PassToOneExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
358
30
                                     Profile&& profile, SourceInfo&& source_info) {
359
30
    if (source_info.channel_id != 0) {
360
6
        *eos = true;
361
6
        return Status::OK();
362
6
    }
363
24
    BlockWrapperSPtr next_block;
364
24
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
365
24
    return Status::OK();
366
30
}
367
368
10
void ExchangerBase::finalize() {
369
10
    DCHECK(_running_source_operators == 0);
370
10
    Block block;
371
98
    while (_free_blocks.try_dequeue(block)) {
372
        // do nothing
373
88
    }
374
10
}
375
376
Status BroadcastExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
377
32
                                SinkInfo& sink_info) {
378
32
    if (in_block->empty()) {
379
0
        return Status::OK();
380
0
    }
381
32
    Block new_block;
382
32
    if (!_free_blocks.try_dequeue(new_block)) {
383
18
        new_block = {in_block->clone_empty()};
384
18
    }
385
32
    new_block.swap(*in_block);
386
32
    auto wrapper = BlockWrapper::create_shared(
387
32
            std::move(new_block),
388
32
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1);
389
160
    for (int i = 0; i < _num_partitions; i++) {
390
128
        _enqueue_data_and_set_ready(
391
128
                i, sink_info.local_state,
392
128
                {wrapper, {.offset_start = 0, .length = wrapper->_data_block.rows()}});
393
128
    }
394
395
32
    return Status::OK();
396
32
}
397
398
8
void BroadcastExchanger::close(SourceInfo&& source_info) {
399
8
    BroadcastBlock partitioned_block;
400
8
    bool eos;
401
8
    Block block;
402
8
    _data_queue[source_info.channel_id].set_eos();
403
8
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
404
8
                         source_info.channel_id)) {
405
        // do nothing
406
0
    }
407
8
}
408
409
Status BroadcastExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
410
120
                                     Profile&& profile, SourceInfo&& source_info) {
411
120
    BroadcastBlock partitioned_block;
412
413
120
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
414
120
                      source_info.channel_id)) {
415
96
        SCOPED_TIMER(profile.copy_data_timer);
416
96
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
417
96
                block, partitioned_block.first->_data_block);
418
96
        auto& mutable_block = scoped_mutable_block.mutable_block();
419
96
        auto block_wrapper = partitioned_block.first;
420
96
        RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block,
421
96
                                               partitioned_block.second.offset_start,
422
96
                                               partitioned_block.second.length));
423
96
    }
424
425
120
    return Status::OK();
426
120
}
427
428
Status AdaptivePassthroughExchanger::_passthrough_sink(RuntimeState* state, Block* in_block,
429
40
                                                       SinkInfo& sink_info) {
430
40
    Block new_block;
431
40
    if (!_free_blocks.try_dequeue(new_block)) {
432
26
        new_block = {in_block->clone_empty()};
433
26
    }
434
40
    new_block.swap(*in_block);
435
40
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
436
40
    _enqueue_data_and_set_ready(
437
40
            channel_id, sink_info.local_state,
438
40
            {BlockWrapper::create_shared(
439
40
                     std::move(new_block),
440
40
                     sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1),
441
40
             {.row_idxs = nullptr, .offset_start = 0, .length = 0}});
442
443
40
    sink_info.local_state->_memory_used_counter->set(
444
40
            sink_info.local_state->_shared_state->mem_usage);
445
40
    return Status::OK();
446
40
}
447
448
Status AdaptivePassthroughExchanger::_shuffle_sink(RuntimeState* state, Block* block,
449
8
                                                   SinkInfo& sink_info) {
450
8
    std::vector<uint32_t> channel_ids;
451
8
    const auto num_rows = block->rows();
452
8
    channel_ids.resize(num_rows, 0);
453
8
    if (num_rows <= _num_partitions) {
454
0
        std::iota(channel_ids.begin(), channel_ids.end(), 0);
455
8
    } else {
456
8
        size_t i = 0;
457
24
        for (; i < num_rows - _num_partitions; i += _num_partitions) {
458
16
            std::iota(channel_ids.begin() + i, channel_ids.begin() + i + _num_partitions, 0);
459
16
        }
460
8
        if (i < num_rows - 1) {
461
8
            std::iota(channel_ids.begin() + i, channel_ids.end(), 0);
462
8
        }
463
8
    }
464
465
8
    sink_info.local_state->_memory_used_counter->set(
466
8
            sink_info.local_state->_shared_state->mem_usage);
467
8
    RETURN_IF_ERROR(_split_rows(state, channel_ids, block, sink_info));
468
8
    return Status::OK();
469
8
}
470
471
Status AdaptivePassthroughExchanger::_split_rows(RuntimeState* state,
472
                                                 const std::vector<uint32_t>& channel_ids,
473
8
                                                 Block* block, SinkInfo& sink_info) {
474
8
    const auto rows = cast_set<int32_t>(block->rows());
475
8
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
476
8
    auto& partition_rows_histogram = _partition_rows_histogram[sink_info.ins_idx];
477
8
    {
478
8
        partition_rows_histogram.assign(_num_partitions + 1, 0);
479
104
        for (int32_t i = 0; i < rows; ++i) {
480
96
            partition_rows_histogram[channel_ids[i]]++;
481
96
        }
482
40
        for (int32_t i = 1; i <= _num_partitions; ++i) {
483
32
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
484
32
        }
485
486
104
        for (int32_t i = rows - 1; i >= 0; --i) {
487
96
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
488
96
            partition_rows_histogram[channel_ids[i]]--;
489
96
        }
490
8
    }
491
8
    Block data_block;
492
8
    if (!_free_blocks.try_dequeue(data_block)) {
493
8
        data_block = block->clone_empty();
494
8
    }
495
8
    data_block.swap(*block);
496
8
    std::shared_ptr<BlockWrapper> new_block_wrapper = BlockWrapper::create_shared(
497
8
            std::move(data_block), sink_info.local_state->_shared_state, sink_info.ins_idx);
498
8
    if (new_block_wrapper->_data_block.empty()) {
499
0
        return Status::OK();
500
0
    }
501
40
    for (int32_t i = 0; i < _num_partitions; i++) {
502
32
        const uint32_t start = partition_rows_histogram[i];
503
32
        const uint32_t size = partition_rows_histogram[i + 1] - start;
504
32
        if (size > 0) {
505
32
            _enqueue_data_and_set_ready(
506
32
                    i, sink_info.local_state,
507
32
                    {new_block_wrapper,
508
32
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
509
32
        }
510
32
    }
511
8
    return Status::OK();
512
8
}
513
514
Status AdaptivePassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos,
515
48
                                          Profile&& profile, SinkInfo& sink_info) {
516
48
    if (in_block->empty()) {
517
0
        return Status::OK();
518
0
    }
519
48
    if (_is_pass_through) {
520
40
        return _passthrough_sink(state, in_block, sink_info);
521
40
    } else {
522
8
        if (++_total_block >= _num_partitions) {
523
2
            _is_pass_through = true;
524
2
        }
525
8
        return _shuffle_sink(state, in_block, sink_info);
526
8
    }
527
48
}
528
529
Status AdaptivePassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
530
88
                                               Profile&& profile, SourceInfo&& source_info) {
531
88
    if (!_tmp_block[source_info.channel_id].empty()) {
532
8
        *block = std::move(_tmp_block[source_info.channel_id]);
533
8
        *eos = _tmp_eos[source_info.channel_id];
534
8
        _tmp_block[source_info.channel_id] = {};
535
8
        return Status::OK();
536
8
    }
537
80
    PartitionedBlock partitioned_block;
538
80
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
539
80
                      source_info.channel_id)) {
540
32
        SCOPED_TIMER(profile.copy_data_timer);
541
32
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
542
32
                block, partitioned_block.first->_data_block);
543
32
        auto& mutable_block = scoped_mutable_block.mutable_block();
544
64
        do {
545
64
            if (partitioned_block.second.row_idxs == nullptr) {
546
                // The passthrough path which means the block is not partitioned, we can directly move the block without copying.
547
32
                if (mutable_block.rows() > 0) {
548
8
                    _tmp_block[source_info.channel_id] =
549
8
                            std::move(partitioned_block.first->_data_block);
550
8
                    _tmp_eos[source_info.channel_id] = *eos;
551
8
                    *eos = false;
552
24
                } else {
553
24
                    scoped_mutable_block.restore();
554
24
                    *block = std::move(partitioned_block.first->_data_block);
555
24
                }
556
32
                break;
557
32
            }
558
32
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
559
32
                                       partitioned_block.second.offset_start;
560
32
            auto block_wrapper = partitioned_block.first;
561
32
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
562
32
                                                   offset_start + partitioned_block.second.length));
563
32
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
564
32
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
565
32
                               source_info.channel_id));
566
32
    }
567
80
    return Status::OK();
568
80
}
569
570
8
void AdaptivePassthroughExchanger::close(SourceInfo&& source_info) {
571
8
    PartitionedBlock partitioned_block;
572
8
    bool eos;
573
8
    Block block;
574
8
    _data_queue[source_info.channel_id].set_eos();
575
8
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
576
8
                         source_info.channel_id)) {
577
        // do nothing
578
0
    }
579
8
}
580
581
} // namespace doris