Coverage Report

Created: 2026-06-30 15:46

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
305k
                                                       BlockType&& block) {
31
305k
    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
305k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
92.5k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
92.5k
        block.first->record_channel_id(channel_id);
43
212k
    } else {
44
212k
        block->record_channel_id(channel_id);
45
212k
    }
46
47
305k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
304k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
304k
    }
50
305k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
71.9k
                                                       BlockType&& block) {
31
71.9k
    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
71.9k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
71.9k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
71.9k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
71.9k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
70.9k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
70.9k
    }
50
71.9k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS4_
Line
Count
Source
30
212k
                                                       BlockType&& block) {
31
212k
    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
212k
    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
212k
    } else {
44
212k
        block->record_channel_id(channel_id);
45
212k
    }
46
47
212k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
212k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
212k
    }
50
212k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
20.5k
                                                       BlockType&& block) {
31
20.5k
    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
20.5k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
20.5k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
20.5k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
20.5k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
20.5k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
20.5k
    }
50
20.5k
}
51
52
template <typename BlockType>
53
bool Exchanger<BlockType>::_dequeue_data(LocalExchangeSourceLocalState* local_state,
54
                                         BlockType& block, bool* eos, Block* data_block,
55
2.09M
                                         int channel_id) {
56
2.09M
    if (local_state == nullptr) {
57
20
        return _dequeue_data(block, eos, data_block, channel_id);
58
20
    }
59
2.09M
    bool all_finished = _running_sink_operators == 0;
60
2.09M
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
91.4k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
91.4k
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
212k
        } else {
65
212k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
212k
            data_block->swap(block->_data_block);
67
212k
        }
68
304k
        return true;
69
1.79M
    } else if (all_finished) {
70
1.62M
        *eos = true;
71
1.62M
    } else {
72
163k
        std::unique_lock l(*_m[channel_id]);
73
163k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
8
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
8
                local_state->_shared_state->sub_mem_usage(channel_id,
77
8
                                                          block.first->_allocated_bytes);
78
11
            } else {
79
11
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
11
                data_block->swap(block->_data_block);
81
11
            }
82
19
            return true;
83
19
        }
84
163k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
163k
        local_state->_dependency->block();
86
163k
    }
87
1.79M
    return false;
88
2.09M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
379k
                                         int channel_id) {
56
379k
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
379k
    bool all_finished = _running_sink_operators == 0;
60
379k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
70.9k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
70.9k
            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
70.9k
        return true;
69
308k
    } else if (all_finished) {
70
276k
        *eos = true;
71
276k
    } else {
72
32.7k
        std::unique_lock l(*_m[channel_id]);
73
32.7k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
7
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
7
                local_state->_shared_state->sub_mem_usage(channel_id,
77
7
                                                          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
7
            return true;
83
7
        }
84
32.7k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
32.7k
        local_state->_dependency->block();
86
32.7k
    }
87
308k
    return false;
88
379k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS4_PbPNS_5BlockEi
Line
Count
Source
55
1.67M
                                         int channel_id) {
56
1.67M
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
1.67M
    bool all_finished = _running_sink_operators == 0;
60
1.67M
    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
212k
        } else {
65
212k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
212k
            data_block->swap(block->_data_block);
67
212k
        }
68
212k
        return true;
69
1.45M
    } else if (all_finished) {
70
1.33M
        *eos = true;
71
1.33M
    } else {
72
127k
        std::unique_lock l(*_m[channel_id]);
73
127k
        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
11
            } else {
79
11
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
11
                data_block->swap(block->_data_block);
81
11
            }
82
11
            return true;
83
11
        }
84
127k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
127k
        local_state->_dependency->block();
86
127k
    }
87
1.45M
    return false;
