Coverage Report

Created: 2026-08-07 05:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/pipeline/dependency.h
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
#pragma once
19
20
#ifdef __APPLE__
21
#include <netinet/in.h>
22
#include <sys/_types/_u_int.h>
23
#endif
24
25
#include <gen_cpp/Partitions_types.h>
26
#include <gen_cpp/internal_service.pb.h>
27
#include <sqltypes.h>
28
29
#include <atomic>
30
#include <condition_variable>
31
#include <functional>
32
#include <list>
33
#include <memory>
34
#include <mutex>
35
#include <queue>
36
#include <set>
37
#include <thread>
38
#include <utility>
39
40
#include "common/cast_set.h"
41
#include "common/config.h"
42
#include "common/exception.h"
43
#include "common/factory_creator.h"
44
#include "common/logging.h"
45
#include "common/thread_safety_annotations.h"
46
#include "core/arena.h"
47
#include "core/block/block.h"
48
#include "core/types.h"
49
#include "exec/common/join_op_utils.h"
50
#include "exec/operator/data_queue.h"
51
#include "exec/sort/partition_sorter.h"
52
#include "exec/sort/sorter.h"
53
#include "exec/spill/spill_file.h"
54
#include "exprs/vexpr_fwd.h"
55
#include "runtime/runtime_profile_counter_names.h"
56
#include "util/stack_util.h"
57
#include "util/stopwatch.hpp"
58
59
namespace doris {
60
class AggFnEvaluator;
61
class VSlotRef;
62
// Heavy hash-table variant machinery (exec/common/*_utils.h) is referenced
63
// through pointers only; keep it out of this header's parse cost.
64
struct AggregatedDataVariants;
65
struct AggregateDataContainer;
66
struct BucketedAggDataVariants;
67
struct JoinDataVariants;
68
struct SetDataVariants;
69
using AggregateDataPtr = char*;
70
} // namespace doris
71
72
namespace doris {
73
class Dependency;
74
class PipelineTask;
75
struct BasicSharedState;
76
using DependencySPtr = std::shared_ptr<Dependency>;
77
class LocalExchangeSourceLocalState;
78
79
static constexpr auto SLOW_DEPENDENCY_THRESHOLD = 60 * 1000L * 1000L * 1000L;
80
static constexpr auto TIME_UNIT_DEPENDENCY_LOG = 30 * 1000L * 1000L * 1000L;
81
static_assert(TIME_UNIT_DEPENDENCY_LOG < SLOW_DEPENDENCY_THRESHOLD);
82
83
struct BasicSharedState {
84
    ENABLE_FACTORY_CREATOR(BasicSharedState)
85
86
    template <class TARGET>
87
2.63M
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
2.63M
        return reinterpret_cast<TARGET*>(this);
92
2.63M
    }
_ZN5doris16BasicSharedState4castINS_19HashJoinSharedStateEEEPT_v
Line
Count
Source
87
185k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
185k
        return reinterpret_cast<TARGET*>(this);
92
185k
    }
_ZN5doris16BasicSharedState4castINS_30PartitionedHashJoinSharedStateEEEPT_v
Line
Count
Source
87
3
    TARGET* cast() {
88
3
        DCHECK(dynamic_cast<TARGET*>(this))
89
0
                << " Mismatch type! Current type is " << typeid(*this).name()
90
0
                << " and expect type is" << typeid(TARGET).name();
91
3
        return reinterpret_cast<TARGET*>(this);
92
3
    }
_ZN5doris16BasicSharedState4castINS_15SortSharedStateEEEPT_v
Line
Count
Source
87
533k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
533k
        return reinterpret_cast<TARGET*>(this);
92
533k
    }
_ZN5doris16BasicSharedState4castINS_20SpillSortSharedStateEEEPT_v
Line
Count
Source
87
51
    TARGET* cast() {
88
51
        DCHECK(dynamic_cast<TARGET*>(this))
89
0
                << " Mismatch type! Current type is " << typeid(*this).name()
90
0
                << " and expect type is" << typeid(TARGET).name();
91
51
        return reinterpret_cast<TARGET*>(this);
92
51
    }
_ZN5doris16BasicSharedState4castINS_25NestedLoopJoinSharedStateEEEPT_v
Line
Count
Source
87
18.5k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
18.5k
        return reinterpret_cast<TARGET*>(this);
92
18.5k
    }
_ZN5doris16BasicSharedState4castINS_19AnalyticSharedStateEEEPT_v
Line
Count
Source
87
15.4k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
15.4k
        return reinterpret_cast<TARGET*>(this);
92
15.4k
    }
_ZN5doris16BasicSharedState4castINS_14AggSharedStateEEEPT_v
Line
Count
Source
87
317k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
317k
        return reinterpret_cast<TARGET*>(this);
92
317k
    }
_ZN5doris16BasicSharedState4castINS_22BucketedAggSharedStateEEEPT_v
Line
Count
Source
87
1.18k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
1.18k
        return reinterpret_cast<TARGET*>(this);
92
1.18k
    }
_ZN5doris16BasicSharedState4castINS_25PartitionedAggSharedStateEEEPT_v
Line
Count
Source
87
448
    TARGET* cast() {
88
448
        DCHECK(dynamic_cast<TARGET*>(this))
89
0
                << " Mismatch type! Current type is " << typeid(*this).name()
90
0
                << " and expect type is" << typeid(TARGET).name();
91
448
        return reinterpret_cast<TARGET*>(this);
92
448
    }
