Coverage Report

Created: 2026-04-06 12:04

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