Coverage Report

Created: 2026-05-16 12:16

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
267k
                                                       BlockType&& block) {
31
267k
    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
267k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
62.3k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
62.3k
        block.first->record_channel_id(channel_id);
43
205k
    } else {
44
205k
        block->record_channel_id(channel_id);
45
205k
    }
46
47
267k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
267k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
267k
    }
50
267k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
38.4k
                                                       BlockType&& block) {
31
38.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
38.4k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
38.4k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
38.4k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
38.4k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
38.4k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
38.4k
    }
50
38.4k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS4_
Line
Count
Source
30
205k
                                                       BlockType&& block) {
31
205k
    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
205k
    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
205k
    } else {
44
205k
        block->record_channel_id(channel_id);
45
205k
    }
46
47
205k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
205k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
205k
    }
50
205k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
23.9k
                                                       BlockType&& block) {
31
23.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
23.9k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
23.9k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
23.9k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
23.9k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
23.9k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
23.9k
    }
50
23.9k
}
51
52
template <typename BlockType>
53
bool Exchanger<BlockType>::_dequeue_data(LocalExchangeSourceLocalState* local_state,
54
                                         BlockType& block, bool* eos, Block* data_block,
55
1.83M
                                         int channel_id) {
56
1.83M
    if (local_state == nullptr) {
57
20
        return _dequeue_data(block, eos, data_block, channel_id);
58
20
    }
59
1.83M
    bool all_finished = _running_sink_operators == 0;
60
1.83M
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
62.2k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
62.2k
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
205k
        } else {
65
205k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
205k
            data_block->swap(block->_data_block);
67
205k
        }
68
267k
        return true;
69
1.57M
    } else if (all_finished) {
70
1.39M
        *eos = true;
71
1.39M
    } else {
72
176k
        std::unique_lock l(*_m[channel_id]);
73
176k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
22
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
22
                local_state->_shared_state->sub_mem_usage(channel_id,
77
22
                                                          block.first->_allocated_bytes);
78
22
            } else {
79
2
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
2
                data_block->swap(block->_data_block);
81
2
            }
82
24
            return true;
83
24
        }
84
176k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
176k
        local_state->_dependency->block();
86
176k
    }
87
1.57M
    return false;
88
1.83M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
196k
                                         int channel_id) {
56
196k
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
196k
    bool all_finished = _running_sink_operators == 0;
60
196k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
38.4k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
38.4k
            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
38.4k
        return true;
69
158k
    } else if (all_finished) {
70
132k
        *eos = true;
71
132k
    } else {
72
25.3k
        std::unique_lock l(*_m[channel_id]);
73
25.3k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
14
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
14
                local_state->_shared_state->sub_mem_usage(channel_id,
77
14
                                                          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
14
            return true;
83
14
        }
84
25.2k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
25.2k
        local_state->_dependency->block();
86
25.2k
    }
87
158k
    return false;
88
196k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS4_PbPNS_5BlockEi
Line
Count
Source
55
1.58M
                                         int channel_id) {
56
1.58M
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
1.58M
    bool all_finished = _running_sink_operators == 0;
60
1.58M
    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
205k
        } else {
65
205k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
205k
            data_block->swap(block->_data_block);
67
205k
        }
68
205k
        return true;
69
1.38M
    } else if (all_finished) {
70
1.23M
        *eos = true;
71
1.23M
    } else {
72
144k
        std::unique_lock l(*_m[channel_id]);
73
144k
        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
2
            } else {
79
2
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
2
                data_block->swap(block->_data_block);
81
2
            }
82
2
            return true;
83
2
        }
84
144k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
144k
        local_state->_dependency->block();
86
144k
    }
87
1.38M
    return false;
88
1.58M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
54.8k
                                         int channel_id) {
56
54.8k
    if (local_state == nullptr) {
57
4
        return _dequeue_data(block, eos, data_block, channel_id);
58
4
    }
59
54.8k
    bool all_finished = _running_sink_operators == 0;
60
54.8k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
23.8k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
23.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
23.8k
        return true;
69
30.9k
    } else if (all_finished) {
70
24.3k
        *eos = true;
71
24.3k
    } else {
72
6.57k
        std::unique_lock l(*_m[channel_id]);
73
6.57k
        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
            } else {
79
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
                data_block->swap(block->_data_block);
81
            }
82
8
            return true;
83
8
        }
