Coverage Report

Created: 2026-07-06 16:01

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
213k
                                                       BlockType&& block) {
31
213k
    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
213k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
73.3k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
73.3k
        block.first->record_channel_id(channel_id);
43
140k
    } else {
44
140k
        block->record_channel_id(channel_id);
45
140k
    }
46
47
213k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
213k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
213k
    }
50
213k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
48.9k
                                                       BlockType&& block) {
31
48.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
48.9k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
48.9k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
48.9k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
48.9k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
48.9k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
48.9k
    }
50
48.9k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS4_
Line
Count
Source
30
140k
                                                       BlockType&& block) {
31
140k
    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
140k
    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
140k
    } else {
44
140k
        block->record_channel_id(channel_id);
45
140k
    }
46
47
140k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
140k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
140k
    }
50
140k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
24.4k
                                                       BlockType&& block) {
31
24.4k
    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
24.4k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
24.4k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
24.4k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
24.4k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
24.4k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
24.4k
    }
50
24.4k
}
51
52
template <typename BlockType>
53
bool Exchanger<BlockType>::_dequeue_data(LocalExchangeSourceLocalState* local_state,
54
                                         BlockType& block, bool* eos, Block* data_block,
55
1.46M
                                         int channel_id) {
56
1.46M
    if (local_state == nullptr) {
57
20
        return _dequeue_data(block, eos, data_block, channel_id);
58
20
    }
59
1.46M
    bool all_finished = _running_sink_operators == 0;
60
1.46M
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
73.2k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
73.2k
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
140k
        } else {
65
140k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
140k
            data_block->swap(block->_data_block);
67
140k
        }
68
213k
        return true;
69
1.25M
    } else if (all_finished) {
70
1.14M
        *eos = true;
71
1.14M
    } else {
72
111k
        std::unique_lock l(*_m[channel_id]);
73
111k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
18
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
18
                local_state->_shared_state->sub_mem_usage(channel_id,
77
18
                                                          block.first->_allocated_bytes);
78
18
            } else {
79
6
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
6
                data_block->swap(block->_data_block);
81
6
            }
82
24
            return true;
83
24
        }
84
111k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
111k
        local_state->_dependency->block();
86
111k
    }
87
1.25M
    return false;
88
1.46M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
346k
                                         int channel_id) {
56
346k
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
346k
    bool all_finished = _running_sink_operators == 0;
60
346k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
48.8k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
48.8k
            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
48.8k
        return true;
69
297k
    } else if (all_finished) {
70
274k
        *eos = true;
71
274k
    } else {
72
23.9k
        std::unique_lock l(*_m[channel_id]);
73
23.9k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
17
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
17
                local_state->_shared_state->sub_mem_usage(channel_id,
77
17
                                                          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
17
            return true;
83
17
        }
84
23.9k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
23.9k
        local_state->_dependency->block();
86
23.9k
    }
87
297k
    return false;
88
346k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS4_PbPNS_5BlockEi
Line
Count
Source
55
1.06M
                                         int channel_id) {
56
1.06M
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
1.06M
    bool all_finished = _running_sink_operators == 0;
60
1.06M
    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
140k
        } else {
65
140k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
140k
            data_block->swap(block->_data_block);
67
140k
        }
68
140k
        return true;
69
928k
    } else if (all_finished) {
70
845k
        *eos = true;
71
845k
    } else {
72
82.6k
        std::unique_lock l(*_m[channel_id]);
73
82.6k
        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
6
            } else {
79
6
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
6
                data_block->swap(block->_data_block);
81
6
            }
82
6
            return true;
83
6
        }
84
82.6k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
82.6k
        local_state->_dependency->block();
86
82.6k
    }
87
928k
    return false;
88
1.06M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
53.4k
                                         int channel_id) {
56
53.4k
    if (local_state == nullptr) {
57
4
        return _dequeue_data(block, eos, data_block, channel_id);
58
4
    }
59
53.4k
    bool all_finished = _running_sink_operators == 0;
60
53.4k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
24.3k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
24.3k
            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
24.3k
        return true;
69
29.0k
    } else if (all_finished) {
70
24.2k
        *eos = true;
71
24.2k
    } else {
72
4.79k
        std::unique_lock l(*_m[channel_id]);
73
4.79k
        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
4.79k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
4.79k
        local_state->_dependency->block();
86
4.79k
    }
87
29.0k
    return false;
