Coverage Report

Created: 2026-07-14 15:37

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
310k
                                                       BlockType&& block) {
31
310k
    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
310k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
112k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
112k
        block.first->record_channel_id(channel_id);
43
197k
    } else {
44
197k
        block->record_channel_id(channel_id);
45
197k
    }
46
47
310k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
310k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
310k
    }
50
310k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
93.5k
                                                       BlockType&& block) {
31
93.5k
    if (local_state == nullptr) {
32
0
        _enqueue_data_and_set_ready(channel_id, std::move(block));
33
0
        return;
34
0
    }
35
    // PartitionedBlock is used by shuffle exchanger.
36
    // PartitionedBlock will be push into multiple queues with different row ranges, so it will be
37
    // referenced multiple times. Otherwise, we only ref the block once because it is only push into
38
    // one queue.
39
93.5k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
93.5k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
93.5k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
93.5k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
93.5k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
93.5k
    }
50
93.5k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS4_
Line
Count
Source
30
197k
                                                       BlockType&& block) {
31
197k
    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
197k
    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
197k
    } else {
44
197k
        block->record_channel_id(channel_id);
45
197k
    }
46
47
197k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
197k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
197k
    }
50
197k
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE27_enqueue_data_and_set_readyEiPNS_27LocalExchangeSinkLocalStateEOS7_
Line
Count
Source
30
18.9k
                                                       BlockType&& block) {
31
18.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
18.9k
    std::unique_lock l(*_m[channel_id]);
40
    if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
41
18.9k
                  std::is_same_v<BroadcastBlock, BlockType>) {
42
18.9k
        block.first->record_channel_id(channel_id);
43
    } else {
44
        block->record_channel_id(channel_id);
45
    }
46
47
18.9k
    if (_data_queue[channel_id].enqueue(std::move(block))) {
48
18.9k
        local_state->_shared_state->set_ready_to_read(channel_id);
49
18.9k
    }
50
18.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.98M
                                         int channel_id) {
56
1.98M
    if (local_state == nullptr) {
57
20
        return _dequeue_data(block, eos, data_block, channel_id);
58
20
    }
59
1.98M
    bool all_finished = _running_sink_operators == 0;
60
1.98M
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
112k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
112k
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
197k
        } else {
65
197k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
197k
            data_block->swap(block->_data_block);
67
197k
        }
68
310k
        return true;
69
1.67M
    } else if (all_finished) {
70
1.50M
        *eos = true;
71
1.50M
    } else {
72
163k
        std::unique_lock l(*_m[channel_id]);
73
163k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
18
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
18
                local_state->_shared_state->sub_mem_usage(channel_id,
77
18
                                                          block.first->_allocated_bytes);
78
18
            } else {
79
17
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
17
                data_block->swap(block->_data_block);
81
17
            }
82
35
            return true;
83
35
        }
84
163k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
163k
        local_state->_dependency->block();
86
163k
    }
87
1.67M
    return false;
88
1.98M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_18PartitionedRowIdxsEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
431k
                                         int channel_id) {
56
431k
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
431k
    bool all_finished = _running_sink_operators == 0;
60
431k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
93.4k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
93.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
93.4k
        return true;
69
337k
    } else if (all_finished) {
70
295k
        *eos = true;
71
295k
    } else {
72
42.1k
        std::unique_lock l(*_m[channel_id]);
73
42.1k
        if (_data_queue[channel_id].try_dequeue(block)) {
74
            if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
75
16
                          std::is_same_v<BroadcastBlock, BlockType>) {
76
16
                local_state->_shared_state->sub_mem_usage(channel_id,
77
16
                                                          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
16
            return true;
83
16
        }
84
42.1k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
42.1k
        local_state->_dependency->block();
86
42.1k
    }
87
337k
    return false;
88
431k
}
_ZN5doris9ExchangerISt10shared_ptrINS_13ExchangerBase12BlockWrapperEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS4_PbPNS_5BlockEi
Line
Count
Source
55
1.50M
                                         int channel_id) {
56
1.50M
    if (local_state == nullptr) {
57
8
        return _dequeue_data(block, eos, data_block, channel_id);
58
8
    }
59
1.50M
    bool all_finished = _running_sink_operators == 0;
60
1.50M
    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
197k
        } else {
65
197k
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
197k
            data_block->swap(block->_data_block);
67
197k
        }
