Coverage Report

Created: 2026-06-02 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
291k
                                                       BlockType&& block) {
31
291k
    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
291k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
83.2k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
83.2k
        block.first->record_channel_id(channel_id);
43
208k
    } else {
44
208k
        block->record_channel_id(channel_id);
45
208k
    }
46
47
291k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
291k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
291k
    }
50
291k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
58.8k
                                                       BlockType&& block) {
31
58.8k
    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
58.8k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
58.8k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
58.8k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
58.8k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
58.6k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
58.6k
    }
50
58.8k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS4_
Line
Count
Source
30
208k
                                                       BlockType&& block) {
31
208k
    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
208k
    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
208k
    } else {
44
208k
        block->record_channel_id(channel_id);
45
208k
    }
46
47
208k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
208k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
208k
    }
50
208k
}
_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.3k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
24.3k
    }
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.99M
                                         int channel_id) {
56
1.99M
    if (local_state == nullptr) {
57
20
        return _dequeue_data(block, eos, data_block, channel_id);
58
20
    }
59
1.99M
    bool all_finished = _running_sink_operators == 0;
60
1.99M
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
82.9k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
82.9k
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
208k
        } else {
65
208k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
208k
            data_block->swap(block->_data_block);
67
208k
        }
68
291k
        return true;
69
1.70M
    } else if (all_finished) {
70
1.52M
        *eos = true;
71
1.52M
    } else {
72
178k
        std::unique_lock l(*_m[channel_id]);
73
178k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
15
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
15
                local_state->_shared_state->sub_mem_usage(channel_id,
77
15
                                                          block.first->_allocated_bytes);
78
15
            } else {
79
12
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
12
                data_block->swap(block->_data_block);
81
12
            }
82
27
            return true;
83
27
        }
84
178k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
178k
        local_state->_dependency->block();
86
178k
    }
87
1.70M
    return false;
88
1.99M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
418k
                                         int channel_id) {
56
418k
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
418k
    bool all_finished = _running_sink_operators == 0;
60
418k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
58.5k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
58.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
58.5k
        return true;
69
359k
    } else if (all_finished) {
70
324k
        *eos = true;
71
324k
    } else {
72
35.1k
        std::unique_lock l(*_m[channel_id]);
73
35.1k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
9
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
9
                local_state->_shared_state->sub_mem_usage(channel_id,
77
9
                                                          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
9
            return true;
83
9
        }
84
35.1k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
35.1k
        local_state->_dependency->block();
86
35.1k
    }
87
359k
    return false;
88
418k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS4_PbPNS_5BlockEi
Line
Count
Source
55
1.52M
                                         int channel_id) {
56
1.52M
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
1.52M
    bool all_finished = _running_sink_operators == 0;
60
1.52M
    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
208k
        } else {
65
208k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
208k
            data_block->swap(block->_data_block);
67
208k
        }
68
208k
        return true;
69
1.31M
    } else if (all_finished) {
70
1.18M
        *eos = true;
71
1.18M
    } else {
72
136k
        std::unique_lock l(*_m[channel_id]);
73
136k
        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
12
            } else {
79
12
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
12
                data_block->swap(block->_data_block);
81
12
            }
82
12
            return true;
83
12
        }
84
136k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
136k
        local_state->_dependency->block();
86
136k
    }
87
1.31M
    return false;
88
1.52M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
53.3k
                                         int channel_id) {
56
53.3k
    if (local_state == nullptr) {
57
4
        return _dequeue_data(block, eos, data_block, channel_id);
58
4
    }
59
53.3k
    bool all_finished = _running_sink_operators == 0;
60
53.3k
    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
22.1k
        *eos = true;
71
22.1k
    } else {
72
6.88k
        std::unique_lock l(*_m[channel_id]);
73
6.88k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
6
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
6
                local_state->_shared_state->sub_mem_usage(channel_id,
77
6
                                                          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
6
            return true;
83
6
        }
84
6.87k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
6.87k
        local_state->_dependency->block();
86
6.87k
    }
87
29.0k
    return false;