88
53.4k
}
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
151k
                              SinkInfo& sink_info) {
116
151k
    if (in_block->empty()) {
117
132k
        return Status::OK();
118
132k
    }
119
19.6k
    {
120
19.6k
        SCOPED_TIMER(profile.compute_hash_value_timer);
121
19.6k
        RETURN_IF_ERROR(sink_info.partitioner->do_partitioning(state, in_block));
122
19.6k
    }
123
19.6k
    {
124
19.6k
        SCOPED_TIMER(profile.distribute_timer);
125
19.6k
        RETURN_IF_ERROR(_split_rows(state, sink_info.partitioner->get_channel_ids(), in_block,
126
19.6k
                                    *sink_info.channel_id, sink_info.local_state,
127
19.6k
                                    sink_info.shuffle_idx_to_instance_idx));
128
19.6k
    }
129
130
19.6k
    sink_info.local_state->_memory_used_counter->set(
131
19.6k
            sink_info.local_state->_shared_state->mem_usage);
132
19.6k
    return Status::OK();
133
19.6k
}
134
135
133k
void ShuffleExchanger::close(SourceInfo&& source_info) {
136
133k
    PartitionedBlock partitioned_block;
137
133k
    bool eos;
138
133k
    Block block;
139
133k
    _data_queue[source_info.channel_id].set_eos();
140
133k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
141
133k
                         source_info.channel_id)) {
142
        // do nothing
143
148
    }
144
133k
}
145
146
Status ShuffleExchanger::get_block(RuntimeState* state, Block* block, bool* eos, Profile&& profile,
147
154k
                                   SourceInfo&& source_info) {
148
154k
    PartitionedBlock partitioned_block;
149
154k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
150
154k
                      source_info.channel_id)) {
151
30.9k
        SCOPED_TIMER(profile.copy_data_timer);
152
30.9k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
153
30.9k
                block, partitioned_block.first->_data_block);
154
30.9k
        auto& mutable_block = scoped_mutable_block.mutable_block();
155
42.8k
        do {
156
42.8k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
157
42.8k
                                       partitioned_block.second.offset_start;
158
42.8k
            auto block_wrapper = partitioned_block.first;
159
42.8k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
160
42.8k
                                                   offset_start + partitioned_block.second.length));
161
42.8k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
162
42.8k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
163
41.8k
                               source_info.channel_id));
164
30.9k
    }
165
154k
    return Status::OK();
166
154k
}
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
19.5k
                                     std::map<int, int>* shuffle_idx_to_instance_idx) {
172
19.5k
    if (local_state == nullptr) {
173
0
        return _split_rows(state, channel_ids, block, channel_id);
174
0
    }
175
19.5k
    const auto rows = cast_set<int32_t>(block->rows());
176
19.5k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
177
19.5k
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
178
19.5k
    {
179
19.5k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
180
15.3M
        for (int32_t i = 0; i < rows; ++i) {
181
15.3M
            partition_rows_histogram[channel_ids[i]]++;
182
15.3M
        }
183
134k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
184
115k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
185
115k
        }
186
14.9M
        for (int32_t i = rows - 1; i >= 0; --i) {
187
14.9M
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
188
14.9M
            partition_rows_histogram[channel_ids[i]]--;
189
14.9M
        }
190
19.5k
    }
191
192
19.5k
    Block data_block;
193
19.5k
    std::shared_ptr<BlockWrapper> new_block_wrapper;
194
19.5k
    if (!_free_blocks.try_dequeue(data_block)) {
195
12.8k
        data_block = block->clone_empty();
196
12.8k
    }
197
19.5k
    data_block.swap(*block);
198
19.5k
    new_block_wrapper =
199
19.5k
            BlockWrapper::create_shared(std::move(data_block), local_state->_shared_state, -1);
200
19.5k
    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
19.5k
    DCHECK(shuffle_idx_to_instance_idx && !shuffle_idx_to_instance_idx->empty());
210
19.5k
    const auto& map = *shuffle_idx_to_instance_idx;
211
19.5k
    int32_t enqueue_rows = 0;