84
6.56k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
6.56k
        local_state->_dependency->block();
86
6.56k
    }
87
30.9k
    return false;
88
54.8k
}
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
78.7k
                              SinkInfo& sink_info) {
116
78.7k
    if (in_block->empty()) {
117
62.2k
        return Status::OK();
118
62.2k
    }
119
16.4k
    {
120
16.4k
        SCOPED_TIMER(profile.compute_hash_value_timer);
121
16.4k
        RETURN_IF_ERROR(sink_info.partitioner->do_partitioning(state, in_block));
122
16.4k
    }
123
16.4k
    {
124
16.4k
        SCOPED_TIMER(profile.distribute_timer);
125
16.4k
        RETURN_IF_ERROR(_split_rows(state, sink_info.partitioner->get_channel_ids(), in_block,
126
16.4k
                                    *sink_info.channel_id, sink_info.local_state,
127
16.4k
                                    sink_info.shuffle_idx_to_instance_idx));
128
16.4k
    }
129
130
16.4k
    sink_info.local_state->_memory_used_counter->set(
131
16.4k
            sink_info.local_state->_shared_state->mem_usage);
132
16.4k
    return Status::OK();
133
16.4k
}
134
135
62.8k
void ShuffleExchanger::close(SourceInfo&& source_info) {
136
62.8k
    PartitionedBlock partitioned_block;
137
62.8k
    bool eos;
138
62.8k
    Block block;
139
62.8k
    _data_queue[source_info.channel_id].set_eos();
140
62.8k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
141
62.8k
                         source_info.channel_id)) {
142
        // do nothing
143
4
    }
144
62.8k
}
145
146
Status ShuffleExchanger::get_block(RuntimeState* state, Block* block, bool* eos, Profile&& profile,
147
83.9k
                                   SourceInfo&& source_info) {
148
83.9k
    PartitionedBlock partitioned_block;
149
83.9k
    MutableBlock mutable_block;
150
151
83.9k
    auto get_data = [&]() -> Status {
152
32.9k
        do {
153
32.9k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
154
32.9k
                                       partitioned_block.second.offset_start;
155
32.9k
            auto block_wrapper = partitioned_block.first;
156
32.9k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
157
32.9k
                                                   offset_start + partitioned_block.second.length));
158
32.9k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
159
32.9k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
160
32.4k
                               source_info.channel_id));
161
27.6k
        return Status::OK();
162
27.6k
    };
163
164
83.9k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
165
83.9k
                      source_info.channel_id)) {
166
27.6k
        SCOPED_TIMER(profile.copy_data_timer);
167
27.6k
        mutable_block = VectorizedUtils::build_mutable_mem_reuse_block(
168
27.6k
                block, partitioned_block.first->_data_block);
169
27.6k
        RETURN_IF_ERROR(get_data());
170
27.6k
    }
171
83.9k
    return Status::OK();
172
83.9k
}
173
174
Status ShuffleExchanger::_split_rows(RuntimeState* state, const std::vector<uint32_t>& channel_ids,
175
                                     Block* block, int channel_id,
176
                                     LocalExchangeSinkLocalState* local_state,
177
16.3k
                                     std::map<int, int>* shuffle_idx_to_instance_idx) {
178
16.3k
    if (local_state == nullptr) {
179
0
        return _split_rows(state, channel_ids, block, channel_id);
180
0
    }
181
16.3k
    const auto rows = cast_set<int32_t>(block->rows());
182
16.3k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
183
16.3k
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
184
16.3k
    {
185
16.3k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
186
9.42M
        for (int32_t i = 0; i < rows; ++i) {
187
9.40M
            partition_rows_histogram[channel_ids[i]]++;
188
9.40M
        }
189
157k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
190
141k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
191
141k
        }
192
9.13M
        for (int32_t i = rows - 1; i >= 0; --i) {
193
9.11M
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
194
9.11M
            partition_rows_histogram[channel_ids[i]]--;
195
9.11M
        }
196
16.3k
    }
197
198
16.3k
    Block data_block;
199
16.3k
    std::shared_ptr<BlockWrapper> new_block_wrapper;
200
16.3k
    if (!_free_blocks.try_dequeue(data_block)) {
201
8.11k
        data_block = block->clone_empty();
202
8.11k
    }
203
16.3k
    data_block.swap(*block);
204
16.3k
    new_block_wrapper =
205
16.3k
            BlockWrapper::create_shared(std::move(data_block), local_state->_shared_state, -1);