_ZN5doris16BasicSharedState4castINS_16UnionSharedStateEEEPT_v
Line
Count
Source
87
10.3k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
10.3k
        return reinterpret_cast<TARGET*>(this);
92
10.3k
    }
_ZN5doris16BasicSharedState4castINS_28PartitionSortNodeSharedStateEEEPT_v
Line
Count
Source
87
849
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
849
        return reinterpret_cast<TARGET*>(this);
92
849
    }
_ZN5doris16BasicSharedState4castINS_20MultiCastSharedStateEEEPT_v
Line
Count
Source
87
13.8k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
13.8k
        return reinterpret_cast<TARGET*>(this);
92
13.8k
    }
_ZN5doris16BasicSharedState4castINS_14SetSharedStateEEEPT_v
Line
Count
Source
87
18.0k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
18.0k
        return reinterpret_cast<TARGET*>(this);
92
18.0k
    }
_ZN5doris16BasicSharedState4castINS_24LocalExchangeSharedStateEEEPT_v
Line
Count
Source
87
1.01M
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
1.01M
        return reinterpret_cast<TARGET*>(this);
92
1.01M
    }
_ZN5doris16BasicSharedState4castIS0_EEPT_v
Line
Count
Source
87
501k
    TARGET* cast() {
88
18.4E
        DCHECK(dynamic_cast<TARGET*>(this))
89
18.4E
                << " Mismatch type! Current type is " << typeid(*this).name()
90
18.4E
                << " and expect type is" << typeid(TARGET).name();
91
501k
        return reinterpret_cast<TARGET*>(this);
92
501k
    }
_ZN5doris16BasicSharedState4castINS_20DataQueueSharedStateEEEPT_v
Line
Count
Source
87
51
    TARGET* cast() {
88
51
        DCHECK(dynamic_cast<TARGET*>(this))
89
0
                << " Mismatch type! Current type is " << typeid(*this).name()
90
0
                << " and expect type is" << typeid(TARGET).name();
91
51
        return reinterpret_cast<TARGET*>(this);
92
51
    }
_ZN5doris16BasicSharedState4castINS_17RecCTESharedStateEEEPT_v
Line
Count
Source
87
491
    TARGET* cast() {
88
491
        DCHECK(dynamic_cast<TARGET*>(this))
89
0
                << " Mismatch type! Current type is " << typeid(*this).name()
90
0
                << " and expect type is" << typeid(TARGET).name();
91
491
        return reinterpret_cast<TARGET*>(this);
92
491
    }
93
    template <class TARGET>
94
    const TARGET* cast() const {
95
        DCHECK(dynamic_cast<const TARGET*>(this))
96
                << " Mismatch type! Current type is " << typeid(*this).name()
97
                << " and expect type is" << typeid(TARGET).name();
98
        return reinterpret_cast<const TARGET*>(this);
99
    }
100
    std::vector<DependencySPtr> source_deps;
101
    std::vector<DependencySPtr> sink_deps;
102
    int id = 0;
103
    std::set<int> related_op_ids;
104
105
1.88M
    virtual ~BasicSharedState() = default;
106
107
    void create_source_dependencies(int num_sources, int operator_id, int node_id,
108
                                    const std::string& name);
109
    Dependency* create_source_dependency(int operator_id, int node_id, const std::string& name);
110
111
    Dependency* create_sink_dependency(int dest_id, int node_id, const std::string& name);
112
756k
    std::vector<DependencySPtr> get_dep_by_channel_id(int channel_id) {
113
756k
        DCHECK_LT(channel_id, source_deps.size());
114
756k
        return {source_deps[channel_id]};
115
756k
    }