212
114k
    for (const auto& it : map) {
213
18.4E
        DCHECK(it.second >= 0 && it.second < _num_partitions)
214
18.4E
                << it.first << " : " << it.second << " " << _num_partitions;
215
114k
        uint32_t start = partition_rows_histogram[it.first];
216
114k
        uint32_t size = partition_rows_histogram[it.first + 1] - start;
217
114k
        if (size > 0) {
218
42.9k
            enqueue_rows += size;
219
42.9k
            _enqueue_data_and_set_ready(
220
42.9k
                    it.second, local_state,
221
42.9k
                    {new_block_wrapper,
222
42.9k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
223
42.9k
        }
224
114k
    }
225
19.5k
    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
19.5k
    return Status::OK();
239
19.5k
}
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
208k
                                  SinkInfo& sink_info) {
285
208k
    if (in_block->empty()) {
286
69.9k
        return Status::OK();
287
69.9k
    }
288
138k
    Block new_block;
289
138k
    if (!_free_blocks.try_dequeue(new_block)) {
290
62.7k
        new_block = {in_block->clone_empty()};
291
62.7k
    }
292
138k
    new_block.swap(*in_block);
293
138k
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
294
138k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
295
138k
            std::move(new_block),
296
138k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, channel_id);
297
298
138k
    _enqueue_data_and_set_ready(channel_id, sink_info.local_state, std::move(wrapper));
299
300
138k
    sink_info.local_state->_memory_used_counter->set(
301
138k
            sink_info.local_state->_shared_state->mem_usage);
302
303
138k
    return Status::OK();
304
208k
}
305
306
419k
void PassthroughExchanger::close(SourceInfo&& source_info) {
307
419k
    Block next_block;
308
419k
    BlockWrapperSPtr wrapper;
309
419k
    bool eos;
310
419k
    _data_queue[source_info.channel_id].set_eos();
311
420k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
312
420k
                         source_info.channel_id)) {
313
        // do nothing
314
1.37k
    }
315
419k
}
316
317
5.20k
void PassToOneExchanger::close(SourceInfo&& source_info) {
318
5.20k
    Block next_block;
319
5.20k
    BlockWrapperSPtr wrapper;
320
5.20k
    bool eos;
321
5.20k
    _data_queue[source_info.channel_id].set_eos();
322
5.20k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
323
5.20k
                         source_info.channel_id)) {
324
        // do nothing
325
0
    }
326
5.20k
}
327
328
Status PassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
329
637k
                                       Profile&& profile, SourceInfo&& source_info) {
330
637k
    BlockWrapperSPtr next_block;
331
637k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
332
637k
    return Status::OK();
333
637k
}
334
335
Status PassToOneExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
336
2.16k
                                SinkInfo& sink_info) {
337
2.16k
    if (in_block->empty()) {
338
712
        return Status::OK();
339
712
    }
340
1.45k
    Block new_block;
341
1.45k
    if (!_free_blocks.try_dequeue(new_block)) {
342
845
        new_block = {in_block->clone_empty()};
343
845
    }
344
1.45k
    new_block.swap(*in_block);
345
346
1.45k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
347
1.45k
            std::move(new_block),
348
1.45k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, 0);
349
1.45k
    _enqueue_data_and_set_ready(0, sink_info.local_state, std::move(wrapper));
350
351
1.45k
    sink_info.local_state->_memory_used_counter->set(
352
1.45k
            sink_info.local_state->_shared_state->mem_usage);
353
354
1.45k
    return Status::OK();
355
2.16k
}
356
357
Status PassToOneExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
358
2.59k
                                     Profile&& profile, SourceInfo&& source_info) {
359
2.59k
    if (source_info.channel_id != 0) {
360
3
        *eos = true;
361
3
        return Status::OK();
362
3
    }
363
2.59k
    BlockWrapperSPtr next_block;
364
2.59k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
365
2.59k
    return Status::OK();
366
2.59k
}
367
368
109k
void ExchangerBase::finalize() {
369
109k
    DCHECK(_running_source_operators == 0);
370
109k
    Block block;
371
187k
    while (_free_blocks.try_dequeue(block)) {
372
        // do nothing
373
78.7k
    }
374
109k
}
375
376
Status BroadcastExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
377
4.80k
                                SinkInfo& sink_info) {
378
4.80k
    if (in_block->empty()) {
379
1.71k
        return Status::OK();
380
1.71k
    }
381
3.08k
    Block new_block;
382
3.08k
    if (!_free_blocks.try_dequeue(new_block)) {
383
2.23k
        new_block = {in_block->clone_empty()};
384
2.23k
    }
385
3.08k
    new_block.swap(*in_block);
386
3.08k
    auto wrapper = BlockWrapper::create_shared(
387
3.08k
            std::move(new_block),
388
3.08k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1);
389
27.5k
    for (int i = 0; i < _num_partitions; i++) {
390
24.4k
        _enqueue_data_and_set_ready(
391
24.4k
                i, sink_info.local_state,
392
24.4k
                {wrapper, {.offset_start = 0, .length = wrapper->_data_block.rows()}});
393
24.4k
    }
394
395
3.08k
    return Status::OK();
396
4.80k
}
397
398
12.1k
void BroadcastExchanger::close(SourceInfo&& source_info) {
399
12.1k
    BroadcastBlock partitioned_block;
400
12.1k
    bool eos;
401
12.1k
    Block block;
402
12.1k
    _data_queue[source_info.channel_id].set_eos();
403
12.1k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
404
12.1k
                         source_info.channel_id)) {
405
        // do nothing
406
1
    }