68
197k
        return true;
69
1.31M
    } else if (all_finished) {
70
1.19M
        *eos = true;
71
1.19M
    } else {
72
117k
        std::unique_lock l(*_m[channel_id]);
73
117k
        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
17
            } else {
79
17
                local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
80
17
                data_block->swap(block->_data_block);
81
17
            }
82
17
            return true;
83
17
        }
84
117k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
117k
        local_state->_dependency->block();
86
117k
    }
87
1.31M
    return false;
88
1.50M
}
_ZN5doris9ExchangerISt4pairISt10shared_ptrINS_13ExchangerBase12BlockWrapperEENS_17BroadcastRowRangeEEE13_dequeue_dataEPNS_29LocalExchangeSourceLocalStateERS7_PbPNS_5BlockEi
Line
Count
Source
55
41.1k
                                         int channel_id) {
56
41.1k
    if (local_state == nullptr) {
57
4
        return _dequeue_data(block, eos, data_block, channel_id);
58
4
    }
59
41.1k
    bool all_finished = _running_sink_operators == 0;
60
41.1k
    if (_data_queue[channel_id].try_dequeue(block)) {
61
        if constexpr (std::is_same_v<PartitionedBlock, BlockType> ||
62
18.9k
                      std::is_same_v<BroadcastBlock, BlockType>) {
63
18.9k
            local_state->_shared_state->sub_mem_usage(channel_id, block.first->_allocated_bytes);
64
        } else {
65
            local_state->_shared_state->sub_mem_usage(channel_id, block->_allocated_bytes);
66
            data_block->swap(block->_data_block);
67
        }
68
18.9k
        return true;
69
22.1k
    } else if (all_finished) {
70
17.8k
        *eos = true;
71
17.8k
    } else {
72
4.33k
        std::unique_lock l(*_m[channel_id]);
73
4.33k
        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.33k
        COUNTER_UPDATE(local_state->_get_block_failed_counter, 1);
85
4.33k
        local_state->_dependency->block();
86
4.33k
    }
87
22.1k
    return false;
88
41.1k
}
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
172k
                              SinkInfo& sink_info) {
116
172k
    if (in_block->empty()) {
117
142k
        return Status::OK();
118
142k
    }
119
29.6k
    {
120
29.6k
        SCOPED_TIMER(profile.compute_hash_value_timer);
121
29.6k
        RETURN_IF_ERROR(sink_info.partitioner->do_partitioning(state, in_block));
122
29.6k
    }
123
29.6k
    {
124
29.6k
        SCOPED_TIMER(profile.distribute_timer);
125
29.6k
        RETURN_IF_ERROR(_split_rows(state, sink_info.partitioner->get_channel_ids(), in_block,
126
29.6k
                                    *sink_info.channel_id, sink_info.local_state,
127
29.6k
                                    sink_info.shuffle_idx_to_instance_idx));
128
29.6k
    }
129
130
29.6k
    sink_info.local_state->_memory_used_counter->set(
131
29.6k
            sink_info.local_state->_shared_state->mem_usage);
132
29.6k
    return Status::OK();
133
29.6k
}
134
135
143k
void ShuffleExchanger::close(SourceInfo&& source_info) {
136
143k
    PartitionedBlock partitioned_block;
137
143k
    bool eos;
138
143k
    Block block;
139
143k
    _data_queue[source_info.channel_id].set_eos();
140
143k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
141
143k
                         source_info.channel_id)) {
142
        // do nothing
143
8
    }
144
143k
}
145
146
Status ShuffleExchanger::get_block(RuntimeState* state, Block* block, bool* eos, Profile&& profile,
147
186k
                                   SourceInfo&& source_info) {
148
186k
    PartitionedBlock partitioned_block;
149
186k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
150
186k
                      source_info.channel_id)) {
151
53.1k
        SCOPED_TIMER(profile.copy_data_timer);
152
53.1k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
153
53.1k
                block, partitioned_block.first->_data_block);