88
1.67M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
45.6k
                                         int channel_id) {
56
45.6k
    if (local_state == nullptr) {
57
4
        return _dequeue_data(block, eos, data_block, channel_id);
58
4
    }
59
45.6k
    bool all_finished = _running_sink_operators == 0;
60
45.6k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
20.5k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
20.5k
            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
20.5k
        return true;
69
25.1k
    } else if (all_finished) {
70
21.6k
        *eos = true;
71
21.6k
    } else {
72
3.51k
        std::unique_lock l(*_m[channel_id]);
73
3.51k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
1
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
1
                local_state->_shared_state->sub_mem_usage(channel_id,
77
1
                                                          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
1
            return true;
83
1
        }
84
3.51k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
3.51k
        local_state->_dependency->block();
86
3.51k
    }
87
25.1k
    return false;
88
45.6k
}
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
20
                                         int channel_id) {
104
20
    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
20
    return false;
112
20
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_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
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataERS4_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
0
                      !std::is_same_v<BroadcastBlock, BlockType>) {
107
0
            data_block->swap(block->_data_block);
108
0
        }
109
0
        return true;
110
0
    }
111
8
    return false;
112
8
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataERS7_PbPNS_5BlockEi
Line
Count
Source
103
4
                                         int channel_id) {
104
4
    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
4
    return false;
112
4
}
113
114
Status ShuffleExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
115
159k
                              SinkInfo& sink_info) {
116
159k
    if (in_block->empty()) {
117
133k
        return Status::OK();
118
133k
    }
119
26.4k
    {
120
26.4k
        SCOPED_TIMER(profile.compute_hash_value_timer);
121
26.4k
        RETURN_IF_ERROR(sink_info.partitioner->do_partitioning(state, in_block));
122
26.4k
    }
123
26.4k
    {
124
26.4k
        SCOPED_TIMER(profile.distribute_timer);
125
26.4k
        RETURN_IF_ERROR(_split_rows(state, sink_info.partitioner->get_channel_ids(), in_block,
126
26.4k
                                    *sink_info.channel_id, sink_info.local_state,
127
26.4k
                                    sink_info.shuffle_idx_to_instance_idx));
128
26.4k
    }
129
130
26.4k
    sink_info.local_state->_memory_used_counter->set(
131
26.4k
            sink_info.local_state->_shared_state->mem_usage);
132
26.4k
    return Status::OK();
133
26.4k
}
134
135
134k
void ShuffleExchanger::close(SourceInfo&& source_info) {
136
134k
    PartitionedBlock partitioned_block;
137
134k
    bool eos;
138
134k
    Block block;
139
134k
    _data_queue[source_info.channel_id].set_eos();
140
134k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
141
134k
                         source_info.channel_id)) {
142
        // do nothing
143
4
    }
144
134k
}
145
146
Status ShuffleExchanger::get_block(RuntimeState* state, Block* block, bool* eos, Profile&& profile,
147
166k
                                   SourceInfo&& source_info) {
148
166k
    PartitionedBlock partitioned_block;
149
166k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
150
166k
                      source_info.channel_id)) {
151
44.0k
        SCOPED_TIMER(profile.copy_data_timer);
152
44.0k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
153
44.0k
                block, partitioned_block.first->_data_block);
154
44.0k
        auto& mutable_block = scoped_mutable_block.mutable_block();
155
64.3k
        do {
156
64.3k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
157
64.3k
                                       partitioned_block.second.offset_start;
158
64.3k
            auto block_wrapper = partitioned_block.first;
159
64.3k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
160
64.3k
                                                   offset_start + partitioned_block.second.length));
161
64.3k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
162
64.3k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
163
60.5k
                               source_info.channel_id));
164
44.0k
    }
165
166k
    return Status::OK();