407
12.1k
}
408
409
Status BroadcastExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
410
41.2k
                                     Profile&& profile, SourceInfo&& source_info) {
411
41.2k
    BroadcastBlock partitioned_block;
412
413
41.2k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
414
41.2k
                      source_info.channel_id)) {
415
24.3k
        SCOPED_TIMER(profile.copy_data_timer);
416
24.3k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
417
24.3k
                block, partitioned_block.first->_data_block);
418
24.3k
        auto& mutable_block = scoped_mutable_block.mutable_block();
419
24.3k
        auto block_wrapper = partitioned_block.first;
420
24.3k
        RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block,
421
24.3k
                                               partitioned_block.second.offset_start,
422
24.3k
                                               partitioned_block.second.length));
423
24.3k
    }
424
425
41.2k
    return Status::OK();
426
41.2k
}
427
428
Status AdaptivePassthroughExchanger::_passthrough_sink(RuntimeState* state, Block* in_block,
429
727
                                                       SinkInfo& sink_info) {
430
727
    Block new_block;
431
727
    if (!_free_blocks.try_dequeue(new_block)) {
432
326
        new_block = {in_block->clone_empty()};
433
326
    }
434
727
    new_block.swap(*in_block);
435
727
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
436
727
    _enqueue_data_and_set_ready(
437
727
            channel_id, sink_info.local_state,
438
727
            {BlockWrapper::create_shared(
439
727
                     std::move(new_block),
440
727
                     sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1),
441
727
             {.row_idxs = nullptr, .offset_start = 0, .length = 0}});
442
443
727
    sink_info.local_state->_memory_used_counter->set(
444
727
            sink_info.local_state->_shared_state->mem_usage);
445
727
    return Status::OK();
446
727
}
447
448
Status AdaptivePassthroughExchanger::_shuffle_sink(RuntimeState* state, Block* block,
449
1.99k
                                                   SinkInfo& sink_info) {
450
1.99k
    std::vector<uint32_t> channel_ids;
451
1.99k
    const auto num_rows = block->rows();
452
1.99k
    channel_ids.resize(num_rows, 0);
453
1.99k
    if (num_rows <= _num_partitions) {
454
1.38k
        std::iota(channel_ids.begin(), channel_ids.end(), 0);
455
1.38k
    } else {
456
613
        size_t i = 0;
457
32.8k
        for (; i < num_rows - _num_partitions; i += _num_partitions) {
458
32.2k
            std::iota(channel_ids.begin() + i, channel_ids.begin() + i + _num_partitions, 0);
459
32.2k
        }
460
613
        if (i < num_rows - 1) {
461
330
            std::iota(channel_ids.begin() + i, channel_ids.end(), 0);
462
330
        }
463
613
    }
464
465
1.99k
    sink_info.local_state->_memory_used_counter->set(
466
1.99k
            sink_info.local_state->_shared_state->mem_usage);
467
1.99k
    RETURN_IF_ERROR(_split_rows(state, channel_ids, block, sink_info));
468
1.99k
    return Status::OK();
469
1.99k
}
470
471
Status AdaptivePassthroughExchanger::_split_rows(RuntimeState* state,
472
                                                 const std::vector<uint32_t>& channel_ids,
473
1.99k
                                                 Block* block, SinkInfo& sink_info) {
474
1.99k
    const auto rows = cast_set<int32_t>(block->rows());
475
1.99k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
476
1.99k
    auto& partition_rows_histogram = _partition_rows_histogram[sink_info.ins_idx];
477
1.99k
    {
478
1.99k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
479
102k
        for (int32_t i = 0; i < rows; ++i) {
480
100k
            partition_rows_histogram[channel_ids[i]]++;
481
100k
        }
482
11.5k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
483
9.51k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
484
9.51k
        }
485
486
102k
        for (int32_t i = rows - 1; i >= 0; --i) {
487
100k
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
488
100k
            partition_rows_histogram[channel_ids[i]]--;
489
100k
        }
490
1.99k
    }