206
16.3k
    if (new_block_wrapper->_data_block.empty()) {
207
0
        return Status::OK();
208
0
    }
209
    /**
210
     * Data are hash-shuffled and distributed to all instances of
211
     * all BEs. So we need a shuffleId-To-InstanceId mapping.
212
     * For example, row 1 get a hash value 1 which means we should distribute to instance 1 on
213
     * BE 1 and row 2 get a hash value 2 which means we should distribute to instance 1 on BE 3.
214
     */
215
16.3k
    DCHECK(shuffle_idx_to_instance_idx && shuffle_idx_to_instance_idx->size() > 0);
216
16.3k
    const auto& map = *shuffle_idx_to_instance_idx;
217
16.3k
    int32_t enqueue_rows = 0;
218
141k
    for (const auto& it : map) {
219
141k
        DCHECK(it.second >= 0 && it.second < _num_partitions)
220
0
                << it.first << " : " << it.second << " " << _num_partitions;
221
141k
        uint32_t start = partition_rows_histogram[it.first];
222
141k
        uint32_t size = partition_rows_histogram[it.first + 1] - start;
223
141k
        if (size > 0) {
224
32.9k
            enqueue_rows += size;
225
32.9k
            _enqueue_data_and_set_ready(
226
32.9k
                    it.second, local_state,
227
32.9k
                    {new_block_wrapper,
228
32.9k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
229
32.9k
        }
230
141k
    }
231
16.3k
    if (enqueue_rows != rows) [[unlikely]] {
232
1
        fmt::memory_buffer debug_string_buffer;
233
1
        fmt::format_to(debug_string_buffer, "Type: {}, Local Exchange Id: {}, Shuffled Map: ",
234
1
                       get_exchange_type_name(get_type()), local_state->parent()->node_id());
235
3
        for (const auto& it : map) {
236
3
            fmt::format_to(debug_string_buffer, "[{}:{}], ", it.first, it.second);
237
3
        }
238
1
        return Status::InternalError(
239
1
                "Rows mismatched! Data may be lost. [Expected enqueue rows={}, Real enqueue "
240
1
                "rows={}, Detail: {}]",
241
1
                rows, enqueue_rows, fmt::to_string(debug_string_buffer));
242
1
    }
243
244
16.3k
    return Status::OK();
245
16.3k
}
246
247
Status ShuffleExchanger::_split_rows(RuntimeState* state, const std::vector<uint32_t>& channel_ids,
248
0
                                     Block* block, int channel_id) {
249
0
    const auto rows = cast_set<int32_t>(block->rows());
250
0
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
251
0
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
252
0
    {
253
0
        partition_rows_histogram.assign(_num_partitions + 1, 0);
254
0
        for (int32_t i = 0; i < rows; ++i) {
255
0
            partition_rows_histogram[channel_ids[i]]++;
256
0
        }
257
0
        for (int32_t i = 1; i <= _num_partitions; ++i) {
258
0
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
259
0
        }
260
0
        for (int32_t i = rows - 1; i >= 0; --i) {
261
0
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
262
0
            partition_rows_histogram[channel_ids[i]]--;
263
0
        }
264
0
    }
265
266
0
    Block data_block;
267
0
    std::shared_ptr<BlockWrapper> new_block_wrapper;
268
0
    if (!_free_blocks.try_dequeue(data_block)) {
269
0
        data_block = block->clone_empty();
270
0
    }
271
0
    data_block.swap(*block);
272
0
    new_block_wrapper = BlockWrapper::create_shared(std::move(data_block), nullptr, -1);
273
0
    if (new_block_wrapper->_data_block.empty()) {
274
0
        return Status::OK();
275
0
    }
276
0
    for (int i = 0; i < _num_partitions; i++) {
277
0
        uint32_t start = partition_rows_histogram[i];
278
0
        uint32_t size = partition_rows_histogram[i + 1] - start;
279
0
        if (size > 0) {
280
0
            _enqueue_data_and_set_ready(
281
0
                    i, {new_block_wrapper,
282
0
                        {.row_idxs = row_idx, .offset_start = start, .length = size}});
283
0
        }
284
0
    }
285
286
0
    return Status::OK();
287
0
}
288
289
Status PassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
290
302k
                                  SinkInfo& sink_info) {
291
302k
    if (in_block->empty()) {
292
100k
        return Status::OK();
293
100k
    }
294
201k
    Block new_block;
295
201k
    if (!_free_blocks.try_dequeue(new_block)) {
296
78.3k
        new_block = {in_block->clone_empty()};
297
78.3k
    }
298
201k
    new_block.swap(*in_block);
299
201k
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
300
201k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
301
201k
            std::move(new_block),
302
201k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, channel_id);
303
304
201k
    _enqueue_data_and_set_ready(channel_id, sink_info.local_state, std::move(wrapper));