88
53.3k
}
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
183k
                              SinkInfo& sink_info) {
116
183k
    if (in_block->empty()) {
117
156k
        return Status::OK();
118
156k
    }
119
27.0k
    {
120
27.0k
        SCOPED_TIMER(profile.compute_hash_value_timer);
121
27.0k
        RETURN_IF_ERROR(sink_info.partitioner->do_partitioning(state, in_block));
122
27.0k
    }
123
27.0k
    {
124
27.0k
        SCOPED_TIMER(profile.distribute_timer);
125
27.0k
        RETURN_IF_ERROR(_split_rows(state, sink_info.partitioner->get_channel_ids(), in_block,
126
27.0k
                                    *sink_info.channel_id, sink_info.local_state,
127
27.0k
                                    sink_info.shuffle_idx_to_instance_idx));
128
27.0k
    }
129
130
27.0k
    sink_info.local_state->_memory_used_counter->set(
131
27.0k
            sink_info.local_state->_shared_state->mem_usage);
132
27.0k
    return Status::OK();
133
27.0k
}
134
135
158k
void ShuffleExchanger::close(SourceInfo&& source_info) {
136
158k
    PartitionedBlock partitioned_block;
137
158k
    bool eos;
138
158k
    Block block;
139
158k
    _data_queue[source_info.channel_id].set_eos();
140
158k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
141
158k
                         source_info.channel_id)) {
142
        // do nothing
143
13
    }
144
158k
}
145
146
Status ShuffleExchanger::get_block(RuntimeState* state, Block* block, bool* eos, Profile&& profile,
147
191k
                                   SourceInfo&& source_info) {
148
191k
    PartitionedBlock partitioned_block;
149
191k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
150
191k
                      source_info.channel_id)) {
151
43.5k
        SCOPED_TIMER(profile.copy_data_timer);
152
43.5k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
153
43.5k
                block, partitioned_block.first->_data_block);
154
43.5k
        auto& mutable_block = scoped_mutable_block.mutable_block();
155
51.9k
        do {
156
51.9k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
157
51.9k
                                       partitioned_block.second.offset_start;
158
51.9k
            auto block_wrapper = partitioned_block.first;
159
51.9k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
160
51.9k
                                                   offset_start + partitioned_block.second.length));
161
51.9k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
162
51.9k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
163
50.3k
                               source_info.channel_id));
164
43.5k
    }
165
191k
    return Status::OK();
166
191k
}
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.8k
                                     std::map<int, int>* shuffle_idx_to_instance_idx) {
172
26.8k
    if (local_state == nullptr) {
173
0
        return _split_rows(state, channel_ids, block, channel_id);
174
0
    }
175
26.8k
    const auto rows = cast_set<int32_t>(block->rows());
176
26.8k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
177
26.8k
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
178
26.8k
    {
179
26.8k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
180
32.2M
        for (int32_t i = 0; i < rows; ++i) {
181
32.2M
            partition_rows_histogram[channel_ids[i]]++;
182
32.2M
        }
183
210k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
184
183k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
185
183k
        }
186
31.8M
        for (int32_t i = rows - 1; i >= 0; --i) {
187
31.7M
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
188
31.7M
            partition_rows_histogram[channel_ids[i]]--;
189
31.7M
        }
190
26.8k
    }
191
192
26.8k
    Block data_block;
193
26.8k
    std::shared_ptr<BlockWrapper> new_block_wrapper;
194
26.8k
    if (!_free_blocks.try_dequeue(data_block)) {
195
14.0k
        data_block = block->clone_empty();
196
14.0k
    }
197
26.8k
    data_block.swap(*block);
198
26.8k
    new_block_wrapper =
199
26.8k
            BlockWrapper::create_shared(std::move(data_block), local_state->_shared_state, -1);
200
26.8k
    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.8k
    DCHECK(shuffle_idx_to_instance_idx && !shuffle_idx_to_instance_idx->empty());
210
26.8k
    const auto& map = *shuffle_idx_to_instance_idx;
211
26.8k
    int32_t enqueue_rows = 0;
