Coverage Report

Created: 2026-06-25 06:13

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