305
306
201k
    sink_info.local_state->_memory_used_counter->set(
307
201k
            sink_info.local_state->_shared_state->mem_usage);
308
309
201k
    return Status::OK();
310
302k
}
311
312
610k
void PassthroughExchanger::close(SourceInfo&& source_info) {
313
610k
    Block next_block;
314
610k
    BlockWrapperSPtr wrapper;
315
610k
    bool eos;
316
610k
    _data_queue[source_info.channel_id].set_eos();
317
611k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
318
611k
                         source_info.channel_id)) {
319
        // do nothing
320
1.05k
    }
321
610k
}
322
323
13.8k
void PassToOneExchanger::close(SourceInfo&& source_info) {
324
13.8k
    Block next_block;
325
13.8k
    BlockWrapperSPtr wrapper;
326
13.8k
    bool eos;
327
13.8k
    _data_queue[source_info.channel_id].set_eos();
328
13.8k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
329
13.8k
                         source_info.channel_id)) {
330
        // do nothing
331
0
    }
332
13.8k
}
333
334
Status PassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
335
952k
                                       Profile&& profile, SourceInfo&& source_info) {
336
952k
    BlockWrapperSPtr next_block;
337
952k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
338
952k
    return Status::OK();
339
952k
}
340
341
Status PassToOneExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
342
5.06k
                                SinkInfo& sink_info) {
343
5.06k
    if (in_block->empty()) {
344
1.73k
        return Status::OK();
345
1.73k
    }
346
3.33k
    Block new_block;
347
3.33k
    if (!_free_blocks.try_dequeue(new_block)) {
348
1.87k
        new_block = {in_block->clone_empty()};
349
1.87k
    }
350
3.33k
    new_block.swap(*in_block);
351
352
3.33k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
353
3.33k
            std::move(new_block),
354
3.33k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, 0);
355
3.33k
    _enqueue_data_and_set_ready(0, sink_info.local_state, std::move(wrapper));
356
357
3.33k
    sink_info.local_state->_memory_used_counter->set(
358
3.33k
            sink_info.local_state->_shared_state->mem_usage);
359
360
3.33k
    return Status::OK();
361
5.06k
}
362
363
Status PassToOneExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
364
6.07k
                                     Profile&& profile, SourceInfo&& source_info) {
365
6.07k
    if (source_info.channel_id != 0) {
366
3
        *eos = true;
367
3
        return Status::OK();
368
3
    }
369
6.07k
    BlockWrapperSPtr next_block;
370
6.07k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
371
6.07k
    return Status::OK();
372
6.07k
}
373
374
110k
void ExchangerBase::finalize() {
375
110k
    DCHECK(_running_source_operators == 0);
376
110k
    Block block;
377
200k
    while (_free_blocks.try_dequeue(block)) {
378
        // do nothing
379
90.8k
    }
380
110k
}
381
382
Status BroadcastExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
383
4.30k
                                SinkInfo& sink_info) {
384
4.30k
    if (in_block->empty()) {
385
1.46k
        return Status::OK();
386
1.46k
    }
387
2.83k
    Block new_block;
388
2.83k
    if (!_free_blocks.try_dequeue(new_block)) {
389
1.96k
        new_block = {in_block->clone_empty()};
390
1.96k
    }
391
2.83k
    new_block.swap(*in_block);
392
2.83k
    auto wrapper = BlockWrapper::create_shared(
393
2.83k
            std::move(new_block),
394
2.83k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1);
395
26.7k
    for (int i = 0; i < _num_partitions; i++) {
396
23.9k
        _enqueue_data_and_set_ready(
397
23.9k
                i, sink_info.local_state,
398
23.9k
                {wrapper, {.offset_start = 0, .length = wrapper->_data_block.rows()}});
399
23.9k
    }
400
401
2.83k
    return Status::OK();
402
4.30k
}
403
404
12.1k
void BroadcastExchanger::close(SourceInfo&& source_info) {
405
12.1k
    BroadcastBlock partitioned_block;
406
12.1k
    bool eos;
407
12.1k
    Block block;
408
12.1k
    _data_queue[source_info.channel_id].set_eos();
409
12.1k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
410
12.1k
                         source_info.channel_id)) {
411
        // do nothing
412
0
    }