212
182k
    for (const auto& it : map) {
213
182k
        DCHECK(it.second >= 0 && it.second < _num_partitions)
214
0
                << it.first << " : " << it.second << " " << _num_partitions;
215
182k
        uint32_t start = partition_rows_histogram[it.first];
216
182k
        uint32_t size = partition_rows_histogram[it.first + 1] - start;
217
182k
        if (size > 0) {
218
52.2k
            enqueue_rows += size;
219
52.2k
            _enqueue_data_and_set_ready(
220
52.2k
                    it.second, local_state,
221
52.2k
                    {new_block_wrapper,
222
52.2k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
223
52.2k
        }
224
182k
    }
225
26.8k
    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.8k
    return Status::OK();
239
26.8k
}
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
305k
                                  SinkInfo& sink_info) {
285
305k
    if (in_block->empty()) {
286
99.8k
        return Status::OK();
287
99.8k
    }
288
205k
    Block new_block;
289
205k
    if (!_free_blocks.try_dequeue(new_block)) {
290
79.9k
        new_block = {in_block->clone_empty()};
291
79.9k
    }
292
205k
    new_block.swap(*in_block);
293
205k
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
294
205k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
295
205k
            std::move(new_block),
296
205k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, channel_id);
297
298
205k
    _enqueue_data_and_set_ready(channel_id, sink_info.local_state, std::move(wrapper));
299
300
205k
    sink_info.local_state->_memory_used_counter->set(
301
205k
            sink_info.local_state->_shared_state->mem_usage);
302
303
205k
    return Status::OK();
304
305k
}
305
306
584k
void PassthroughExchanger::close(SourceInfo&& source_info) {
307
584k
    Block next_block;
308
584k
    BlockWrapperSPtr wrapper;
309
584k
    bool eos;
310
584k
    _data_queue[source_info.channel_id].set_eos();
311
586k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
312
586k
                         source_info.channel_id)) {
313
        // do nothing
314
1.35k
    }
315
584k
}
316
317
10.9k
void PassToOneExchanger::close(SourceInfo&& source_info) {
318
10.9k
    Block next_block;
319
10.9k
    BlockWrapperSPtr wrapper;
320
10.9k
    bool eos;
321
10.9k
    _data_queue[source_info.channel_id].set_eos();
322
10.9k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
323
10.9k
                         source_info.channel_id)) {
324
        // do nothing
325
0
    }
326
10.9k
}
327
328
Status PassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
329
923k
                                       Profile&& profile, SourceInfo&& source_info) {
330
923k
    BlockWrapperSPtr next_block;
331
923k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
332
923k
    return Status::OK();
333
923k
}
334
335
Status PassToOneExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
336
4.41k
                                SinkInfo& sink_info) {
337
4.41k
    if (in_block->empty()) {
338
1.51k
        return Status::OK();
339
1.51k
    }
340
2.90k
    Block new_block;
341
2.90k
    if (!_free_blocks.try_dequeue(new_block)) {
342
1.71k
        new_block = {in_block->clone_empty()};
343
1.71k
    }
344
2.90k
    new_block.swap(*in_block);
345
346
2.90k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
347
2.90k
            std::move(new_block),
348
2.90k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, 0);
349
2.90k
    _enqueue_data_and_set_ready(0, sink_info.local_state, std::move(wrapper));
350
351
2.90k
    sink_info.local_state->_memory_used_counter->set(
352
2.90k
            sink_info.local_state->_shared_state->mem_usage);
353
354
2.90k
    return Status::OK();
355
4.41k
}
356
357
Status PassToOneExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
358
5.23k
                                     Profile&& profile, SourceInfo&& source_info) {
359
5.23k
    if (source_info.channel_id != 0) {
360
3
        *eos = true;
361
3
        return Status::OK();
362
3
    }
363
5.23k
    BlockWrapperSPtr next_block;
364
5.23k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
365
5.23k
    return Status::OK();
366
5.23k
}
367
368
127k
void ExchangerBase::finalize() {
369
127k
    DCHECK(_running_source_operators == 0);
370
127k
    Block block;
371
225k
    while (_free_blocks.try_dequeue(block)) {
372
        // do nothing
373
98.0k
    }
374
127k
}
375
376
Status BroadcastExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
377
5.00k
                                SinkInfo& sink_info) {
378
5.00k
    if (in_block->empty()) {
379
1.75k
        return Status::OK();
380
1.75k
    }
381
3.24k
    Block new_block;
382
3.24k
    if (!_free_blocks.try_dequeue(new_block)) {
383
2.28k
        new_block = {in_block->clone_empty()};
384
2.28k
    }
385
3.24k
    new_block.swap(*in_block);
386
3.24k
    auto wrapper = BlockWrapper::create_shared(
387
3.24k
            std::move(new_block),
388
3.24k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1);
389
27.6k
    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.24k
    return Status::OK();
396
5.00k
}
397
398
11.0k
void BroadcastExchanger::close(SourceInfo&& source_info) {
399
11.0k
    BroadcastBlock partitioned_block;
400
11.0k
    bool eos;
401
11.0k
    Block block;
402
11.0k
    _data_queue[source_info.channel_id].set_eos();
403
11.0k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
404
11.0k
                         source_info.channel_id)) {
405
        // do nothing
406
0
    }
