Coverage Report

Created: 2025-10-15 19:27

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