413
12.1k
}
414
415
Status BroadcastExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
416
42.6k
                                     Profile&& profile, SourceInfo&& source_info) {
417
42.6k
    BroadcastBlock partitioned_block;
418
419
42.6k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
420
42.6k
                      source_info.channel_id)) {
421
23.8k
        SCOPED_TIMER(profile.copy_data_timer);
422
23.8k
        MutableBlock mutable_block = VectorizedUtils::build_mutable_mem_reuse_block(
423
23.8k
                block, partitioned_block.first->_data_block);
424
23.8k
        auto block_wrapper = partitioned_block.first;
425
23.8k
        RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block,
426
23.8k
                                               partitioned_block.second.offset_start,
427
23.8k
                                               partitioned_block.second.length));
428
23.8k
    }
429
430
42.6k
    return Status::OK();
431
42.6k
}
432
433
Status AdaptivePassthroughExchanger::_passthrough_sink(RuntimeState* state, Block* in_block,
434
591
                                                       SinkInfo& sink_info) {
435
591
    Block new_block;
436
591
    if (!_free_blocks.try_dequeue(new_block)) {
437
201
        new_block = {in_block->clone_empty()};
438
201
    }
439
591
    new_block.swap(*in_block);
440
591
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
441
591
    _enqueue_data_and_set_ready(
442
591
            channel_id, sink_info.local_state,
443
591
            {BlockWrapper::create_shared(
444
591
                     std::move(new_block),
445
591
                     sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1),
446
591
             {.row_idxs = nullptr, .offset_start = 0, .length = 0}});
447
448
591
    sink_info.local_state->_memory_used_counter->set(
449
591
            sink_info.local_state->_shared_state->mem_usage);
450
591
    return Status::OK();
451
591
}
452
453
Status AdaptivePassthroughExchanger::_shuffle_sink(RuntimeState* state, Block* block,
454
1.92k
                                                   SinkInfo& sink_info) {
455
1.92k
    std::vector<uint32_t> channel_ids;
456
1.92k
    const auto num_rows = block->rows();
457
1.92k
    channel_ids.resize(num_rows, 0);
458
1.92k
    if (num_rows <= _num_partitions) {
459
1.62k
        std::iota(channel_ids.begin(), channel_ids.end(), 0);
460
1.62k
    } else {
461
302
        size_t i = 0;
462
16.0k
        for (; i < num_rows - _num_partitions; i += _num_partitions) {
463
15.7k
            std::iota(channel_ids.begin() + i, channel_ids.begin() + i + _num_partitions, 0);
464
15.7k
        }
465
302
        if (i < num_rows - 1) {
466
170
            std::iota(channel_ids.begin() + i, channel_ids.end(), 0);
467
170
        }
468
302
    }
469
470
1.92k
    sink_info.local_state->_memory_used_counter->set(
471
1.92k
            sink_info.local_state->_shared_state->mem_usage);
472
1.92k
    RETURN_IF_ERROR(_split_rows(state, channel_ids, block, sink_info));
473
1.92k
    return Status::OK();
474
1.92k
}
475
476
Status AdaptivePassthroughExchanger::_split_rows(RuntimeState* state,
477
                                                 const std::vector<uint32_t>& channel_ids,
478
1.92k
                                                 Block* block, SinkInfo& sink_info) {
479
1.92k
    const auto rows = cast_set<int32_t>(block->rows());
480
1.92k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
481
1.92k
    auto& partition_rows_histogram = _partition_rows_histogram[sink_info.ins_idx];
482
1.92k
    {
483
1.92k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
484
67.3k
        for (int32_t i = 0; i < rows; ++i) {
485
65.3k
            partition_rows_histogram[channel_ids[i]]++;
486
65.3k
        }
487
13.3k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
488
11.4k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
489
11.4k
        }
490
491
67.3k
        for (int32_t i = rows - 1; i >= 0; --i) {
492
65.3k
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
493
65.3k
            partition_rows_histogram[channel_ids[i]]--;
494
65.3k
        }
495
1.92k
    }
496
1.92k
    Block data_block;