166
166k
}
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
26.3k
                                     std::map<int, int>* shuffle_idx_to_instance_idx) {
172
26.3k
    if (local_state == nullptr) {
173
0
        return _split_rows(state, channel_ids, block, channel_id);
174
0
    }
175
26.3k
    const auto rows = cast_set<int32_t>(block->rows());
176
26.3k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
177
26.3k
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
178
26.3k
    {
179
26.3k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
180
51.9M
        for (int32_t i = 0; i < rows; ++i) {
181
51.8M
            partition_rows_histogram[channel_ids[i]]++;
182
51.8M
        }
183
214k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
184
187k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
185
187k
        }
186
51.5M
        for (int32_t i = rows - 1; i >= 0; --i) {
187
51.5M
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
188
51.5M
            partition_rows_histogram[channel_ids[i]]--;
189
51.5M
        }
190
26.3k
    }
191
192
26.3k
    Block data_block;
193
26.3k
    std::shared_ptr<BlockWrapper> new_block_wrapper;
194
26.3k
    if (!_free_blocks.try_dequeue(data_block)) {
195
14.1k
        data_block = block->clone_empty();
196
14.1k
    }
197
26.3k
    data_block.swap(*block);
198
26.3k
    new_block_wrapper =
199
26.3k
            BlockWrapper::create_shared(std::move(data_block), local_state->_shared_state, -1);
200
26.3k
    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
26.3k
    DCHECK(shuffle_idx_to_instance_idx && !shuffle_idx_to_instance_idx->empty());
210
26.3k
    const auto& map = *shuffle_idx_to_instance_idx;
211
26.3k
    int32_t enqueue_rows = 0;
212
187k
    for (const auto& it : map) {
213
187k
        DCHECK(it.second >= 0 && it.second < _num_partitions)
214
5
                << it.first << " : " << it.second << " " << _num_partitions;
215
187k
        uint32_t start = partition_rows_histogram[it.first];
216
187k
        uint32_t size = partition_rows_histogram[it.first + 1] - start;
217
187k
        if (size > 0) {
218
65.3k
            enqueue_rows += size;
219
65.3k
            _enqueue_data_and_set_ready(
220
65.3k
                    it.second, local_state,
221
65.3k
                    {new_block_wrapper,
222
65.3k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
223
65.3k
        }
224
187k
    }
225
26.3k
    if (enqueue_rows != rows) [[unlikely]] {
226
1
        fmt::memory_buffer debug_string_buffer;
227
1
        fmt::format_to(debug_string_buffer, "Type: {}, Local Exchange Id: {}, Shuffled Map: ",
228
1
                       get_exchange_type_name(get_type()), local_state->parent()->node_id());
229
3
        for (const auto& it : map) {
230
3
            fmt::format_to(debug_string_buffer, "[{}:{}], ", it.first, it.second);
231
3
        }
232
1
        return Status::InternalError(
233
1
                "Rows mismatched! Data may be lost. [Expected enqueue rows={}, Real enqueue "
234
1
                "rows={}, Detail: {}]",
235
1
                rows, enqueue_rows, fmt::to_string(debug_string_buffer));
236
1
    }
237
238
26.3k
    return Status::OK();
239
26.3k
}
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
300k
                                  SinkInfo& sink_info) {
285
300k
    if (in_block->empty()) {
286
91.6k
        return Status::OK();
287
91.6k
    }
288
208k
    Block new_block;
289
208k
    if (!_free_blocks.try_dequeue(new_block)) {
290
86.6k
        new_block = {in_block->clone_empty()};
291
86.6k
    }
292
208k
    new_block.swap(*in_block);
293
208k
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
294
208k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
295
208k
            std::move(new_block),
296
208k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, channel_id);
297
298
208k
    _enqueue_data_and_set_ready(channel_id, sink_info.local_state, std::move(wrapper));
299
300
208k
    sink_info.local_state->_memory_used_counter->set(
301
208k
            sink_info.local_state->_shared_state->mem_usage);
302
303
208k
    return Status::OK();
304
300k
}
305
306
656k
void PassthroughExchanger::close(SourceInfo&& source_info) {
307
656k
    Block next_block;
308
656k
    BlockWrapperSPtr wrapper;
309
656k
    bool eos;
310
656k
    _data_queue[source_info.channel_id].set_eos();
311
657k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
312
657k
                         source_info.channel_id)) {
313
        // do nothing
314
1.19k
    }