154
53.1k
        auto& mutable_block = scoped_mutable_block.mutable_block();
155
85.2k
        do {
156
85.2k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
157
85.2k
                                       partitioned_block.second.offset_start;
158
85.2k
            auto block_wrapper = partitioned_block.first;
159
85.2k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
160
85.2k
                                                   offset_start + partitioned_block.second.length));
161
85.2k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
162
85.2k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
163
81.6k
                               source_info.channel_id));
164
53.1k
    }
165
186k
    return Status::OK();
166
186k
}
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
29.5k
                                     std::map<int, int>* shuffle_idx_to_instance_idx) {
172
29.5k
    if (local_state == nullptr) {
173
0
        return _split_rows(state, channel_ids, block, channel_id);
174
0
    }
175
29.5k
    const auto rows = cast_set<int32_t>(block->rows());
176
29.5k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
177
29.5k
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
178
29.5k
    {
179
29.5k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
180
65.6M
        for (int32_t i = 0; i < rows; ++i) {
181
65.6M
            partition_rows_histogram[channel_ids[i]]++;
182
65.6M
        }
183
235k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
184
205k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
185
205k
        }
186
64.9M
        for (int32_t i = rows - 1; i >= 0; --i) {
187
64.9M
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
188
64.9M
            partition_rows_histogram[channel_ids[i]]--;
189
64.9M
        }
190
29.5k
    }
191
192
29.5k
    Block data_block;
193
29.5k
    std::shared_ptr<BlockWrapper> new_block_wrapper;
194
29.5k
    if (!_free_blocks.try_dequeue(data_block)) {
195
15.2k
        data_block = block->clone_empty();
196
15.2k
    }
197
29.5k
    data_block.swap(*block);
198
29.5k
    new_block_wrapper =
199
29.5k
            BlockWrapper::create_shared(std::move(data_block), local_state->_shared_state, -1);
200
29.5k
    if (new_block_wrapper->_data_block.empty()) {
201
0
        return Status::OK();
202
0
    }
203
    /**
204
     * Data are hash-shuffled and distributed to all instances of
205
     * all BEs. So we need a shuffleId-To-InstanceId mapping.
206
     * For example, row 1 get a hash value 1 which means we should distribute to instance 1 on
207
     * BE 1 and row 2 get a hash value 2 which means we should distribute to instance 1 on BE 3.
208
     */
209
29.5k
    DCHECK(shuffle_idx_to_instance_idx && !shuffle_idx_to_instance_idx->empty());
210
29.5k
    const auto& map = *shuffle_idx_to_instance_idx;
211
29.5k
    int32_t enqueue_rows = 0;