497
1.92k
    if (!_free_blocks.try_dequeue(data_block)) {
498
1.69k
        data_block = block->clone_empty();
499
1.69k
    }
500
1.92k
    data_block.swap(*block);
501
1.92k
    std::shared_ptr<BlockWrapper> new_block_wrapper = BlockWrapper::create_shared(
502
1.92k
            std::move(data_block), sink_info.local_state->_shared_state, sink_info.ins_idx);
503
1.92k
    if (new_block_wrapper->_data_block.empty()) {
504
0
        return Status::OK();
505
0
    }
506
13.3k
    for (int32_t i = 0; i < _num_partitions; i++) {
507
11.4k
        const uint32_t start = partition_rows_histogram[i];
508
11.4k
        const uint32_t size = partition_rows_histogram[i + 1] - start;
509
11.4k
        if (size > 0) {
510
4.89k
            _enqueue_data_and_set_ready(
511
4.89k
                    i, sink_info.local_state,
512
4.89k
                    {new_block_wrapper,
513
4.89k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
514
4.89k
        }
515
11.4k
    }
516
1.92k
    return Status::OK();
517
1.92k
}
518
519
Status AdaptivePassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos,
520
7.14k
                                          Profile&& profile, SinkInfo& sink_info) {
521
7.14k
    if (in_block->empty()) {
522
4.62k
        return Status::OK();
523
4.62k
    }
524
2.52k
    if (_is_pass_through) {
525
591
        return _passthrough_sink(state, in_block, sink_info);
526
1.92k
    } else {
527
1.92k
        if (++_total_block >= _num_partitions) {
528
273
            _is_pass_through = true;
529
273
        }
530
1.92k
        return _shuffle_sink(state, in_block, sink_info);
531
1.92k
    }
532
2.52k
}
533
534
Status AdaptivePassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
535
7.37k
                                               Profile&& profile, SourceInfo&& source_info) {
536
7.37k
    if (!_tmp_block[source_info.channel_id].empty()) {
537
129
        *block = std::move(_tmp_block[source_info.channel_id]);
538
129
        *eos = _tmp_eos[source_info.channel_id];
539
129
        _tmp_block[source_info.channel_id] = {};
540
129
        return Status::OK();
541
129
    }
542
7.24k
    PartitionedBlock partitioned_block;
543
7.24k
    MutableBlock mutable_block;
544
545
7.24k
    auto get_data = [&]() -> Status {
546
5.46k
        do {
547
5.46k
            if (partitioned_block.second.row_idxs == nullptr) {
548
                // The passthrough path which means the block is not partitioned, we can directly move the block without copying.
549
587
                if (mutable_block.rows() > 0) {
550
129
                    _tmp_block[source_info.channel_id] =
551
129
                            std::move(partitioned_block.first->_data_block);
552
129
                    _tmp_eos[source_info.channel_id] = *eos;
553
129
                    *eos = false;
554
458
                } else {
555
458
                    *block = std::move(partitioned_block.first->_data_block);
556
458
                }
557
587
                break;
558
587
            }
559
4.88k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
560
4.88k
                                       partitioned_block.second.offset_start;
561
4.88k
            auto block_wrapper = partitioned_block.first;
562
4.88k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
563
4.88k
                                                   offset_start + partitioned_block.second.length));
564
4.88k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
565
4.88k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
566
4.88k
                               source_info.channel_id));
567
3.39k
        return Status::OK();
568
3.39k
    };
569
570
7.24k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
571
7.24k
                      source_info.channel_id)) {
572
3.40k
        SCOPED_TIMER(profile.copy_data_timer);
573
3.40k
        mutable_block = VectorizedUtils::build_mutable_mem_reuse_block(
574
3.40k
                block, partitioned_block.first->_data_block);
575
3.40k
        RETURN_IF_ERROR(get_data());
576
3.40k
    }
577
7.24k
    return Status::OK();
578
7.24k
}
579
580
5.16k
void AdaptivePassthroughExchanger::close(SourceInfo&& source_info) {
581
5.16k
    PartitionedBlock partitioned_block;
582
5.16k
    bool eos;
583
5.16k
    Block block;
584
5.16k
    _data_queue[source_info.channel_id].set_eos();
585
5.16k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
586
5.16k
                         source_info.channel_id)) {
587
        // do nothing
588
2
    }
589
5.16k
}
590
591
} // namespace doris