491
1.99k
    Block data_block;
492
1.99k
    if (!_free_blocks.try_dequeue(data_block)) {
493
1.73k
        data_block = block->clone_empty();
494
1.73k
    }
495
1.99k
    data_block.swap(*block);
496
1.99k
    std::shared_ptr<BlockWrapper> new_block_wrapper = BlockWrapper::create_shared(
497
1.99k
            std::move(data_block), sink_info.local_state->_shared_state, sink_info.ins_idx);
498
1.99k
    if (new_block_wrapper->_data_block.empty()) {
499
0
        return Status::OK();
500
0
    }
501
11.5k
    for (int32_t i = 0; i < _num_partitions; i++) {
502
9.51k
        const uint32_t start = partition_rows_histogram[i];
503
9.51k
        const uint32_t size = partition_rows_histogram[i + 1] - start;
504
9.51k
        if (size > 0) {
505
5.22k
            _enqueue_data_and_set_ready(
506
5.22k
                    i, sink_info.local_state,
507
5.22k
                    {new_block_wrapper,
508
5.22k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
509
5.22k
        }
510
9.51k
    }
511
1.99k
    return Status::OK();
512
1.99k
}
513
514
Status AdaptivePassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos,
515
5.93k
                                          Profile&& profile, SinkInfo& sink_info) {
516
5.93k
    if (in_block->empty()) {
517
3.21k
        return Status::OK();
518
3.21k
    }
519
2.72k
    if (_is_pass_through) {
520
727
        return _passthrough_sink(state, in_block, sink_info);
521
1.99k
    } else {
522
1.99k
        if (++_total_block >= _num_partitions) {
523
420
            _is_pass_through = true;
524
420
        }
525
1.99k
        return _shuffle_sink(state, in_block, sink_info);
526
1.99k
    }
527
2.72k
}
528
529
Status AdaptivePassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
530
7.21k
                                               Profile&& profile, SourceInfo&& source_info) {
531
7.21k
    if (!_tmp_block[source_info.channel_id].empty()) {
532
172
        *block = std::move(_tmp_block[source_info.channel_id]);
533
172
        *eos = _tmp_eos[source_info.channel_id];
534
172
        _tmp_block[source_info.channel_id] = {};
535
172
        return Status::OK();
536
172
    }
537
7.04k
    PartitionedBlock partitioned_block;
538
7.04k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
539
7.04k
                      source_info.channel_id)) {
540
3.91k
        SCOPED_TIMER(profile.copy_data_timer);
541
3.91k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
542
3.91k
                block, partitioned_block.first->_data_block);
543
3.91k
        auto& mutable_block = scoped_mutable_block.mutable_block();
544
5.94k
        do {
545
5.94k
            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
723
                if (mutable_block.rows() > 0) {
548
172
                    _tmp_block[source_info.channel_id] =
549
172
                            std::move(partitioned_block.first->_data_block);
550
172
                    _tmp_eos[source_info.channel_id] = *eos;
551
172
                    *eos = false;
552
551
                } else {
553
551
                    scoped_mutable_block.restore();
554
551
                    *block = std::move(partitioned_block.first->_data_block);
555
551
                }
556
723
                break;
557
723
            }
558
5.22k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
559
5.22k
                                       partitioned_block.second.offset_start;
560
5.22k
            auto block_wrapper = partitioned_block.first;
561
5.22k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
562
5.22k
                                                   offset_start + partitioned_block.second.length));
563
5.22k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
564
5.22k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
565
5.22k
                               source_info.channel_id));
566
3.91k
    }
567
7.04k
    return Status::OK();
568
7.04k
}
569
570
4.37k
void AdaptivePassthroughExchanger::close(SourceInfo&& source_info) {
571
4.37k
    PartitionedBlock partitioned_block;
572
4.37k
    bool eos;
573
4.37k
    Block block;
574
4.37k
    _data_queue[source_info.channel_id].set_eos();
575
4.37k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
576
4.37k
                         source_info.channel_id)) {
577
        // do nothing
578
2
    }
579
4.37k
}
580
581
} // namespace doris