315
656k
}
316
317
17.3k
void PassToOneExchanger::close(SourceInfo&& source_info) {
318
17.3k
    Block next_block;
319
17.3k
    BlockWrapperSPtr wrapper;
320
17.3k
    bool eos;
321
17.3k
    _data_queue[source_info.channel_id].set_eos();
322
17.3k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
323
17.3k
                         source_info.channel_id)) {
324
        // do nothing
325
0
    }
326
17.3k
}
327
328
Status PassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
329
986k
                                       Profile&& profile, SourceInfo&& source_info) {
330
986k
    BlockWrapperSPtr next_block;
331
986k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
332
986k
    return Status::OK();
333
986k
}
334
335
Status PassToOneExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
336
6.45k
                                SinkInfo& sink_info) {
337
6.45k
    if (in_block->empty()) {
338
2.21k
        return Status::OK();
339
2.21k
    }
340
4.23k
    Block new_block;
341
4.23k
    if (!_free_blocks.try_dequeue(new_block)) {
342
2.42k
        new_block = {in_block->clone_empty()};
343
2.42k
    }
344
4.23k
    new_block.swap(*in_block);
345
346
4.23k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
347
4.23k
            std::move(new_block),
348
4.23k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, 0);
349
4.23k
    _enqueue_data_and_set_ready(0, sink_info.local_state, std::move(wrapper));
350
351
4.23k
    sink_info.local_state->_memory_used_counter->set(
352
4.23k
            sink_info.local_state->_shared_state->mem_usage);
353
354
4.23k
    return Status::OK();
355
6.45k
}
356
357
Status PassToOneExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
358
7.63k
                                     Profile&& profile, SourceInfo&& source_info) {
359
7.63k
    if (source_info.channel_id != 0) {
360
3
        *eos = true;
361
3
        return Status::OK();
362
3
    }
363
7.62k
    BlockWrapperSPtr next_block;
364
7.62k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
365
7.62k
    return Status::OK();
366
7.63k
}
367
368
127k
void ExchangerBase::finalize() {
369
127k
    DCHECK(_running_source_operators == 0);
370
127k
    Block block;
371
232k
    while (_free_blocks.try_dequeue(block)) {
372
        // do nothing
373
104k
    }
374
127k
}
375
376
Status BroadcastExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
377
4.15k
                                SinkInfo& sink_info) {
378
4.15k
    if (in_block->empty()) {
379
1.45k
        return Status::OK();
380
1.45k
    }
381
2.70k
    Block new_block;
382
2.70k
    if (!_free_blocks.try_dequeue(new_block)) {
383
1.98k
        new_block = {in_block->clone_empty()};
384
1.98k
    }
385
2.70k
    new_block.swap(*in_block);
386
2.70k
    auto wrapper = BlockWrapper::create_shared(
387
2.70k
            std::move(new_block),
388
2.70k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1);
389
23.2k
    for (int i = 0; i < _num_partitions; i++) {
390
20.5k
        _enqueue_data_and_set_ready(
391
20.5k
                i, sink_info.local_state,
392
20.5k
                {wrapper, {.offset_start = 0, .length = wrapper->_data_block.rows()}});
393
20.5k
    }
394
395
2.70k
    return Status::OK();
396
4.15k
}
397
398
10.8k
void BroadcastExchanger::close(SourceInfo&& source_info) {
399
10.8k
    BroadcastBlock partitioned_block;
400
10.8k
    bool eos;
401
10.8k
    Block block;
402
10.8k
    _data_queue[source_info.channel_id].set_eos();
403
10.8k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
404
10.8k
                         source_info.channel_id)) {
405
        // do nothing
406
0
    }