116
};
117
118
class Dependency : public std::enable_shared_from_this<Dependency> {
119
public:
120
    ENABLE_FACTORY_CREATOR(Dependency);
121
    Dependency(int id, int node_id, std::string name, bool ready = false)
122
6.71M
            : _id(id), _node_id(node_id), _name(std::move(name)), _ready(ready) {}
123
6.74M
    virtual ~Dependency() = default;
124
125
0
    [[nodiscard]] int id() const { return _id; }
126
8.52M
    [[nodiscard]] virtual std::string name() const { return _name; }
127
301k
    BasicSharedState* shared_state() { return _shared_state; }
128
2.54M
    void set_shared_state(BasicSharedState* shared_state) { _shared_state = shared_state; }
129
    virtual std::string debug_string(int indentation_level = 0);
130
1.03G
    bool ready() const { return _ready; }
131
132
    // Start the watcher. We use it to count how long this dependency block the current pipeline task.
133
5.40M
    void start_watcher() { _watcher.start(); }
134
8.53M
    [[nodiscard]] int64_t watcher_elapse_time() { return _watcher.elapsed_time(); }
135
136
    // Which dependency current pipeline task is blocked by. `nullptr` if this dependency is ready.
137
    [[nodiscard]] Dependency* is_blocked_by(std::shared_ptr<PipelineTask> task = nullptr);
138
    // Notify downstream pipeline tasks this dependency is ready.
139
    void set_ready();
140
554k
    void set_ready_to_read(int channel_id = 0) {
141
554k
        DCHECK_LT(channel_id, _shared_state->source_deps.size()) << debug_string();
142
554k
        _shared_state->source_deps[channel_id]->set_ready();
143
554k
    }
144
1.24k
    void set_ready_to_write() {
145
1.24k
        DCHECK_EQ(_shared_state->sink_deps.size(), 1) << debug_string();
146
1.24k
        _shared_state->sink_deps.front()->set_ready();
147
1.24k
    }
148
149
    // Notify downstream pipeline tasks this dependency is blocked.
150
1.98M
    void block() {
151
1.98M
        if (_always_ready) {
152
328k
            return;
153
328k
        }
154
1.65M
        std::unique_lock<std::mutex> lc(_always_ready_lock);
155
1.65M
        if (_always_ready) {
156
4
            return;
157
4
        }
158
1.65M
        _ready = false;
159
1.65M
    }
160
161
4.51M
    void set_always_ready() {
162
4.51M
        if (_always_ready) {
163
1.92M
            return;
164
1.92M
        }
165
2.59M
        std::unique_lock<std::mutex> lc(_always_ready_lock);
166
2.59M
        if (_always_ready) {
167
1
            return;
168
1
        }
169
2.59M
        _always_ready = true;
170
2.59M
        set_ready();
171
2.59M
    }
172
173
protected:
174
    void _add_block_task(std::shared_ptr<PipelineTask> task);
175
176
    const int _id;
177
    const int _node_id;
178
    const std::string _name;
179
    std::atomic<bool> _ready;
180
181
    BasicSharedState* _shared_state = nullptr;
182
    MonotonicStopWatch _watcher;
183
184
    std::mutex _task_lock;
185
    std::vector<std::weak_ptr<PipelineTask>> _blocked_task;
186
187
    // If `_always_ready` is true, `block()` will never block tasks.
188
    std::atomic<bool> _always_ready = false;
189
    std::mutex _always_ready_lock;
190
};
191
192
struct FakeSharedState final : public BasicSharedState {
193
    ENABLE_FACTORY_CREATOR(FakeSharedState)
194
};
195
196
class CountedFinishDependency final : public Dependency {
197
public:
198
    using SharedState = FakeSharedState;
199
    CountedFinishDependency(int id, int node_id, std::string name)
200
147k
            : Dependency(id, node_id, std::move(name), true) {}
201
202
1.47k
    void add(uint32_t count = 1) {
203
1.47k
        std::unique_lock<std::mutex> l(_mtx);
204
1.47k
        if (!_counter) {
205
1.47k
            block();
206
1.47k
        }
207
1.47k
        _counter += count;
208
1.47k
    }
209
210
1.47k
    void sub() {
211
1.47k
        std::unique_lock<std::mutex> l(_mtx);
212
        // _counter is unsigned: a stray sub() when counter is already 0 would
213
        // underflow to UINT32_MAX and the dependency would never become ready,
214
        // hanging the query forever. Fail loudly instead.
215
1.47k
        if (_counter == 0) [[unlikely]] {
216
2
            throw Exception(ErrorCode::INTERNAL_ERROR,
217
2
                            "CountedFinishDependency::sub() underflow on {}", debug_string());
218
2
        }
219
1.47k
        _counter--;
220
1.47k
        if (!_counter) {
221
1.46k
            set_ready();
222
1.46k
        }
223
1.47k
    }
224
225
    std::string debug_string(int indentation_level = 0) override;
226
227
private:
228
    std::mutex _mtx;
229
    uint32_t _counter = 0;
230
};
231
232
struct RuntimeFilterTimerQueue;
233
class RuntimeFilterTimer {
234
public:
235
    RuntimeFilterTimer(int64_t registration_time, int32_t wait_time_ms,
236
                       std::shared_ptr<Dependency> parent, bool force_wait_timeout = false)
237
17.5k
            : _parent(std::move(parent)),
238
17.5k
              _registration_time(registration_time),
239
17.5k
              _wait_time_ms(wait_time_ms),
240
17.5k
              _force_wait_timeout(force_wait_timeout) {}
241
242
    // Called by runtime filter producer.
243
    void call_ready();
244
245
    // Called by RuntimeFilterTimerQueue which is responsible for checking if this rf is timeout.
246
    void call_timeout();
247
248
623k
    int64_t registration_time() const { return _registration_time; }
249
623k
    int32_t wait_time_ms() const { return _wait_time_ms; }
250
251
    void set_local_runtime_filter_dependencies(
252
5.59k
            const std::vector<std::shared_ptr<Dependency>>& deps) {
253
5.59k
        _local_runtime_filter_dependencies = deps;
254
5.59k
    }
255
256
    bool should_be_check_timeout();
257
258
639k
    bool force_wait_timeout() { return _force_wait_timeout; }
259
260
private:
261
    friend struct RuntimeFilterTimerQueue;
262
    std::shared_ptr<Dependency> _parent = nullptr;
263
    std::vector<std::shared_ptr<Dependency>> _local_runtime_filter_dependencies;
264
    std::mutex _lock;
265
    int64_t _registration_time;
266
    const int32_t _wait_time_ms;
267
    // true only for group_commit_scan_operator
268
    bool _force_wait_timeout;
269
};
270
271
struct RuntimeFilterTimerQueue {
272
    constexpr static int64_t interval = 10;
273
9
    void run() { _thread.detach(); }
274
    void start();
275
276
3
    void stop() {
277
3
        _stop = true;
278
3
        cv.notify_all();
279
3
        wait_for_shutdown();
280
3
    }
281
282
3
    void wait_for_shutdown() const {
283
6
        while (!_shutdown) {
284
3
            std::this_thread::sleep_for(std::chrono::milliseconds(interval));
285
3
        }
286
3
    }
287
288
3
    ~RuntimeFilterTimerQueue() = default;
289
9
    RuntimeFilterTimerQueue() { _thread = std::thread(&RuntimeFilterTimerQueue::start, this); }
290
9.23k
    void push_filter_timer(std::vector<std::shared_ptr<RuntimeFilterTimer>>&& filter) {
291
9.23k
        std::unique_lock<std::mutex> lc(_que_lock);
292
9.23k
        _que.insert(_que.end(), filter.begin(), filter.end());
293
9.23k
        cv.notify_all();
294
9.23k
    }
295
296
    std::thread _thread;
297
    std::condition_variable cv;
298
    std::mutex cv_m;
299
    std::mutex _que_lock;
300
    std::atomic_bool _stop = false;
301
    std::atomic_bool _shutdown = false;
302
    std::list<std::shared_ptr<RuntimeFilterTimer>> _que;
303
};
304
305
struct AggSharedState : public BasicSharedState {
306
    ENABLE_FACTORY_CREATOR(AggSharedState)
307
public:
308
    // Defined in dependency.cpp: the bodies touch AggregatedDataVariants'
309
    // full variant machinery, which every includer would otherwise
310
    // instantiate at parse time.
311
    AggSharedState();
312
    ~AggSharedState() override;
313
314
    Status reset_hash_table();
315
316
    bool do_limit_filter(Block* block, size_t num_rows, const std::vector<int>* key_locs = nullptr);
317
    void build_limit_heap(size_t hash_table_size);
318
319
    // We should call this function only at 1st phase.
320
    // 1st phase: is_merge=true, only have one SlotRef.
321
    // 2nd phase: is_merge=false, maybe have multiple exprs.
322
    static int get_slot_column_id(const AggFnEvaluator* evaluator);
323
324
    std::unique_ptr<AggregatedDataVariants> agg_data;
325
    std::unique_ptr<AggregateDataContainer> aggregate_data_container;
326
    std::vector<AggFnEvaluator*> aggregate_evaluators;
327
    // group by k1,k2
328
    VExprContextSPtrs probe_expr_ctxs;
329
    size_t input_num_rows = 0;
330
    std::vector<AggregateDataPtr> values;
331
    /// The total size of the row from the aggregate functions.
332
    size_t total_size_of_aggregate_states = 0;
333
    size_t align_aggregate_states = 1;
334
    /// The offset to the n-th aggregate function in a row of aggregate functions.
335
    std::vector<size_t> offsets_of_aggregate_states;
336
    std::vector<size_t> make_nullable_keys;
337
338
    bool agg_data_created_without_key = false;
339
    bool enable_spill = false;
340
    bool reach_limit = false;
341
342
    bool use_simple_count = false;
343
    int64_t limit = -1;
344
    bool do_sort_limit = false;
345
    MutableColumns limit_columns;
346
    int limit_columns_min = -1;
347
    PaddedPODArray<uint8_t> need_computes;
348
    std::vector<uint8_t> cmp_res;
349
    std::vector<int> order_directions;
350
    std::vector<int> null_directions;
351
352
    struct HeapLimitCursor {
353
        HeapLimitCursor(int row_id, MutableColumns& limit_columns,
354
                        std::vector<int>& order_directions, std::vector<int>& null_directions)
355
28.0k
                : _row_id(row_id),
356
28.0k
                  _limit_columns(limit_columns),
357
28.0k
                  _order_directions(order_directions),
358
28.0k
                  _null_directions(null_directions) {}
359
360
        HeapLimitCursor(const HeapLimitCursor& other) = default;
361
362
        HeapLimitCursor(HeapLimitCursor&& other) noexcept
363
180k
                : _row_id(other._row_id),
364
180k
                  _limit_columns(other._limit_columns),
365
180k
                  _order_directions(other._order_directions),
366
180k
                  _null_directions(other._null_directions) {}
367
368
0
        HeapLimitCursor& operator=(const HeapLimitCursor& other) noexcept {
369
0
            _row_id = other._row_id;
370
0
            return *this;
371
0
        }
372
373
296k
        HeapLimitCursor& operator=(HeapLimitCursor&& other) noexcept {
374
296k
            _row_id = other._row_id;
375
296k
            return *this;
376
296k
        }
377
378
274k
        bool operator<(const HeapLimitCursor& rhs) const {
379
335k
            for (int i = 0; i < _limit_columns.size(); ++i) {
380
335k
                const auto& _limit_column = _limit_columns[i];
381
335k
                auto res = _limit_column->compare_at(_row_id, rhs._row_id, *_limit_column,
382
335k
                                                     _null_directions[i]) *
383
335k
                           _order_directions[i];
384
335k
                if (res < 0) {
385
133k
                    return true;
386
201k
                } else if (res > 0) {
387
146k
                    return false;
388
146k
                }
389
335k
            }
390
18.4E
            return false;
391
274k
        }
392
393
        int _row_id;
394
        MutableColumns& _limit_columns;
395
        std::vector<int>& _order_directions;
396
        std::vector<int>& _null_directions;
397
    };
398
399
    std::priority_queue<HeapLimitCursor> limit_heap;
400
401
    // Refresh the top limit heap with a new row
402
    void refresh_top_limit(size_t row_id, const ColumnRawPtrs& key_columns);
403
404
    Arena agg_arena_pool;
405
    Arena agg_profile_arena;
406
407
private:
408
    MutableColumns _get_keys_hash_table();
409
410
    void _close_with_serialized_key();
411
    void _close_without_key();
412
    void _destroy_agg_status(AggregateDataPtr data);
413
};
414
415
static constexpr int BUCKETED_AGG_NUM_BUCKETS = 256;
416
417
/// Shared state for BucketedAggSinkOperatorX / BucketedAggSourceOperatorX.
418
///
419
/// Each sink pipeline instance owns 256 per-bucket hash tables (two-level hash table
420
/// approach, inspired by ClickHouse). During sink, each row is routed to bucket
421
/// (hash >> 24) & 0xFF.
422
///
423
/// Source-side merge is pipelined with sink completion: as each sink instance finishes,
424
/// it unblocks all source dependencies. Source instances scan buckets and merge data
425
/// from finished sink instances into the merge target (the first sink to finish).
426
/// Each bucket has a CAS lock so only one source works on a bucket at a time.
427
/// After all sinks finish and all buckets are merged + output, one source handles
428
/// null key merge and the pipeline completes.
429
///
430
/// Thread safety model:
431
///  - Sink phase: each instance writes only to its own per_instance_data[task_idx]. No locking.
432
///  - Source phase: per-bucket CAS lock (merge_in_progress). Under the lock, a source
433
///    scans all finished sink instances and merges their bucket data into the merge
434
///    target's bucket. Already-merged entries are nulled out to prevent re-processing.
435
///    Output is only done when all sinks have finished and the bucket is fully merged.
436
struct BucketedAggSharedState : public BasicSharedState {
437
    ENABLE_FACTORY_CREATOR(BucketedAggSharedState)
438
public:
439
114
    BucketedAggSharedState() = default;
440
    ~BucketedAggSharedState() override; // defined in dependency.cpp (variant machinery)
441
442
    /// Per-instance data. One per sink pipeline instance.
443
    /// Each instance has 256 bucket hash tables + 1 shared arena.
444
    struct PerInstanceData {
445
        /// 256 per-bucket hash tables. Each bucket has its own BucketedAggDataVariants.
446
        /// Uses PHHashMap<StringRef> for string keys instead of StringHashMap.
447
        std::vector<std::unique_ptr<BucketedAggDataVariants>> bucket_agg_data;
448
        std::unique_ptr<Arena> arena;
449
450
        PerInstanceData(); // defined in dependency.cpp (variant machinery)
451
    };
452
453
    /// Per-bucket merge state for pipelined source-side processing.
454
    struct BucketMergeState {
455
        /// CAS lock: only one source instance can merge/output this bucket at a time.
456
        std::atomic<bool> merge_in_progress {false};
457
        /// Set to true once the bucket is fully merged and all rows have been output.
458
        std::atomic<bool> output_done {false};
459
        /// Tracks which sink instances have been merged into the merge target
460
        /// for this bucket. Accessed only under merge_in_progress CAS lock.
461
        /// Element i is true when instance i's data for this bucket has been merged.
462
        /// Sized to num_sink_instances in init_instances().
463
        std::vector<bool> merged_instances;
464
    };
465
466
    std::vector<PerInstanceData> per_instance_data;
467
    int num_sink_instances = 0;
468
469
    /// Tracks how many sinks have finished. Incremented by each sink on EOS.
470
    std::atomic<int> num_sinks_finished = 0;
471
472
    /// Per-sink completion flags. Set to true when each sink instance finishes.
473
    /// Source instances read these to know which sinks' data is safe to merge.
474
    std::unique_ptr<std::atomic<bool>[]> sink_finished;
475
476
    /// Index of the first sink instance to finish. Its bucket hash tables serve
477
    /// as the merge target — all other sinks' data is merged into it.
478
    /// Initialized to -1; the first sink to finish CAS-sets it to its instance idx.
479
    std::atomic<int> merge_target_instance = -1;
480
481
    /// Per-bucket merge state. Indexed by bucket id [0, 256).
482
    std::array<BucketMergeState, BUCKETED_AGG_NUM_BUCKETS> bucket_states;
483
484
    // Aggregate function metadata (shared, read-only after init).
485
    std::vector<AggFnEvaluator*> aggregate_evaluators;
486
    VExprContextSPtrs probe_expr_ctxs;
487
    size_t total_size_of_aggregate_states = 0;
488
    size_t align_aggregate_states = 1;
489
    std::vector<size_t> offsets_of_aggregate_states;
490
    std::vector<size_t> make_nullable_keys;
491
492
    std::atomic<size_t> input_num_rows {0};
493
494
    /// When true, the aggregate has exactly one COUNT(*) function with no args.
495
    /// In this case, mapped values in the hash table store a UInt64 counter
496
    /// directly (reinterpret_cast<AggregateDataPtr>) instead of a pointer to
497
    /// allocated aggregate state. This eliminates create/merge/destroy overhead.
498
    bool use_simple_count = false;
499
500
    // ---- Source-side fields ----
501
502
    // Null key handling: null keys are stored separately (not in any bucket).
503
    // After all buckets are processed, one source instance merges and outputs
504
    // all null key data. This atomic ensures exactly one source instance does it.
505
    std::atomic<bool> null_key_output_claimed {false};
506
507
    /// Monotonically increasing counter bumped on every state change (bucket lock
508
    /// release, sink finish). Used by source instances to detect missed wakeups:
509
    /// if the generation changed between scan start and post-block() re-check,
510
    /// something happened and the source should unblock immediately.
511
    std::atomic<uint64_t> state_generation {0};
512
513
    /// Initialize per-instance data and optionally run a metadata init callback.
514
    /// The callback runs exactly once (under std::call_once), must return Status,
515
    /// and should populate shared metadata like probe_expr_ctxs, aggregate_evaluators, etc.
516
    /// All threads observe the same init status via _init_status.
517
    /// Once-per-query cold path; defined in dependency.cpp so the body (which
518
    /// materializes the per-bucket BucketedAggDataVariants storage) stays out
519
    /// of every includer's parse.
520
    Status init_instances(int num_instances, const std::function<Status()>& metadata_init);
521
522
private:
523
    std::once_flag _init_once;
524
    Status _init_status;
525
526
    void _close();
527
    void _close_one_agg_data(BucketedAggDataVariants& agg_data);
528
    void _destroy_agg_status(AggregateDataPtr data);
529
};
530
531
struct PartitionedAggSharedState : public BasicSharedState,
532
                                   public std::enable_shared_from_this<PartitionedAggSharedState> {
533
    ENABLE_FACTORY_CREATOR(PartitionedAggSharedState)
534
535
253
    PartitionedAggSharedState() = default;
536
253
    ~PartitionedAggSharedState() override { close(); }
537
538
    void close();
539
540
    AggSharedState* _in_mem_shared_state = nullptr;
541
    std::shared_ptr<BasicSharedState> _in_mem_shared_state_sptr;
542
543
    // partition count is no longer stored in shared state; operators maintain their own
544
    std::atomic<bool> _is_spilled = false;
545
    // This state is shared by the partitioned agg sink and source pipelines. Spill files left
546
    // here are owned by the shared state until the source moves them into its local queue, so the
547
    // cleanup must be tied to the shared state's lifetime and must be idempotent.
548
    std::atomic_bool is_closed = false;
549
    std::deque<SpillFileSPtr> _spill_partitions;
550
};
551
552
struct SortSharedState : public BasicSharedState {
553
    ENABLE_FACTORY_CREATOR(SortSharedState)
554
public:
555
    std::shared_ptr<Sorter> sorter;
556
};
557
558
struct SpillSortSharedState : public BasicSharedState,
559
                              public std::enable_shared_from_this<SpillSortSharedState> {
560
    ENABLE_FACTORY_CREATOR(SpillSortSharedState)
561
562
31
    SpillSortSharedState() = default;
563
31
    ~SpillSortSharedState() override = default;
564
565
448
    void update_spill_block_batch_row_count(RuntimeState* state, const Block* block) {
566
448
        auto rows = block->rows();
567
448
        if (rows > 0 && 0 == avg_row_bytes) {
568
18
            avg_row_bytes = std::max((std::size_t)1, block->bytes() / rows);
569
18
            spill_block_batch_row_count =
570
18
                    (state->spill_buffer_size_bytes() + avg_row_bytes - 1) / avg_row_bytes;
571
18
            LOG(INFO) << "spill sort block batch row count: " << spill_block_batch_row_count;
572
18
        }
573
448
    }
574
575
    void close();
576
577
    SortSharedState* in_mem_shared_state = nullptr;
578
    bool enable_spill = false;
579
    bool is_spilled = false;
580
    int64_t limit = -1;
581
    int64_t offset = 0;
582
    std::atomic_bool is_closed = false;
583
    std::shared_ptr<BasicSharedState> in_mem_shared_state_sptr;
584
585
    std::deque<SpillFileSPtr> sorted_spill_groups;
586
    size_t avg_row_bytes = 0;
587
    size_t spill_block_batch_row_count;
588
};
589
590
struct UnionSharedState : public BasicSharedState {
591
    ENABLE_FACTORY_CREATOR(UnionSharedState)
592
593
public:
594
3.38k
    UnionSharedState(int child_count = 1) : data_queue(child_count), _child_count(child_count) {};
595
0
    int child_count() const { return _child_count; }
596
    DataQueue data_queue;
597
    const int _child_count;
598
};
599
600
struct DataQueueSharedState : public BasicSharedState {
601
    ENABLE_FACTORY_CREATOR(DataQueueSharedState)
602
public:
603
    DataQueue data_queue;
604
};
605
606
class MultiCastDataStreamer;
607
608
struct MultiCastSharedState : public BasicSharedState,
609
                              public std::enable_shared_from_this<MultiCastSharedState> {
610
    MultiCastSharedState(ObjectPool* pool, int cast_sender_count, int node_id);
611
612
    std::unique_ptr<MultiCastDataStreamer> multi_cast_data_streamer;
613
};
614
615
struct AnalyticSharedState : public BasicSharedState {
616
    ENABLE_FACTORY_CREATOR(AnalyticSharedState)
617
618
public:
619
8.18k
    AnalyticSharedState() = default;
620
    std::queue<Block> blocks_buffer GUARDED_BY(buffer_mutex);
621
    AnnotatedMutex buffer_mutex;
622
    bool sink_eos GUARDED_BY(sink_eos_lock) = false;
623
    AnnotatedMutex sink_eos_lock;
624
    Arena agg_arena_pool;
625
};
626
627
struct JoinSharedState : public BasicSharedState {
628
    // For some join case, we can apply a short circuit strategy
629
    // 1. _has_null_in_build_side = true
630
    // 2. build side rows is empty, Join op is: inner join/right outer join/left semi/right semi/right anti
631
    bool _has_null_in_build_side = false;
632
    bool short_circuit_for_probe = false;
633
    // for some join, when build side rows is empty, we could return directly by add some additional null data in probe table.
634
    bool empty_right_table_need_probe_dispose = false;
635
    JoinOpVariants join_op_variants;
636
};
637
638
struct HashJoinSharedState : public JoinSharedState {
639
    ENABLE_FACTORY_CREATOR(HashJoinSharedState)
640
    // Defined in dependency.cpp (they materialize JoinDataVariants).
641
    HashJoinSharedState();
642
    HashJoinSharedState(int num_instances);
643
    std::shared_ptr<Arena> arena = std::make_shared<Arena>();
644
645
    const std::vector<TupleDescriptor*> build_side_child_desc;
646
    size_t build_exprs_size = 0;
647
    std::shared_ptr<Block> build_block;
648
    std::shared_ptr<std::vector<uint32_t>> build_indexes_null;
649
650
    // Used by shared hash table
651
    // For probe operator, hash table in _hash_table_variants is read-only if visited flags is not
652
    // used. (visited flags will be used only in right / full outer join).
653
    //
654
    // For broadcast join, although hash table is read-only, some states in `_hash_table_variants`
655
    // are still could be written. For example, serialized keys will be written in a continuous
656
    // memory in `_hash_table_variants`. So before execution, we should use a local _hash_table_variants
657
    // which has a shared hash table in it.
658
    std::vector<std::shared_ptr<JoinDataVariants>> hash_table_variant_vector;
659
660
    // whether left semi join could directly return
661
    // if runtime filters contains local in filter, we can make sure all input rows are matched
662
    // local filter will always be applied, and in filter could guarantee precise filtering
663
    // ATTN: we should disable always_true logic for in filter when we set this flag
664
    bool left_semi_direct_return = false;
665
666
    // ASOF JOIN specific fields
667
    // Whether the inequality is >= or > (true) vs <= or < (false)
668
    bool asof_inequality_is_greater = true;
669
    // Whether the inequality is strict (> or <) vs non-strict (>= or <=)
670
    bool asof_inequality_is_strict = false;
671
672
    // ASOF JOIN pre-sorted index with inline values for O(log K) branchless lookup
673
    // Typed AsofIndexGroups stored in a variant (uint32_t for DateV2, uint64_t for DateTimeV2/TimestampTZ)
674
    AsofIndexVariant asof_index_groups;
675
    // build_row_index -> bucket_id for O(1) reverse lookup
676
    std::vector<uint32_t> asof_build_row_to_bucket;
677
};
678
679
struct PartitionedHashJoinSharedState
680
        : public HashJoinSharedState,