407
11.0k
}
408
409
Status BroadcastExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
410
42.2k
                                     Profile&& profile, SourceInfo&& source_info) {
411
42.2k
    BroadcastBlock partitioned_block;
412
413
42.2k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
414
42.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
42.2k
    return Status::OK();
426
42.2k
}
427
428
Status AdaptivePassthroughExchanger::_passthrough_sink(RuntimeState* state, Block* in_block,
429
504
                                                       SinkInfo& sink_info) {
430
504
    Block new_block;
431
504
    if (!_free_blocks.try_dequeue(new_block)) {
432
310
        new_block = {in_block->clone_empty()};
433
310
    }
434
504
    new_block.swap(*in_block);
435
504
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
436
504
    _enqueue_data_and_set_ready(
437
504
            channel_id, sink_info.local_state,
438
504
            {BlockWrapper::create_shared(
439
504
                     std::move(new_block),
440
18.4E
                     sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1),
441
504
             {.row_idxs = nullptr, .offset_start = 0, .length = 0}});
442
443
504
    sink_info.local_state->_memory_used_counter->set(
444
504
            sink_info.local_state->_shared_state->mem_usage);
445
504
    return Status::OK();
446
504
}
447
448
Status AdaptivePassthroughExchanger::_shuffle_sink(RuntimeState* state, Block* block,
449
2.14k
                                                   SinkInfo& sink_info) {
450
2.14k
    std::vector<uint32_t> channel_ids;
451
2.14k
    const auto num_rows = block->rows();
452
2.14k
    channel_ids.resize(num_rows, 0);
453
2.14k
    if (num_rows <= _num_partitions) {
454
1.58k
        std::iota(channel_ids.begin(), channel_ids.end(), 0);
455
1.58k
    } else {
456
565
        size_t i = 0;
457
34.9k
        for (; i < num_rows - _num_partitions; i += _num_partitions) {
458
34.3k
            std::iota(channel_ids.begin() + i, channel_ids.begin() + i + _num_partitions, 0);
459
34.3k
        }
460
565
        if (i < num_rows - 1) {
461
356
            std::iota(channel_ids.begin() + i, channel_ids.end(), 0);
462
356
        }
463
565
    }
464
465
2.14k
    sink_info.local_state->_memory_used_counter->set(
466
2.14k
            sink_info.local_state->_shared_state->mem_usage);
467
2.14k
    RETURN_IF_ERROR(_split_rows(state, channel_ids, block, sink_info));
468
2.14k
    return Status::OK();
469
2.14k
}
470
471
Status AdaptivePassthroughExchanger::_split_rows(RuntimeState* state,
472
                                                 const std::vector<uint32_t>& channel_ids,
473
2.14k
                                                 Block* block, SinkInfo& sink_info) {
474
2.14k
    const auto rows = cast_set<int32_t>(block->rows());
475
2.14k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
476
2.14k
    auto& partition_rows_histogram = _partition_rows_histogram[sink_info.ins_idx];
477
2.14k
    {
478
2.14k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
479
110k
        for (int32_t i = 0; i < rows; ++i) {
480
107k
            partition_rows_histogram[channel_ids[i]]++;
481
107k
        }
482
14.0k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
483
11.9k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
484
11.9k
        }
485
486
110k
        for (int32_t i = rows - 1; i >= 0; --i) {
487
107k
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
488
107k
            partition_rows_histogram[channel_ids[i]]--;
489
107k
        }
490
2.14k
    }
