Coverage Report

Created: 2026-03-15 20:53

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