Coverage Report

Created: 2026-03-31 13:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/pipeline/pipeline_task.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
#include <cstdint>
21
#include <memory>
22
#include <string>
23
#include <vector>
24
25
#include "common/status.h"
26
#include "core/block/block.h"
27
#include "exec/operator/operator.h"
28
#include "exec/operator/spill_utils.h"
29
#include "exec/pipeline/dependency.h"
30
#include "exec/pipeline/pipeline.h"
31
#include "runtime/runtime_profile.h"
32
#include "util/stopwatch.hpp"
33
34
namespace doris {
35
class QueryContext;
36
class RuntimeState;
37
class PipelineFragmentContext;
38
} // namespace doris
39
40
namespace doris {
41
42
class MultiCoreTaskQueue;
43
class PriorityTaskQueue;
44
class Dependency;
45
46
class PipelineTask : public std::enable_shared_from_this<PipelineTask> {
47
public:
48
    PipelineTask(PipelinePtr& pipeline, uint32_t task_id, RuntimeState* state,
49
                 std::shared_ptr<PipelineFragmentContext> fragment_context,
50
                 RuntimeProfile* parent_profile,
51
                 std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
52
                                         std::vector<std::shared_ptr<Dependency>>>>
53
                         shared_state_map,
54
                 int task_idx);
55
56
    virtual ~PipelineTask();
57
58
    Status prepare(const std::vector<TScanRangeParams>& scan_range, const int sender_id,
59
                   const TDataSink& tsink);
60
61
    virtual Status execute(bool* done);
62
63
    // if the pipeline create a bunch of pipeline task
64
    // must be call after all pipeline task is finish to release resource
65
    virtual Status close(Status exec_status, bool close_sink = true);
66
67
6.00M
    virtual std::weak_ptr<PipelineFragmentContext>& fragment_context() { return _fragment_context; }
68
69
11.9M
    int get_thread_id(int num_threads) const {
70
11.9M
        return _thread_id == -1 ? _thread_id : _thread_id % num_threads;
71
11.9M
    }
72
73
6.00M
    virtual PipelineTask& set_thread_id(int thread_id) {
74
6.00M
        if (thread_id != _thread_id) {
75
3.63M
            COUNTER_UPDATE(_core_change_times, 1);
76
3.63M
            _thread_id = thread_id;
77
3.63M
        }
78
6.00M
        return *this;
79
6.00M
    }
80
81
    virtual Status finalize();
82
83
    std::string debug_string();
84
85
685k
    std::shared_ptr<BasicSharedState> get_source_shared_state() {
86
685k
        return _op_shared_states.contains(_source->operator_id())
87
685k
                       ? _op_shared_states[_source->operator_id()]
88
685k
                       : nullptr;
89
685k
    }
90
91
    /**
92
     * Pipeline task is blockable means it will be blocked in the next run. So we should put it into
93
     * the blocking task scheduler.
94
     */
95
    virtual bool is_blockable() const;
96
97
    /**
98
     * `shared_state` is shared by different pipeline tasks. This function aims to establish
99
     * connections across related tasks.
100
     *
101
     * There are 2 kinds of relationships to share state by tasks.
102
     * 1. For regular operators, for example, Aggregation, we use the AggSinkOperator to create a
103
     *    shared state and then inject it into downstream task which contains the corresponding
104
     *    AggSourceOperator.
105
     * 2. For multiple-sink-single-source operator, for example, Set operations, the shared state is
106
     *    created once and shared by multiple sink operators and single source operator. For this
107
     *    case, we use the first sink operator create shared state and then inject into all of other
108
     *    tasks.
109
     */
110
    bool inject_shared_state(std::shared_ptr<BasicSharedState> shared_state);
111
112
2.83M
    std::shared_ptr<BasicSharedState> get_sink_shared_state() { return _sink_shared_state; }
113
114
2.33M
    BasicSharedState* get_op_shared_state(int id) {
115
2.33M
        if (!_op_shared_states.contains(id)) {
116
1.93M
            return nullptr;
117
1.93M
        }
118
394k
        return _op_shared_states[id].get();
119
2.33M
    }
120
121
    Status wake_up(Dependency* dep, std::unique_lock<std::mutex>& /* dep_lock */);
122
123
0
    DataSinkOperatorPtr sink() const { return _sink; }
124
125
0
    int task_id() const { return _index; };
126
7.31M
    virtual bool is_finalized() const { return _exec_state == State::FINALIZED; }
127
128
1.08M
    void set_wake_up_early(PipelineId wake_by = -1) {
129
1.08M
        _wake_up_early = true;
130
1.08M
        _wake_by = wake_by;
131
1.08M
    }
132
133
    // Unblock all dependencies so this task can never be blocked again.
134
    // This is called when the task is woken up early or the fragment is canceled.
135
    //
136
    // NOTE: This does NOT call operator-level terminate() — operator terminate must run
137
    // inside execute() on the worker thread because operator state is not thread-safe.
138
    void unblock_all_dependencies();
139
140
    // 1 used for update priority queue
141
    // note(wb) an ugly implementation, need refactor later
142
    // 1.1 pipeline task
143
6.00M
    void inc_runtime_ns(uint64_t delta_time) { this->_runtime += delta_time; }
144
6.66M
    uint64_t get_runtime_ns() const { return this->_runtime; }
145
146
    // 1.2 priority queue's queue level
147
6.66M
    void update_queue_level(int queue_level) { this->_queue_level = queue_level; }
148
5.99M
    int get_queue_level() const { return this->_queue_level; }
149
150
6.65M
    void put_in_runnable_queue() {
151
6.65M
        _schedule_time++;
152
6.65M
        _wait_worker_watcher.start();
153
6.65M
    }
154
155
6.66M
    void pop_out_runnable_queue() { _wait_worker_watcher.stop(); }
156
157
54.8k
    bool is_running() { return _running.load(); }
158
12.6M
    virtual bool set_running(bool running) {
159
12.6M
        bool old_value = !running;
160
12.6M
        _running.compare_exchange_weak(old_value, running);
161
12.6M
        return old_value;
162
12.6M
    }
163
164
2.78M
    virtual RuntimeState* runtime_state() const { return _state; }
165
166
0
    virtual std::string task_name() const {
167
0
        return fmt::format("task{}({})", _index, _pipeline->_name);
168
0
    }
169
170
    [[nodiscard]] Status do_revoke_memory(const std::shared_ptr<SpillContext>& spill_context);
171
172
    // TODO: Maybe we do not need this safe code anymore
173
    void stop_if_finished();
174
175
1.75M
    virtual PipelineId pipeline_id() const { return _pipeline->id(); }
176
    [[nodiscard]] size_t get_revocable_size() const;
177
    [[nodiscard]] Status revoke_memory(const std::shared_ptr<SpillContext>& spill_context);
178
179
4.18M
    Status blocked(Dependency* dependency, std::unique_lock<std::mutex>& /* dep_lock */) {
180
4.18M
        DCHECK_EQ(_blocked_dep, nullptr) << "task: " << debug_string();
181
4.18M
        _blocked_dep = dependency;
182
4.18M
        return _state_transition(PipelineTask::State::BLOCKED);
183
4.18M
    }
184
185
protected:
186
    // Only used for RevokableTask
187
1
    PipelineTask() : _index(0) {}
188
189
private:
190
    // Whether this task is blocked before execution (FE 2-phase commit trigger, runtime filters)
191
    bool _wait_to_start();
192
    // Whether this task is blocked during execution (read dependency, write dependency)
193
    bool _is_blocked();
194
    // Whether this task is blocked after execution (pending finish dependency)
195
    bool _is_pending_finish();
196
197
    Status _extract_dependencies();
198
    void _init_profile();
199
    void _fresh_profile_counter();
200
    Status _open();
201
    Status _prepare();
202
203
    // Operator `op` try to reserve memory before executing. Return false if reserve failed
204
    // otherwise return true.
205
    bool _try_to_reserve_memory(const size_t reserve_size, OperatorBase* op);
206
    bool _should_trigger_revoking(const size_t reserve_size) const;
207
208
    const TUniqueId _query_id;
209
    const uint32_t _index;
210
    PipelinePtr _pipeline;
211
    bool _opened;
212
    RuntimeState* _state = nullptr;
213
    int _thread_id = -1;
214
    uint32_t _schedule_time = 0;
215
    std::unique_ptr<Block> _block;
216
217
    std::weak_ptr<PipelineFragmentContext> _fragment_context;
218
219
    // used for priority queue
220
    // it may be visited by different thread but there is no race condition
221
    // so no need to add lock
222
    uint64_t _runtime = 0;
223
    // it's visited in one thread, so no need to thread synchronization
224
    // 1 get task, (set _queue_level/_core_id)
225
    // 2 exe task
226
    // 3 update task statistics(update _queue_level/_core_id)
227
    int _queue_level = 0;
228
229
    RuntimeProfile* _parent_profile = nullptr;
230
    std::unique_ptr<RuntimeProfile> _task_profile;
231
    RuntimeProfile::Counter* _task_cpu_timer = nullptr;
232
    RuntimeProfile::Counter* _prepare_timer = nullptr;
233
    RuntimeProfile::Counter* _open_timer = nullptr;
234
    RuntimeProfile::Counter* _exec_timer = nullptr;
235
    RuntimeProfile::Counter* _get_block_timer = nullptr;
236
    RuntimeProfile::Counter* _get_block_counter = nullptr;
237
    RuntimeProfile::Counter* _sink_timer = nullptr;
238
    RuntimeProfile::Counter* _close_timer = nullptr;
239
    RuntimeProfile::Counter* _schedule_counts = nullptr;
240
    MonotonicStopWatch _wait_worker_watcher;
241
    RuntimeProfile::Counter* _wait_worker_timer = nullptr;
242
    // TODO we should calculate the time between when really runnable and runnable
243
    RuntimeProfile::Counter* _yield_counts = nullptr;
244
    RuntimeProfile::Counter* _core_change_times = nullptr;
245
    RuntimeProfile::Counter* _memory_reserve_times = nullptr;
246
    RuntimeProfile::Counter* _memory_reserve_failed_times = nullptr;
247
248
    Operators _operators; // left is _source, right is _root
249
    OperatorXBase* _source;
250
    OperatorXBase* _root;
251
    DataSinkOperatorPtr _sink;
252
253
    // `_read_dependencies` is stored as same order as `_operators`
254
    std::vector<std::vector<Dependency*>> _read_dependencies;
255
    std::vector<Dependency*> _write_dependencies;
256
    std::vector<Dependency*> _finish_dependencies;
257
    std::vector<Dependency*> _execution_dependencies;
258
259
    // All shared states of this pipeline task.
260
    std::map<int, std::shared_ptr<BasicSharedState>> _op_shared_states;
261
    std::shared_ptr<BasicSharedState> _sink_shared_state;
262
    std::vector<TScanRangeParams> _scan_ranges;
263
    std::map<int,
264
             std::pair<std::shared_ptr<BasicSharedState>, std::vector<std::shared_ptr<Dependency>>>>
265
            _shared_state_map;
266
    int _task_idx;
267
    bool _dry_run = false;
268
    MOCK_REMOVE(const)
269
    unsigned long long _exec_time_slice = config::pipeline_task_exec_time_slice * NANOS_PER_MILLIS;
270
    Dependency* _blocked_dep = nullptr;
271
272
    Dependency* _memory_sufficient_dependency;
273
    std::mutex _dependency_lock;
274
275
    std::atomic<bool> _running {false};
276
    std::atomic<bool> _eos {false};
277
    std::atomic<bool> _wake_up_early {false};
278
    // PipelineTask maybe hold by TaskQueue
279
    std::shared_ptr<MemTrackerLimiter> _query_mem_tracker;
280
281
    /**
282
         *
283
         * INITED -----> RUNNABLE -------------------------+----> FINISHED ---+---> FINALIZED
284
         *                   ^                             |                  |
285
         *                   |                             |                  |
286
         *                   +----------- BLOCKED <--------+------------------+
287
         */
288
    enum class State : int {
289
        INITED,
290
        RUNNABLE,
291
        BLOCKED,
292
        FINISHED,
293
        FINALIZED,
294
    };
295
    const std::vector<std::set<State>> LEGAL_STATE_TRANSITION = {
296
            {},                                               // Target state is INITED
297
            {State::INITED, State::RUNNABLE, State::BLOCKED}, // Target state is RUNNABLE
298
            {State::RUNNABLE, State::FINISHED},               // Target state is BLOCKED
299
            {State::RUNNABLE},                                // Target state is FINISHED
300
            {State::INITED, State::FINISHED}};                // Target state is FINALIZED
301
302
13.7M
    std::string _to_string(State state) const {
303
13.7M
        switch (state) {
304
17
        case State::INITED:
305
17
            return "INITED";
306
6.00M
        case State::RUNNABLE:
307
6.00M
            return "RUNNABLE";
308
4.19M
        case State::BLOCKED:
309
4.19M
            return "BLOCKED";
310
1.75M
        case State::FINISHED:
311
1.75M
            return "FINISHED";
312
1.75M
        case State::FINALIZED:
313
1.75M
            return "FINALIZED";
314
0
        default:
315
0
            __builtin_unreachable();
316
13.7M
        }
317
13.7M
    }
318
319
    Status _state_transition(State new_state);
320
    std::atomic<State> _exec_state = State::INITED;
321
    MonotonicStopWatch _state_change_watcher;
322
    std::atomic<bool> _spilling = false;
323
    const std::string _pipeline_name;
324
    std::atomic<int> _wake_by = -1;
325
};
326
327
using PipelineTaskSPtr = std::shared_ptr<PipelineTask>;
328
329
} // namespace doris