491
2.14k
    Block data_block;
492
2.14k
    if (!_free_blocks.try_dequeue(data_block)) {
493
1.92k
        data_block = block->clone_empty();
494
1.92k
    }
495
2.14k
    data_block.swap(*block);
496
2.14k
    std::shared_ptr<BlockWrapper> new_block_wrapper = BlockWrapper::create_shared(
497
2.14k
            std::move(data_block), sink_info.local_state->_shared_state, sink_info.ins_idx);
498
2.14k
    if (new_block_wrapper->_data_block.empty()) {
499
0
        return Status::OK();
500
0
    }
501
14.0k
    for (int32_t i = 0; i < _num_partitions; i++) {
502
11.9k
        const uint32_t start = partition_rows_histogram[i];
503
11.9k
        const uint32_t size = partition_rows_histogram[i + 1] - start;
504
11.9k
        if (size > 0) {
505
6.13k
            _enqueue_data_and_set_ready(
506
6.13k
                    i, sink_info.local_state,
507
6.13k
                    {new_block_wrapper,
508
6.13k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
509
6.13k
        }
510
11.9k
    }
511
2.14k
    return Status::OK();
512
2.14k
}
513
514
Status AdaptivePassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos,
515
6.46k
                                          Profile&& profile, SinkInfo& sink_info) {
516
6.46k
    if (in_block->empty()) {
517
3.81k
        return Status::OK();
518
3.81k
    }
519
2.65k
    if (_is_pass_through) {
520
504
        return _passthrough_sink(state, in_block, sink_info);
521
2.15k
    } else {
522
2.15k
        if (++_total_block >= _num_partitions) {
523
299
            _is_pass_through = true;
524
299
        }
525
2.15k
        return _shuffle_sink(state, in_block, sink_info);
526
2.15k
    }
527
2.65k
}
528
529
Status AdaptivePassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
530
7.19k
                                               Profile&& profile, SourceInfo&& source_info) {
531
7.19k
    if (!_tmp_block[source_info.channel_id].empty()) {
532
194
        *block = std::move(_tmp_block[source_info.channel_id]);
533
194
        *eos = _tmp_eos[source_info.channel_id];
534
194
        _tmp_block[source_info.channel_id] = {};
535
194
        return Status::OK();
536
194
    }
537
6.99k
    PartitionedBlock partitioned_block;
538
6.99k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
539
6.99k
                      source_info.channel_id)) {
540
3.64k
        SCOPED_TIMER(profile.copy_data_timer);
541
3.64k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
542
3.64k
                block, partitioned_block.first->_data_block);
543
3.64k
        auto& mutable_block = scoped_mutable_block.mutable_block();
544
6.62k
        do {
545
6.62k
            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
501
                if (mutable_block.rows() > 0) {
548
194
                    _tmp_block[source_info.channel_id] =
549
194
                            std::move(partitioned_block.first->_data_block);
550
194
                    _tmp_eos[source_info.channel_id] = *eos;
551
194
                    *eos = false;
552
307
                } else {
553
307
                    scoped_mutable_block.restore();
554
307
                    *block = std::move(partitioned_block.first->_data_block);
555
307
                }
556
501
                break;
557
501
            }
558
6.12k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
559
6.12k
                                       partitioned_block.second.offset_start;
560
6.12k
            auto block_wrapper = partitioned_block.first;
561
6.12k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
562
6.12k
                                                   offset_start + partitioned_block.second.length));
563
6.12k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
564
6.12k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
565
6.12k
                               source_info.channel_id));
566
3.64k
    }
567
6.99k
    return Status::OK();
568
6.99k
}
569
570
5.01k
void AdaptivePassthroughExchanger::close(SourceInfo&& source_info) {
571
5.01k
    PartitionedBlock partitioned_block;
572
5.01k
    bool eos;
573
5.01k
    Block block;
574
5.01k
    _data_queue[source_info.channel_id].set_eos();
575
5.02k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
576
5.02k
                         source_info.channel_id)) {
577
        // do nothing
578
5
    }
579
5.01k
}
580
581
} // namespace doris