Coverage Report

Created: 2026-03-15 01:14

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
0
    virtual std::weak_ptr<PipelineFragmentContext>& fragment_context() { return _fragment_context; }
68
69
28
    int get_thread_id(int num_threads) const {
70
28
        return _thread_id == -1 ? _thread_id : _thread_id % num_threads;
71
28
    }
72
73
0
    virtual PipelineTask& set_thread_id(int thread_id) {
74
0
        _thread_id = thread_id;
75
0
        if (thread_id != _thread_id) {
76
0
            COUNTER_UPDATE(_core_change_times, 1);
77
0
        }
78
0
        return *this;
79
0
    }
80
81
    virtual Status finalize();
82
83
    std::string debug_string();
84
85
0
    std::shared_ptr<BasicSharedState> get_source_shared_state() {
86
0
        return _op_shared_states.contains(_source->operator_id())
87
0
                       ? _op_shared_states[_source->operator_id()]
88
0
                       : nullptr;
89
0
    }
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
18
    std::shared_ptr<BasicSharedState> get_sink_shared_state() { return _sink_shared_state; }
113
114
18
    BasicSharedState* get_op_shared_state(int id) {
115
18
        if (!_op_shared_states.contains(id)) {
116
16
            return nullptr;
117
16
        }
118
2
        return _op_shared_states[id].get();
119
18
    }
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
164k
    virtual bool is_finalized() const { return _exec_state == State::FINALIZED; }
127
128
5
    void set_wake_up_early(PipelineId wake_by = -1) {
129
5
        _wake_up_early = true;
130
5
        _wake_by = wake_by;
131
5
    }
132
133
    // Execution phase should be terminated. This is called if this task is canceled or waken up early.
134
    void terminate();
135
136
    // 1 used for update priority queue
137
    // note(wb) an ugly implementation, need refactor later
138
    // 1.1 pipeline task
139
0
    void inc_runtime_ns(uint64_t delta_time) { this->_runtime += delta_time; }
140
28
    uint64_t get_runtime_ns() const { return this->_runtime; }
141
142
    // 1.2 priority queue's queue level
143
10
    void update_queue_level(int queue_level) { this->_queue_level = queue_level; }
144
0
    int get_queue_level() const { return this->_queue_level; }
145
146
28
    void put_in_runnable_queue() {
147
28
        _schedule_time++;
148
28
        _wait_worker_watcher.start();
149
28
    }
150
151
10
    void pop_out_runnable_queue() { _wait_worker_watcher.stop(); }
152
153
54.9k
    bool is_running() { return _running.load(); }
154
0
    virtual bool set_running(bool running) {
155
0
        bool old_value = !running;
156
0
        _running.compare_exchange_weak(old_value, running);
157
0
        return old_value;
158
0
    }
159
160
0
    virtual RuntimeState* runtime_state() const { return _state; }
161
162
0
    virtual std::string task_name() const {
163
0
        return fmt::format("task{}({})", _index, _pipeline->_name);
164
0
    }
165
166
    [[nodiscard]] Status do_revoke_memory(const std::shared_ptr<SpillContext>& spill_context);
167
168
    // TODO: Maybe we do not need this safe code anymore
169
    void stop_if_finished();
170
171
0
    virtual PipelineId pipeline_id() const { return _pipeline->id(); }
172
    [[nodiscard]] size_t get_revocable_size() const;
173
    [[nodiscard]] Status revoke_memory(const std::shared_ptr<SpillContext>& spill_context);
174
175
24
    Status blocked(Dependency* dependency, std::unique_lock<std::mutex>& /* dep_lock */) {
176
24
        DCHECK_EQ(_blocked_dep, nullptr) << "task: " << debug_string();
177
24
        _blocked_dep = dependency;
178
24
        return _state_transition(PipelineTask::State::BLOCKED);
179
24
    }
180
181
protected:
182
    // Only used for RevokableTask
183
0
    PipelineTask() : _index(0) {}
184
185
private:
186
    // Whether this task is blocked before execution (FE 2-phase commit trigger, runtime filters)
187
    bool _wait_to_start();
188
    // Whether this task is blocked during execution (read dependency, write dependency)
189
    bool _is_blocked();
190
    // Whether this task is blocked after execution (pending finish dependency)
191
    bool _is_pending_finish();
192
193
    Status _extract_dependencies();
194
    void _init_profile();
195
    void _fresh_profile_counter();
196
    Status _open();
197
    Status _prepare();
198
199
    // Operator `op` try to reserve memory before executing. Return false if reserve failed
200
    // otherwise return true.
201
    bool _try_to_reserve_memory(const size_t reserve_size, OperatorBase* op);
202
203
    const TUniqueId _query_id;
204
    const uint32_t _index;
205
    PipelinePtr _pipeline;
206
    bool _opened;
207
    RuntimeState* _state = nullptr;
208
    int _thread_id = -1;
209
    uint32_t _schedule_time = 0;
210
    std::unique_ptr<Block> _block;
211
212
    std::weak_ptr<PipelineFragmentContext> _fragment_context;
213
214
    // used for priority queue
215
    // it may be visited by different thread but there is no race condition
216
    // so no need to add lock