407
10.8k
}
408
409
Status BroadcastExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
410
34.8k
                                     Profile&& profile, SourceInfo&& source_info) {
411
34.8k
    BroadcastBlock partitioned_block;
412
413
34.8k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
414
34.8k
                      source_info.channel_id)) {
415
20.5k
        SCOPED_TIMER(profile.copy_data_timer);
416
20.5k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
417
20.5k
                block, partitioned_block.first->_data_block);
418
20.5k
        auto& mutable_block = scoped_mutable_block.mutable_block();
419
20.5k
        auto block_wrapper = partitioned_block.first;
420
20.5k
        RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block,
421
20.5k
                                               partitioned_block.second.offset_start,
422
20.5k
                                               partitioned_block.second.length));
423
20.5k
    }
424
425
34.8k
    return Status::OK();
426
34.8k
}
427
428
Status AdaptivePassthroughExchanger::_passthrough_sink(RuntimeState* state, Block* in_block,
429
750
                                                       SinkInfo& sink_info) {
430
750
    Block new_block;
431
750
    if (!_free_blocks.try_dequeue(new_block)) {
432
494
        new_block = {in_block->clone_empty()};
433
494
    }
434
750
    new_block.swap(*in_block);
435
750
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
436
750
    _enqueue_data_and_set_ready(
437
750
            channel_id, sink_info.local_state,
438
750
            {BlockWrapper::create_shared(
439
750
                     std::move(new_block),
440
750
                     sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1),
441
750
             {.row_idxs = nullptr, .offset_start = 0, .length = 0}});
442
443
750
    sink_info.local_state->_memory_used_counter->set(
444
750
            sink_info.local_state->_shared_state->mem_usage);
445
750
    return Status::OK();
446
750
}
447
448
Status AdaptivePassthroughExchanger::_shuffle_sink(RuntimeState* state, Block* block,
449
2.31k
                                                   SinkInfo& sink_info) {
450
2.31k
    std::vector<uint32_t> channel_ids;
451
2.31k
    const auto num_rows = block->rows();
452
2.31k
    channel_ids.resize(num_rows, 0);
453
2.31k
    if (num_rows <= _num_partitions) {
454
1.85k
        std::iota(channel_ids.begin(), channel_ids.end(), 0);
455
1.85k
    } else {
456
463
        size_t i = 0;
457
27.2k
        for (; i < num_rows - _num_partitions; i += _num_partitions) {
458
26.7k
            std::iota(channel_ids.begin() + i, channel_ids.begin() + i + _num_partitions, 0);
459
26.7k
        }
460
463
        if (i < num_rows - 1) {
461
361
            std::iota(channel_ids.begin() + i, channel_ids.end(), 0);
462
361
        }
463
463
    }
464
465
2.31k
    sink_info.local_state->_memory_used_counter->set(
466
2.31k
            sink_info.local_state->_shared_state->mem_usage);
467
2.31k
    RETURN_IF_ERROR(_split_rows(state, channel_ids, block, sink_info));
468
2.31k
    return Status::OK();
469
2.31k
}
470
471
Status AdaptivePassthroughExchanger::_split_rows(RuntimeState* state,
472
                                                 const std::vector<uint32_t>& channel_ids,
473
2.31k
                                                 Block* block, SinkInfo& sink_info) {
474
2.31k
    const auto rows = cast_set<int32_t>(block->rows());
475
2.31k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
476
2.31k
    auto& partition_rows_histogram = _partition_rows_histogram[sink_info.ins_idx];
477
2.31k
    {
478
2.31k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
479
78.5k
        for (int32_t i = 0; i < rows; ++i) {
480
76.2k
            partition_rows_histogram[channel_ids[i]]++;
481
76.2k
        }
482
15.0k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
483
12.7k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
484
12.7k
        }
485
486
78.1k
        for (int32_t i = rows - 1; i >= 0; --i) {
487
75.8k
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
488
75.8k
            partition_rows_histogram[channel_ids[i]]--;
489
75.8k
        }
490
2.31k
    }
491
2.31k
    Block data_block;
492
2.31k
    if (!_free_blocks.try_dequeue(data_block)) {
493
2.07k
        data_block = block->clone_empty();
494
2.07k
    }
