Coverage Report

Created: 2026-07-25 16:07

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