212
205k
    for (const auto& it : map) {
213
205k
        DCHECK(it.second >= 0 && it.second < _num_partitions)
214
3
                << it.first << " : " << it.second << " " << _num_partitions;
215
205k
        uint32_t start = partition_rows_histogram[it.first];
216
205k
        uint32_t size = partition_rows_histogram[it.first + 1] - start;
217
205k
        if (size > 0) {
218
85.3k
            enqueue_rows += size;
219
85.3k
            _enqueue_data_and_set_ready(
220
85.3k
                    it.second, local_state,
221
85.3k
                    {new_block_wrapper,
222
85.3k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
223
85.3k
        }
224
205k
    }
225
29.5k
    if (enqueue_rows != rows) [[unlikely]] {
226
1
        fmt::memory_buffer debug_string_buffer;
227
1
        fmt::format_to(debug_string_buffer, "Type: {}, Local Exchange Id: {}, Shuffled Map: ",
228
1
                       get_exchange_type_name(get_type()), local_state->parent()->node_id());
229
3
        for (const auto& it : map) {
230
3
            fmt::format_to(debug_string_buffer, "[{}:{}], ", it.first, it.second);
231
3
        }
232
1
        return Status::InternalError(
233
1
                "Rows mismatched! Data may be lost. [Expected enqueue rows={}, Real enqueue "
234
1
                "rows={}, Detail: {}]",
235
1
                rows, enqueue_rows, fmt::to_string(debug_string_buffer));
236
1
    }
237
238
29.5k
    return Status::OK();
239
29.5k
}
240
241
Status ShuffleExchanger::_split_rows(RuntimeState* state, const std::vector<uint32_t>& channel_ids,
242
0
                                     Block* block, int channel_id) {
243
0
    const auto rows = cast_set<int32_t>(block->rows());
244
0
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
245
0
    auto& partition_rows_histogram = _partition_rows_histogram[channel_id];
246
0
    {
247
0
        partition_rows_histogram.assign(_num_partitions + 1, 0);
248
0
        for (int32_t i = 0; i < rows; ++i) {
249
0
            partition_rows_histogram[channel_ids[i]]++;
250
0
        }
251
0
        for (int32_t i = 1; i <= _num_partitions; ++i) {
252
0
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
253
0
        }
254
0
        for (int32_t i = rows - 1; i >= 0; --i) {
255
0
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
256
0
            partition_rows_histogram[channel_ids[i]]--;
257
0
        }
258
0
    }
259
260
0
    Block data_block;
261
0
    std::shared_ptr<BlockWrapper> new_block_wrapper;
262
0
    if (!_free_blocks.try_dequeue(data_block)) {
263
0
        data_block = block->clone_empty();
264
0
    }
265
0
    data_block.swap(*block);
266
0
    new_block_wrapper = BlockWrapper::create_shared(std::move(data_block), nullptr, -1);
267
0
    if (new_block_wrapper->_data_block.empty()) {
268
0
        return Status::OK();
269
0
    }
270
0
    for (int i = 0; i < _num_partitions; i++) {
271
0
        uint32_t start = partition_rows_histogram[i];
272
0
        uint32_t size = partition_rows_histogram[i + 1] - start;
273
0
        if (size > 0) {
274
0
            _enqueue_data_and_set_ready(
275
0
                    i, {new_block_wrapper,
276
0
                        {.row_idxs = row_idx, .offset_start = start, .length = size}});
277
0
        }
278
0
    }
279
280
0
    return Status::OK();
281
0
}
282
283
Status PassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
284
287k
                                  SinkInfo& sink_info) {
285
287k
    if (in_block->empty()) {
286
93.1k
        return Status::OK();
287
93.1k
    }
288
194k
    Block new_block;
289
194k
    if (!_free_blocks.try_dequeue(new_block)) {
290
84.1k
        new_block = {in_block->clone_empty()};
291
84.1k
    }
292
194k
    new_block.swap(*in_block);
293
194k
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
294
194k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
295
194k
            std::move(new_block),
296
194k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, channel_id);
297
298
194k
    _enqueue_data_and_set_ready(channel_id, sink_info.local_state, std::move(wrapper));
299
300
194k
    sink_info.local_state->_memory_used_counter->set(
301
194k
            sink_info.local_state->_shared_state->mem_usage);
302
303
194k
    return Status::OK();
304
287k
}
305
306
589k
void PassthroughExchanger::close(SourceInfo&& source_info) {
307
589k
    Block next_block;
308
589k
    BlockWrapperSPtr wrapper;
309
589k
    bool eos;
310
589k
    _data_queue[source_info.channel_id].set_eos();
311
591k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
312
591k
                         source_info.channel_id)) {
313
        // do nothing
314
2.04k
    }