217
    uint64_t _runtime = 0;
218
    // it's visited in one thread, so no need to thread synchronization
219
    // 1 get task, (set _queue_level/_core_id)
220
    // 2 exe task
221
    // 3 update task statistics(update _queue_level/_core_id)
222
    int _queue_level = 0;
223
224
    RuntimeProfile* _parent_profile = nullptr;
225
    std::unique_ptr<RuntimeProfile> _task_profile;
226
    RuntimeProfile::Counter* _task_cpu_timer = nullptr;
227
    RuntimeProfile::Counter* _prepare_timer = nullptr;
228
    RuntimeProfile::Counter* _open_timer = nullptr;
229
    RuntimeProfile::Counter* _exec_timer = nullptr;
230
    RuntimeProfile::Counter* _get_block_timer = nullptr;
231
    RuntimeProfile::Counter* _get_block_counter = nullptr;
232
    RuntimeProfile::Counter* _sink_timer = nullptr;
233
    RuntimeProfile::Counter* _close_timer = nullptr;
234
    RuntimeProfile::Counter* _schedule_counts = nullptr;
235
    MonotonicStopWatch _wait_worker_watcher;
236
    RuntimeProfile::Counter* _wait_worker_timer = nullptr;
237
    // TODO we should calculate the time between when really runnable and runnable
238
    RuntimeProfile::Counter* _yield_counts = nullptr;
239
    RuntimeProfile::Counter* _core_change_times = nullptr;
240
    RuntimeProfile::Counter* _memory_reserve_times = nullptr;
241
    RuntimeProfile::Counter* _memory_reserve_failed_times = nullptr;
242
243
    Operators _operators; // left is _source, right is _root
244
    OperatorXBase* _source;
245
    OperatorXBase* _root;
246
    DataSinkOperatorPtr _sink;
247
248
    // `_read_dependencies` is stored as same order as `_operators`
249
    std::vector<std::vector<Dependency*>> _read_dependencies;
250
    std::vector<Dependency*> _write_dependencies;
251
    std::vector<Dependency*> _finish_dependencies;
252
    std::vector<Dependency*> _execution_dependencies;
253
254
    // All shared states of this pipeline task.
255
    std::map<int, std::shared_ptr<BasicSharedState>> _op_shared_states;
256
    std::shared_ptr<BasicSharedState> _sink_shared_state;
257
    std::vector<TScanRangeParams> _scan_ranges;
258
    std::map<int,
259
             std::pair<std::shared_ptr<BasicSharedState>, std::vector<std::shared_ptr<Dependency>>>>
260
            _shared_state_map;
261
    int _task_idx;
262
    bool _dry_run = false;
263
    MOCK_REMOVE(const)
264
    unsigned long long _exec_time_slice = config::pipeline_task_exec_time_slice * NANOS_PER_MILLIS;
265
    Dependency* _blocked_dep = nullptr;
266
267
    Dependency* _memory_sufficient_dependency;
268
    std::mutex _dependency_lock;
269
270
    std::atomic<bool> _running {false};
271
    std::atomic<bool> _eos {false};
272
    std::atomic<bool> _wake_up_early {false};
273
    // PipelineTask maybe hold by TaskQueue
274
    std::shared_ptr<MemTrackerLimiter> _query_mem_tracker;
275
276
    /**
277
         *
278
         * INITED -----> RUNNABLE -------------------------+----> FINISHED ---+---> FINALIZED
279
         *                   ^                             |                  |
280
         *                   |                             |                  |
281
         *                   +----------- BLOCKED <--------+------------------+
282
         */
283
    enum class State : int {
284
        INITED,
285
        RUNNABLE,
286
        BLOCKED,
287
        FINISHED,
288
        FINALIZED,
289
    };
290
    const std::vector<std::set<State>> LEGAL_STATE_TRANSITION = {
291
            {},                                               // Target state is INITED
292
            {State::INITED, State::RUNNABLE, State::BLOCKED}, // Target state is RUNNABLE
293
            {State::RUNNABLE, State::FINISHED},               // Target state is BLOCKED
294
            {State::RUNNABLE},                                // Target state is FINISHED
295
            {State::INITED, State::FINISHED}};                // Target state is FINALIZED
296
297
55.1k
    std::string _to_string(State state) const {
298
55.1k
        switch (state) {
299
17
        case State::INITED:
300
17
            return "INITED";
301
55.0k
        case State::RUNNABLE:
302
55.0k
            return "RUNNABLE";
303
40
        case State::BLOCKED:
304
40
            return "BLOCKED";
305
21
        case State::FINISHED:
306
21
            return "FINISHED";
307
19
        case State::FINALIZED:
308
19
            return "FINALIZED";
309
0
        default:
310
0
            __builtin_unreachable();
311
55.1k
        }
312
55.1k
    }
313
314
    Status _state_transition(State new_state);
315
    std::atomic<State> _exec_state = State::INITED;
316
    MonotonicStopWatch _state_change_watcher;
317
    std::atomic<bool> _spilling = false;
318
    const std::string _pipeline_name;
319
    int _wake_by = -1;
320
};
321
322
using PipelineTaskSPtr = std::shared_ptr<PipelineTask>;
323
324
} // namespace doris