495
2.31k
    data_block.swap(*block);
496
2.31k
    std::shared_ptr<BlockWrapper> new_block_wrapper = BlockWrapper::create_shared(
497
2.31k
            std::move(data_block), sink_info.local_state->_shared_state, sink_info.ins_idx);
498
2.31k
    if (new_block_wrapper->_data_block.empty()) {
499
0
        return Status::OK();
500
0
    }
501
15.0k
    for (int32_t i = 0; i < _num_partitions; i++) {
502
12.7k
        const uint32_t start = partition_rows_histogram[i];
503
12.7k
        const uint32_t size = partition_rows_histogram[i + 1] - start;
504
12.7k
        if (size > 0) {
505
5.82k
            _enqueue_data_and_set_ready(
506
5.82k
                    i, sink_info.local_state,
507
5.82k
                    {new_block_wrapper,
508
5.82k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
509
5.82k
        }
510
12.7k
    }
511
2.31k
    return Status::OK();
512
2.31k
}
513
514
Status AdaptivePassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos,
515
7.26k
                                          Profile&& profile, SinkInfo& sink_info) {
516
7.26k
    if (in_block->empty()) {
517
4.19k
        return Status::OK();
518
4.19k
    }
519
3.07k
    if (_is_pass_through) {
520
750
        return _passthrough_sink(state, in_block, sink_info);
521
2.32k
    } else {
522
2.32k
        if (++_total_block >= _num_partitions) {
523
387
            _is_pass_through = true;
524
387
        }
525
2.32k
        return _shuffle_sink(state, in_block, sink_info);
526
2.32k
    }
527
3.07k
}
528
529
Status AdaptivePassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
530
7.13k
                                               Profile&& profile, SourceInfo&& source_info) {
531
7.13k
    if (!_tmp_block[source_info.channel_id].empty()) {
532
290
        *block = std::move(_tmp_block[source_info.channel_id]);
533
290
        *eos = _tmp_eos[source_info.channel_id];
534
290
        _tmp_block[source_info.channel_id] = {};
535
290
        return Status::OK();
536
290
    }
537
6.84k
    PartitionedBlock partitioned_block;
538
6.84k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
539
6.84k
                      source_info.channel_id)) {
540
3.60k
        SCOPED_TIMER(profile.copy_data_timer);
541
3.60k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
542
3.60k
                block, partitioned_block.first->_data_block);
543
3.60k
        auto& mutable_block = scoped_mutable_block.mutable_block();
544
6.56k
        do {
545
6.56k
            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
746
                if (mutable_block.rows() > 0) {
548
290
                    _tmp_block[source_info.channel_id] =
549
290
                            std::move(partitioned_block.first->_data_block);
550
290
                    _tmp_eos[source_info.channel_id] = *eos;
551
290
                    *eos = false;
552
456
                } else {
553
456
                    scoped_mutable_block.restore();
554
456
                    *block = std::move(partitioned_block.first->_data_block);
555
456
                }
556
746
                break;
557
746
            }
558
5.81k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
559
5.81k
                                       partitioned_block.second.offset_start;
560
5.81k
            auto block_wrapper = partitioned_block.first;
561
5.81k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
562
5.81k
                                                   offset_start + partitioned_block.second.length));
563
5.81k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
564
5.81k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
565
5.81k
                               source_info.channel_id));
566
3.60k
    }
567
6.84k
    return Status::OK();
568
6.84k
}
569
570
5.00k
void AdaptivePassthroughExchanger::close(SourceInfo&& source_info) {
571
5.00k
    PartitionedBlock partitioned_block;
572
5.00k
    bool eos;
573
5.00k
    Block block;
574
5.00k
    _data_queue[source_info.channel_id].set_eos();
575
5.01k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
576
5.01k
                         source_info.channel_id)) {
577
        // do nothing
578
5
    }
579
5.00k
}
580
581
} // namespace doris