315
589k
}
316
317
12.8k
void PassToOneExchanger::close(SourceInfo&& source_info) {
318
12.8k
    Block next_block;
319
12.8k
    BlockWrapperSPtr wrapper;
320
12.8k
    bool eos;
321
12.8k
    _data_queue[source_info.channel_id].set_eos();
322
12.8k
    while (_dequeue_data(source_info.local_state, wrapper, &eos, &next_block,
323
12.8k
                         source_info.channel_id)) {
324
        // do nothing
325
0
    }
326
12.8k
}
327
328
Status PassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
329
896k
                                       Profile&& profile, SourceInfo&& source_info) {
330
896k
    BlockWrapperSPtr next_block;
331
896k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
332
896k
    return Status::OK();
333
896k
}
334
335
Status PassToOneExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
336
4.88k
                                SinkInfo& sink_info) {
337
4.88k
    if (in_block->empty()) {
338
1.76k
        return Status::OK();
339
1.76k
    }
340
3.12k
    Block new_block;
341
3.12k
    if (!_free_blocks.try_dequeue(new_block)) {
342
1.93k
        new_block = {in_block->clone_empty()};
343
1.93k
    }
344
3.12k
    new_block.swap(*in_block);
345
346
3.12k
    BlockWrapperSPtr wrapper = BlockWrapper::create_shared(
347
3.12k
            std::move(new_block),
348
3.12k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, 0);
349
3.12k
    _enqueue_data_and_set_ready(0, sink_info.local_state, std::move(wrapper));
350
351
3.12k
    sink_info.local_state->_memory_used_counter->set(
352
3.12k
            sink_info.local_state->_shared_state->mem_usage);
353
354
3.12k
    return Status::OK();
355
4.88k
}
356
357
Status PassToOneExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
358
5.61k
                                     Profile&& profile, SourceInfo&& source_info) {
359
5.61k
    if (source_info.channel_id != 0) {
360
3
        *eos = true;
361
3
        return Status::OK();
362
3
    }
363
5.60k
    BlockWrapperSPtr next_block;
364
5.60k
    _dequeue_data(source_info.local_state, next_block, eos, block, source_info.channel_id);
365
5.60k
    return Status::OK();
366
5.61k
}
367
368
127k
void ExchangerBase::finalize() {
369
127k
    DCHECK(_running_source_operators == 0);
370
127k
    Block block;
371
228k
    while (_free_blocks.try_dequeue(block)) {
372
        // do nothing
373
101k
    }
374
127k
}
375
376
Status BroadcastExchanger::sink(RuntimeState* state, Block* in_block, bool eos, Profile&& profile,
377
3.82k
                                SinkInfo& sink_info) {
378
3.82k
    if (in_block->empty()) {
379
1.37k
        return Status::OK();
380
1.37k
    }
381
2.45k
    Block new_block;
382
2.45k
    if (!_free_blocks.try_dequeue(new_block)) {
383
1.73k
        new_block = {in_block->clone_empty()};
384
1.73k
    }
385
2.45k
    new_block.swap(*in_block);
386
2.45k
    auto wrapper = BlockWrapper::create_shared(
387
2.45k
            std::move(new_block),
388
2.45k
            sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1);
389
21.4k
    for (int i = 0; i < _num_partitions; i++) {
390
18.9k
        _enqueue_data_and_set_ready(
391
18.9k
                i, sink_info.local_state,
392
18.9k
                {wrapper, {.offset_start = 0, .length = wrapper->_data_block.rows()}});
393
18.9k
    }
394
395
2.45k
    return Status::OK();
396
3.82k
}
397
398
8.91k
void BroadcastExchanger::close(SourceInfo&& source_info) {
399
8.91k
    BroadcastBlock partitioned_block;
400
8.91k
    bool eos;
401
8.91k
    Block block;
402
8.91k
    _data_queue[source_info.channel_id].set_eos();
403
8.91k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
404
8.91k
                         source_info.channel_id)) {
405
        // do nothing
406
0
    }
407
8.91k
}
408
409
Status BroadcastExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
410
32.1k
                                     Profile&& profile, SourceInfo&& source_info) {
411
32.1k
    BroadcastBlock partitioned_block;
412
413
32.1k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
414
32.1k
                      source_info.channel_id)) {
415
18.9k
        SCOPED_TIMER(profile.copy_data_timer);
416
18.9k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
417
18.9k
                block, partitioned_block.first->_data_block);
418
18.9k
        auto& mutable_block = scoped_mutable_block.mutable_block();
419
18.9k
        auto block_wrapper = partitioned_block.first;
420
18.9k
        RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block,
421
18.9k
                                               partitioned_block.second.offset_start,
422
18.9k
                                               partitioned_block.second.length));
423
18.9k
    }
424
425
32.1k
    return Status::OK();
