Coverage Report

Created: 2026-02-28 11:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/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 "pipeline/dependency.h"
27
#include "pipeline/exec/operator.h"
28
#include "pipeline/exec/spill_utils.h"
29
#include "pipeline/pipeline.h"
30
#include "util/runtime_profile.h"
31
#include "util/stopwatch.hpp"
32
#include "vec/core/block.h"
33
34
namespace doris {
35
class QueryContext;
36
class RuntimeState;
37
namespace pipeline {
38
class PipelineFragmentContext;
39
} // namespace pipeline
40
} // namespace doris
41
42
namespace doris::pipeline {
43
44
class MultiCoreTaskQueue;
45
class PriorityTaskQueue;
46
class Dependency;
47
48
class PipelineTask : public std::enable_shared_from_this<PipelineTask> {
49
public:
50
    PipelineTask(PipelinePtr& pipeline, uint32_t task_id, RuntimeState* state,
51
                 std::shared_ptr<PipelineFragmentContext> fragment_context,
52
                 RuntimeProfile* parent_profile,
53
                 std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
54
                                         std::vector<std::shared_ptr<Dependency>>>>
55
                         shared_state_map,
56
                 int task_idx);
57
58
    virtual ~PipelineTask();
59
60
    Status prepare(const std::vector<TScanRangeParams>& scan_range, const int sender_id,
61
                   const TDataSink& tsink);
62
63
    virtual Status execute(bool* done);
64
65
    // if the pipeline create a bunch of pipeline task
66
    // must be call after all pipeline task is finish to release resource
67
    virtual Status close(Status exec_status, bool close_sink = true);
68
69
0
    virtual std::weak_ptr<PipelineFragmentContext>& fragment_context() { return _fragment_context; }
70
71
28
    int get_thread_id(int num_threads) const {
72
28
        return _thread_id == -1 ? _thread_id : _thread_id % num_threads;
73
28
    }
74
75
0
    virtual PipelineTask& set_thread_id(int thread_id) {
76
0
        _thread_id = thread_id;
77
0
        if (thread_id != _thread_id) {
78
0
            COUNTER_UPDATE(_core_change_times, 1);
79
0
        }
80
0
        return *this;
81
0
    }
82
83
    virtual Status finalize();
84
85
    std::string debug_string();
86
87
0
    std::shared_ptr<BasicSharedState> get_source_shared_state() {
88
0
        return _op_shared_states.contains(_source->operator_id())
89
0
                       ? _op_shared_states[_source->operator_id()]
90
0
                       : nullptr;
91
0
    }
92
93
    /**
94
     * Pipeline task is blockable means it will be blocked in the next run. So we should put it into
95
     * the blocking task scheduler.
96
     */
97
    virtual bool is_blockable() const;
98
99
    /**
100
     * `shared_state` is shared by different pipeline tasks. This function aims to establish
101
     * connections across related tasks.
102
     *
103
     * There are 2 kinds of relationships to share state by tasks.
104
     * 1. For regular operators, for example, Aggregation, we use the AggSinkOperator to create a
105
     *    shared state and then inject it into downstream task which contains the corresponding
106
     *    AggSourceOperator.
107
     * 2. For multiple-sink-single-source operator, for example, Set operations, the shared state is
108
     *    created once and shared by multiple sink operators and single source operator. For this
109
     *    case, we use the first sink operator create shared state and then inject into all of other
110
     *    tasks.
111
     */
112
    bool inject_shared_state(std::shared_ptr<BasicSharedState> shared_state);
113
114
18
    std::shared_ptr<BasicSharedState> get_sink_shared_state() { return _sink_shared_state; }
115
116
18
    BasicSharedState* get_op_shared_state(int id) {
117
18
        if (!_op_shared_states.contains(id)) {
118
16
            return nullptr;
119
16
        }
120
2
        return _op_shared_states[id].get();
121
18
    }
122
123
    Status wake_up(Dependency* dep, std::unique_lock<std::mutex>& /* dep_lock */);
124
125
0
    DataSinkOperatorPtr sink() const { return _sink; }
126
127
0
    int task_id() const { return _index; };
128
94.6k
    virtual bool is_finalized() const { return _exec_state == State::FINALIZED; }
129
0
    virtual bool is_finished() const {
130
0
        return _exec_state == State::FINISHED || _exec_state == State::FINALIZED;
131
0
    }
132
133
5
    void set_wake_up_early(PipelineId wake_by = -1) {
134
5
        _wake_up_early = true;
135
5
        _wake_by = wake_by;
136
5
    }
137
138
    // Execution phase should be terminated. This is called if this task is canceled or waken up early.
139
    void terminate();
140
141
    // 1 used for update priority queue
142
    // note(wb) an ugly implementation, need refactor later
143
    // 1.1 pipeline task
144
0
    void inc_runtime_ns(uint64_t delta_time) { this->_runtime += delta_time; }
145
28
    uint64_t get_runtime_ns() const { return this->_runtime; }
146
147
    // 1.2 priority queue's queue level
148
10
    void update_queue_level(int queue_level) { this->_queue_level = queue_level; }
149
0
    int get_queue_level() const { return this->_queue_level; }
150
151
28
    void put_in_runnable_queue() {
152
28
        _schedule_time++;
153
28
        _wait_worker_watcher.start();
154
28
    }
155
156
10
    void pop_out_runnable_queue() { _wait_worker_watcher.stop(); }
157
158
31.5k
    bool is_running() { return _running.load(); }
159
0
    virtual bool set_running(bool running) {
160
0
        bool old_value = !running;
161
0
        _running.compare_exchange_weak(old_value, running);
162
0
        return old_value;
163
0
    }
164
165
0
    virtual RuntimeState* runtime_state() const { return _state; }
166
167
0
    virtual std::string task_name() const {
168
0
        return fmt::format("task{}({})", _index, _pipeline->_name);
169
0
    }
170
171
    [[nodiscard]] Status do_revoke_memory(const std::shared_ptr<SpillContext>& spill_context);
172
173
    // TODO: Maybe we do not need this safe code anymore
174
    void stop_if_finished();
175
176
0
    virtual PipelineId pipeline_id() const { return _pipeline->id(); }
177
    [[nodiscard]] size_t get_revocable_size() const;
178
    [[nodiscard]] Status revoke_memory(const std::shared_ptr<SpillContext>& spill_context);
179
180
24
    Status blocked(Dependency* dependency, std::unique_lock<std::mutex>& /* dep_lock */) {
181
24
        DCHECK_EQ(_blocked_dep, nullptr) << "task: " << debug_string();
182
24
        _blocked_dep = dependency;
183
24
        return _state_transition(PipelineTask::State::BLOCKED);
184
24
    }
185
186
protected:
187
    // Only used for RevokableTask
188
0
    PipelineTask() : _index(0) {}
189
190
private:
191
    // Whether this task is blocked before execution (FE 2-phase commit trigger, runtime filters)
192
    bool _wait_to_start();
193
    // Whether this task is blocked during execution (read dependency, write dependency)
194
    bool _is_blocked();
195
    // Whether this task is blocked after execution (pending finish dependency)
196
    bool _is_pending_finish();
197
198
    Status _extract_dependencies();
199
    void _init_profile();
200
    void _fresh_profile_counter();
201
    Status _open();
202
    Status _prepare();
203
204
    // Operator `op` try to reserve memory before executing. Return false if reserve failed
205
    // otherwise return true.
206
    bool _try_to_reserve_memory(const size_t reserve_size, OperatorBase* op);
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<vectorized::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
31.6k
    std::string _to_string(State state) const {
303
31.6k
        switch (state) {
304
17
        case State::INITED:
305
17
            return "INITED";
306
31.5k
        case State::RUNNABLE:
307
31.5k
            return "RUNNABLE";
308
40
        case State::BLOCKED:
309
40
            return "BLOCKED";
310
21
        case State::FINISHED:
311
21
            return "FINISHED";
312
19
        case State::FINALIZED:
313
19
            return "FINALIZED";
314
0
        default:
315
0
            __builtin_unreachable();
316
31.6k
        }
317
31.6k
    }
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
    int _wake_by = -1;
325
};
326
327
using PipelineTaskSPtr = std::shared_ptr<PipelineTask>;
328
329
} // namespace doris::pipeline