Coverage Report

Created: 2025-04-22 18:57

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