426
32.1k
}
427
428
Status AdaptivePassthroughExchanger::_passthrough_sink(RuntimeState* state, Block* in_block,
429
908
                                                       SinkInfo& sink_info) {
430
908
    Block new_block;
431
908
    if (!_free_blocks.try_dequeue(new_block)) {
432
311
        new_block = {in_block->clone_empty()};
433
311
    }
434
908
    new_block.swap(*in_block);
435
908
    auto channel_id = ((*sink_info.channel_id)++) % _num_partitions;
436
908
    _enqueue_data_and_set_ready(
437
908
            channel_id, sink_info.local_state,
438
908
            {BlockWrapper::create_shared(
439
908
                     std::move(new_block),
440
908
                     sink_info.local_state ? sink_info.local_state->_shared_state : nullptr, -1),
441
908
             {.row_idxs = nullptr, .offset_start = 0, .length = 0}});
442
443
908
    sink_info.local_state->_memory_used_counter->set(
444
908
            sink_info.local_state->_shared_state->mem_usage);
445
908
    return Status::OK();
446
908
}
447
448
Status AdaptivePassthroughExchanger::_shuffle_sink(RuntimeState* state, Block* block,
449
2.47k
                                                   SinkInfo& sink_info) {
450
2.47k
    std::vector<uint32_t> channel_ids;
451
2.47k
    const auto num_rows = block->rows();
452
2.47k
    channel_ids.resize(num_rows, 0);
453
2.47k
    if (num_rows <= _num_partitions) {
454
1.79k
        std::iota(channel_ids.begin(), channel_ids.end(), 0);
455
1.79k
    } else {
456
681
        size_t i = 0;
457
30.8k
        for (; i < num_rows - _num_partitions; i += _num_partitions) {
458
30.1k
            std::iota(channel_ids.begin() + i, channel_ids.begin() + i + _num_partitions, 0);
459
30.1k
        }
460
681
        if (i < num_rows - 1) {
461
479
            std::iota(channel_ids.begin() + i, channel_ids.end(), 0);
462
479
        }
463
681
    }
464
465
2.47k
    sink_info.local_state->_memory_used_counter->set(
466
2.47k
            sink_info.local_state->_shared_state->mem_usage);
467
2.47k
    RETURN_IF_ERROR(_split_rows(state, channel_ids, block, sink_info));
468
2.47k
    return Status::OK();
469
2.47k
}
470
471
Status AdaptivePassthroughExchanger::_split_rows(RuntimeState* state,
472
                                                 const std::vector<uint32_t>& channel_ids,
473
2.47k
                                                 Block* block, SinkInfo& sink_info) {
474
2.47k
    const auto rows = cast_set<int32_t>(block->rows());
475
2.47k
    auto row_idx = std::make_shared<PODArray<uint32_t>>(rows);
476
2.47k
    auto& partition_rows_histogram = _partition_rows_histogram[sink_info.ins_idx];
477
2.47k
    {
478
2.47k
        partition_rows_histogram.assign(_num_partitions + 1, 0);
479
107k
        for (int32_t i = 0; i < rows; ++i) {
480
105k
            partition_rows_histogram[channel_ids[i]]++;
481
105k
        }
482
15.6k
        for (int32_t i = 1; i <= _num_partitions; ++i) {
483
13.1k
            partition_rows_histogram[i] += partition_rows_histogram[i - 1];
484
13.1k
        }
485
486
107k
        for (int32_t i = rows - 1; i >= 0; --i) {
487
105k
            (*row_idx)[partition_rows_histogram[channel_ids[i]] - 1] = i;
488
105k
            partition_rows_histogram[channel_ids[i]]--;
489
105k
        }
490
2.47k
    }
491
2.47k
    Block data_block;
492
2.47k
    if (!_free_blocks.try_dequeue(data_block)) {
493
2.22k
        data_block = block->clone_empty();
494
2.22k
    }
495
2.47k
    data_block.swap(*block);
496
2.47k
    std::shared_ptr<BlockWrapper> new_block_wrapper = BlockWrapper::create_shared(
497
2.47k
            std::move(data_block), sink_info.local_state->_shared_state, sink_info.ins_idx);
498
2.47k
    if (new_block_wrapper->_data_block.empty()) {
499
0
        return Status::OK();
500
0
    }
501
15.6k
    for (int32_t i = 0; i < _num_partitions; i++) {
502
13.1k
        const uint32_t start = partition_rows_histogram[i];
503
13.1k
        const uint32_t size = partition_rows_histogram[i + 1] - start;
504
13.1k
        if (size > 0) {
505
7.31k
            _enqueue_data_and_set_ready(
506
7.31k
                    i, sink_info.local_state,
507
7.31k
                    {new_block_wrapper,
508
7.31k
                     {.row_idxs = row_idx, .offset_start = start, .length = size}});
509
7.31k
        }
510
13.1k
    }
511
2.47k
    return Status::OK();
512
2.47k
}
513
514
Status AdaptivePassthroughExchanger::sink(RuntimeState* state, Block* in_block, bool eos,
515
6.74k
                                          Profile&& profile, SinkInfo& sink_info) {
516
6.74k
    if (in_block->empty()) {
517
3.36k
        return Status::OK();
518
3.36k
    }
519
3.38k
    if (_is_pass_through) {
520
908
        return _passthrough_sink(state, in_block, sink_info);
521
2.47k
    } else {
522
2.47k
        if (++_total_block >= _num_partitions) {
523
384
            _is_pass_through = true;
524
384
        }
525
2.47k
        return _shuffle_sink(state, in_block, sink_info);
526
2.47k
    }
527
3.38k
}
528
529
Status AdaptivePassthroughExchanger::get_block(RuntimeState* state, Block* block, bool* eos,
530
7.61k
                                               Profile&& profile, SourceInfo&& source_info) {
531
7.61k
    if (!_tmp_block[source_info.channel_id].empty()) {
532
174
        *block = std::move(_tmp_block[source_info.channel_id]);
533
174
        *eos = _tmp_eos[source_info.channel_id];
534
174
        _tmp_block[source_info.channel_id] = {};
535
174
        return Status::OK();
536
174
    }
537
7.44k
    PartitionedBlock partitioned_block;
538
7.44k
    if (_dequeue_data(source_info.local_state, partitioned_block, eos, block,
539
7.44k
                      source_info.channel_id)) {
540
4.38k
        SCOPED_TIMER(profile.copy_data_timer);
541
4.38k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
542
4.38k
                block, partitioned_block.first->_data_block);
543
4.38k
        auto& mutable_block = scoped_mutable_block.mutable_block();
544
8.21k
        do {
545
8.21k
            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
904
                if (mutable_block.rows() > 0) {
548
174
                    _tmp_block[source_info.channel_id] =
549
174
                            std::move(partitioned_block.first->_data_block);
550
174
                    _tmp_eos[source_info.channel_id] = *eos;
551
174
                    *eos = false;
552
730
                } else {
553
730
                    scoped_mutable_block.restore();
554
730
                    *block = std::move(partitioned_block.first->_data_block);
555
730
                }
556
904
                break;
557
904
            }
558
7.30k
            const auto* offset_start = partitioned_block.second.row_idxs->data() +
559
7.30k
                                       partitioned_block.second.offset_start;
560
7.30k
            auto block_wrapper = partitioned_block.first;
561
7.30k
            RETURN_IF_ERROR(mutable_block.add_rows(&block_wrapper->_data_block, offset_start,
562
7.30k
                                                   offset_start + partitioned_block.second.length));
563
7.30k
        } while (mutable_block.rows() < state->batch_size() && !*eos &&
564
7.30k
                 _dequeue_data(source_info.local_state, partitioned_block, eos, block,
565
7.30k
                               source_info.channel_id));
566
4.38k
    }
567
7.44k
    return Status::OK();
568
7.44k
}
569
570
4.66k
void AdaptivePassthroughExchanger::close(SourceInfo&& source_info) {
571
4.66k
    PartitionedBlock partitioned_block;
572
4.66k
    bool eos;
573
4.66k
    Block block;
574
4.66k
    _data_queue[source_info.channel_id].set_eos();
575
4.66k
    while (_dequeue_data(source_info.local_state, partitioned_block, &eos, &block,
576
4.66k
                         source_info.channel_id)) {
577
        // do nothing
578
3
    }
579
4.66k
}
580
581
} // namespace doris