681
          public std::enable_shared_from_this<PartitionedHashJoinSharedState> {
682
    ENABLE_FACTORY_CREATOR(PartitionedHashJoinSharedState)
683
684
    std::unique_ptr<RuntimeState> _inner_runtime_state;
685
    std::shared_ptr<HashJoinSharedState> _inner_shared_state;
686
    std::vector<std::unique_ptr<MutableBlock>> _partitioned_build_blocks;
687
    std::vector<SpillFileSPtr> _spilled_build_groups;
688
    std::atomic<bool> _is_spilled = false;
689
};
690
691
struct NestedLoopJoinSharedState : public JoinSharedState {
692
    ENABLE_FACTORY_CREATOR(NestedLoopJoinSharedState)
693
    // if true, probe child has no more rows to process
694
    bool probe_side_eos = false;
695
    // Visited flags for each row in build side.
696
    MutableColumns build_side_visited_flags;
697
    // List of build blocks, constructed in prepare()
698
    Blocks build_blocks;
699
};
700
701
struct PartitionSortNodeSharedState : public BasicSharedState {
702
    ENABLE_FACTORY_CREATOR(PartitionSortNodeSharedState)
703
public:
704
    std::queue<Block> blocks_buffer GUARDED_BY(buffer_mutex);
705
    AnnotatedMutex buffer_mutex;
706
    std::vector<std::unique_ptr<PartitionSorter>> partition_sorts;
707
    bool sink_eos GUARDED_BY(sink_eos_lock) = false;
708
    AnnotatedMutex sink_eos_lock;
709
    AnnotatedMutex prepared_finish_lock;
710
};
711
712
struct SetSharedState : public BasicSharedState {
713
    ENABLE_FACTORY_CREATOR(SetSharedState)
714
public:
715
    // Defined in dependency.cpp: constructing/destroying SetDataVariants
716
    // needs the full variant machinery.
717
    SetSharedState();
718
    ~SetSharedState() override;
719
720
    /// default init
721
    Block build_block; // build to source
722
    //record element size in hashtable
723
    int64_t valid_element_in_hash_tbl = 0;
724
    //first: idx mapped to column types
725
    //second: column_id, could point to origin column or cast column
726
    std::unordered_map<int, int> build_col_idx;
727
728
    //// shared static states (shared, decided in prepare/open...)
729
730
    /// init in setup_local_state (allocated in the constructor)
731
    std::unique_ptr<SetDataVariants> hash_table_variants; // the real data HERE.
732
    std::vector<bool> build_not_ignore_null;
733
734
    // The SET operator's child might have different nullable attributes.
735
    // If a calculation involves both nullable and non-nullable columns, the final output should be a nullable column
736
    Status update_build_not_ignore_null(const VExprContextSPtrs& ctxs);
737
738
    size_t get_hash_table_size() const;
739
    /// init in both upstream side.
740
    //The i-th result expr list refers to the i-th child.
741
    std::vector<VExprContextSPtrs> child_exprs_lists;
742
743
    /// init in build side
744
    size_t child_quantity;
745
    VExprContextSPtrs build_child_exprs;
746
    std::vector<Dependency*> probe_finished_children_dependency;
747
748
    /// init in probe side
749
    std::vector<VExprContextSPtrs> probe_child_exprs_lists;
750
751
    std::atomic<bool> ready_for_read = false;
752
753
    Arena arena;
754
755
    /// called in setup_local_state
756
    Status hash_table_init();
757
};
758
759
1.30M
inline bool is_shuffled_exchange(TLocalPartitionType::type idx) {
760
1.30M
    return idx == TLocalPartitionType::GLOBAL_EXECUTION_HASH_SHUFFLE ||
761
1.30M
           idx == TLocalPartitionType::LOCAL_EXECUTION_HASH_SHUFFLE ||
762
1.30M
           idx == TLocalPartitionType::BUCKET_HASH_SHUFFLE;
763
1.30M
}
764
765
240k
inline std::string get_exchange_type_name(TLocalPartitionType::type idx) {
766
240k
    switch (idx) {
767
14
    case TLocalPartitionType::NOOP:
768
14
        return "NOOP";
769
59
    case TLocalPartitionType::GLOBAL_EXECUTION_HASH_SHUFFLE:
770
59
        return "GLOBAL_HASH_SHUFFLE";
771
37.9k
    case TLocalPartitionType::LOCAL_EXECUTION_HASH_SHUFFLE:
772
37.9k
        return "LOCAL_HASH_SHUFFLE";
773
194k
    case TLocalPartitionType::PASSTHROUGH:
774
194k
        return "PASSTHROUGH";
775
190
    case TLocalPartitionType::BUCKET_HASH_SHUFFLE:
776
190
        return "BUCKET_HASH_SHUFFLE";
777
694
    case TLocalPartitionType::BROADCAST:
778
694
        return "BROADCAST";
779
1.68k
    case TLocalPartitionType::ADAPTIVE_PASSTHROUGH:
780
1.68k
        return "ADAPTIVE_PASSTHROUGH";
781
5.68k
    case TLocalPartitionType::PASS_TO_ONE:
782
5.68k
        return "PASS_TO_ONE";
783
0
    case TLocalPartitionType::LOCAL_MERGE_SORT:
784
0
        return "LOCAL_MERGE_SORT";
785
240k
    }
786
0
    throw Exception(Status::FatalError("__builtin_unreachable"));
787
240k
}
788
789
struct DataDistribution {
790
2.03M
    DataDistribution(TLocalPartitionType::type type) : distribution_type(type) {}
791
    DataDistribution(TLocalPartitionType::type type, const std::vector<TExpr>& partition_exprs_)
792
82.1k
            : distribution_type(type), partition_exprs(partition_exprs_) {}
793
8.08k
    DataDistribution(const DataDistribution& other) = default;
794
214k
    bool need_local_exchange() const { return distribution_type != TLocalPartitionType::NOOP; }
795
227k
    DataDistribution& operator=(const DataDistribution& other) = default;
796
    TLocalPartitionType::type distribution_type;
797
    std::vector<TExpr> partition_exprs;
798
};
799
800
class ExchangerBase;
801
802
struct LocalExchangeSharedState : public BasicSharedState {
803
public:
804
    ENABLE_FACTORY_CREATOR(LocalExchangeSharedState);
805
    LocalExchangeSharedState(int num_instances);
806
    ~LocalExchangeSharedState() override;
807
    std::unique_ptr<ExchangerBase> exchanger {};
808
    std::vector<RuntimeProfile::Counter*> mem_counters;
809
    std::atomic<int64_t> mem_usage = 0;
810
    std::atomic<size_t> _buffer_mem_limit = config::local_exchange_buffer_mem_limit;
811
    // We need to make sure to add mem_usage first and then enqueue, otherwise sub mem_usage may cause negative mem_usage during concurrent dequeue.
812
    std::mutex le_lock;
813
    void sub_running_sink_operators();
814
    void sub_running_source_operators();
815
240k
    void _set_always_ready() {
816
1.50M
        for (auto& dep : source_deps) {
817
1.50M
            DCHECK(dep);
818
1.50M
            dep->set_always_ready();
819
1.50M
        }
820
240k
        for (auto& dep : sink_deps) {
821
240k
            DCHECK(dep);
822
240k
            dep->set_always_ready();
823
240k
        }
824
240k
    }
825
826
280k
    Dependency* get_sink_dep_by_channel_id(int channel_id) { return nullptr; }
827
828
291k
    void set_ready_to_read(int channel_id) {
829
291k
        auto& dep = source_deps[channel_id];
830
18.4E
        DCHECK(dep) << channel_id;
831
291k
        dep->set_ready();
832
291k
    }
833
834
291k
    void add_mem_usage(int channel_id, size_t delta) { mem_counters[channel_id]->update(delta); }
835
836
291k
    void sub_mem_usage(int channel_id, size_t delta) {
837
291k
        mem_counters[channel_id]->update(-(int64_t)delta);
838
291k
    }
839
840
233k
    void add_total_mem_usage(size_t delta) {
841
233k
        if (cast_set<int64_t>(mem_usage.fetch_add(delta) + delta) > _buffer_mem_limit) {
842
2.03k
            sink_deps.front()->block();
843
2.03k
        }
844
233k
    }
845
846
233k
    void sub_total_mem_usage(size_t delta) {
847
233k
        auto prev_usage = mem_usage.fetch_sub(delta);
848
233k
        DCHECK_GE(prev_usage, cast_set<int64_t>(delta))
849
0
                << "prev_usage: " << prev_usage << " delta: " << delta;
850
233k
        if (cast_set<int64_t>(prev_usage - delta) <= _buffer_mem_limit) {
851
232k
            sink_deps.front()->set_ready();
852
232k
        }
853
233k
    }
854
855
0
    void set_low_memory_mode(RuntimeState* state) {
856
0
        _buffer_mem_limit = std::min<int64_t>(config::local_exchange_buffer_mem_limit,
857
0
                                              state->low_memory_mode_buffer_limit());
858
0
    }
859
};
860
861
} // namespace doris