Coverage Report

Created: 2026-05-16 21:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/pipeline/pipeline_fragment_context.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 <brpc/closure_guard.h>
21
#include <gen_cpp/FrontendService_types.h>
22
#include <gen_cpp/Types_types.h>
23
#include <gen_cpp/types.pb.h>
24
25
#include <atomic>
26
#include <cstddef>
27
#include <cstdint>
28
#include <functional>
29
#include <memory>
30
#include <mutex>
31
#include <set>
32
#include <string>
33
#include <vector>
34
35
#include "common/status.h"
36
#include "exec/pipeline/pipeline.h"
37
#include "exec/pipeline/pipeline_task.h"
38
#include "runtime/query_context.h"
39
#include "runtime/runtime_profile.h"
40
#include "runtime/runtime_state.h"
41
#include "runtime/task_execution_context.h"
42
#include "util/stopwatch.hpp"
43
#include "util/uid_util.h"
44
45
namespace doris {
46
struct ReportStatusRequest;
47
class ExecEnv;
48
class RuntimeFilterMergeControllerEntity;
49
class TDataSink;
50
class TPipelineFragmentParams;
51
52
class Dependency;
53
54
class PipelineFragmentContext : public TaskExecutionContext {
55
public:
56
    ENABLE_FACTORY_CREATOR(PipelineFragmentContext);
57
    PipelineFragmentContext(TUniqueId query_id, const TPipelineFragmentParams& request,
58
                            std::shared_ptr<QueryContext> query_ctx, ExecEnv* exec_env,
59
                            const std::function<void(RuntimeState*, Status*)>& call_back);
60
61
    ~PipelineFragmentContext() override;
62
63
    void print_profile(const std::string& extra_info);
64
65
    std::vector<TProfileNodeReport> collect_realtime_profile() const;
66
    std::shared_ptr<TRuntimeProfileTree> collect_realtime_load_channel_profile() const;
67
68
    bool is_timeout(timespec now) const;
69
70
15.3k
    uint64_t elapsed_time() const { return _fragment_watcher.elapsed_time(); }
71
72
0
    int timeout_second() const { return _timeout; }
73
74
    PipelinePtr add_pipeline(PipelinePtr parent = nullptr, int idx = -1);
75
76
123k
    QueryContext* get_query_ctx() { return _query_ctx.get(); }
77
2.95M
    [[nodiscard]] bool is_canceled() const { return _query_ctx->is_cancelled(); }
78
79
    Status prepare(ThreadPool* thread_pool);
80
81
    Status submit();
82
83
0
    void set_is_report_success(bool is_report_success) { _is_report_success = is_report_success; }
84
85
    void cancel(const Status reason);
86
87
    bool notify_close();
88
89
26
    TUniqueId get_query_id() const { return _query_id; }
90
91
6
    [[nodiscard]] int get_fragment_id() const { return _fragment_id; }
92
93
    void decrement_running_task(PipelineId pipeline_id);
94
95
2
    uint32_t rec_cte_stage() const { return _rec_cte_stage; }
96
0
    void set_rec_cte_stage(uint32_t stage) { _rec_cte_stage = stage; }
97
98
    Status send_report(bool);
99
100
    void trigger_report_if_necessary();
101
    void refresh_next_report_time();
102
103
    std::string debug_string();
104
105
0
    [[nodiscard]] int next_operator_id() { return _operator_id--; }
106
107
0
    [[nodiscard]] int max_operator_id() const { return _operator_id; }
108
109
0
    [[nodiscard]] int next_sink_operator_id() { return _sink_operator_id--; }
110
111
    [[nodiscard]] size_t get_revocable_size(bool* has_running_task) const;
112
113
    [[nodiscard]] std::vector<PipelineTask*> get_revocable_tasks() const;
114
115
0
    void clear_finished_tasks() {
116
0
        if (_need_notify_close) {
117
0
            return;
118
0
        }
119
0
        for (size_t j = 0; j < _tasks.size(); j++) {
120
0
            for (size_t i = 0; i < _tasks[j].size(); i++) {
121
0
                _tasks[j][i].first->stop_if_finished();
122
0
            }
123
0
        }
124
0
    }
125
126
    std::string get_load_error_url();
127
    std::string get_first_error_msg();
128
129
    std::set<int> get_deregister_runtime_filter() const;
130
131
    // Store the brpc ClosureGuard so the RPC response is deferred until this PFC is destroyed.
132
    // When need_send_report_on_destruction is true (final_close), send the report immediately
133
    // and do not store the guard (let it fire on return to complete the RPC).
134
    //
135
    // Thread safety: This method is NOT thread-safe. It reads/writes _wait_close_guard without
136
    // synchronization. Currently it is only called from rerun_fragment() which is invoked
137
    // sequentially by RecCTESourceOperatorX (a serial operator) — one opcode at a time per
138
    // fragment. Do NOT call this concurrently from multiple threads.
139
    Status listen_wait_close(const std::shared_ptr<brpc::ClosureGuard>& guard,
140
0
                             bool need_send_report_on_destruction) {
141
0
        if (_wait_close_guard) {
142
0
            return Status::InternalError("Already listening wait close");
143
0
        }
144
0
        if (need_send_report_on_destruction) {
145
0
            return send_report(true);
146
0
        } else {
147
0
            _wait_close_guard = guard;
148
0
        }
149
0
        return Status::OK();
150
0
    }
151
152
private:
153
    void _coordinator_callback(const ReportStatusRequest& req);
154
    std::string _to_http_path(const std::string& file_name) const;
155
156
    void _release_resource();
157
158
    Status _build_and_prepare_full_pipeline(ThreadPool* thread_pool);
159
160
    Status _build_pipelines(ObjectPool* pool, const DescriptorTbl& descs, OperatorPtr* root,
161
                            PipelinePtr cur_pipe);
162
    Status _create_tree_helper(ObjectPool* pool, const std::vector<TPlanNode>& tnodes,
163
                               const DescriptorTbl& descs, OperatorPtr parent, int* node_idx,
164
                               OperatorPtr* root, PipelinePtr& cur_pipe, int child_idx,
165
                               const bool followed_by_shuffled_join,
166
                               const bool require_bucket_distribution);
167
168
    Status _create_operator(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs,
169
                            OperatorPtr& op, PipelinePtr& cur_pipe, int parent_idx, int child_idx,
170
                            const bool followed_by_shuffled_join,
171
                            const bool require_bucket_distribution, OperatorPtr& cache_op);
172
    template <bool is_intersect>
173
    Status _build_operators_for_set_operation_node(ObjectPool* pool, const TPlanNode& tnode,
174
                                                   const DescriptorTbl& descs, OperatorPtr& op,
175
                                                   PipelinePtr& cur_pipe,
176
                                                   std::vector<DataSinkOperatorPtr>& sink_ops);
177
178
    Status _create_data_sink(ObjectPool* pool, const TDataSink& thrift_sink,
179
                             const std::vector<TExpr>& output_exprs,
180
                             const TPipelineFragmentParams& params, const RowDescriptor& row_desc,
181
                             RuntimeState* state, DescriptorTbl& desc_tbl,
182
                             PipelineId cur_pipeline_id);
183
    Status _plan_local_exchange(int num_buckets,
184
                                const std::map<int, int>& bucket_seq_to_instance_idx,
185
                                const std::map<int, int>& shuffle_idx_to_instance_idx);
186
    Status _plan_local_exchange(int num_buckets, int pip_idx, PipelinePtr pip,
187
                                const std::map<int, int>& bucket_seq_to_instance_idx,
188
                                const std::map<int, int>& shuffle_idx_to_instance_idx);
189
    void _inherit_pipeline_properties(const DataDistribution& data_distribution,
190
                                      PipelinePtr pipe_with_source, PipelinePtr pipe_with_sink);
191
    Status _add_local_exchange(int pip_idx, int idx, int node_id, ObjectPool* pool,
192
                               PipelinePtr cur_pipe, DataDistribution data_distribution,
193
                               bool* do_local_exchange, int num_buckets,
194
                               const std::map<int, int>& bucket_seq_to_instance_idx,
195
                               const std::map<int, int>& shuffle_idx_to_instance_idx);
196
    Status _add_local_exchange_impl(int idx, ObjectPool* pool, PipelinePtr cur_pipe,
197
                                    PipelinePtr new_pip, DataDistribution data_distribution,
198
                                    bool* do_local_exchange, int num_buckets,
199
                                    const std::map<int, int>& bucket_seq_to_instance_idx,
200
                                    const std::map<int, int>& shuffle_idx_to_instance_idx);
201
202
    Status _build_pipeline_tasks(ThreadPool* thread_pool);
203
    Status _build_pipeline_tasks_for_instance(
204
            int instance_idx,
205
            const std::vector<std::shared_ptr<RuntimeProfile>>& pipeline_id_to_profile);
206
    // Close the fragment instance and return true if the caller should call
207
    // remove_pipeline_context() **after** releasing _task_mutex. This avoids
208
    // holding _task_mutex while acquiring _pipeline_map's shard lock, which
209
    // would create an ABBA deadlock with dump_pipeline_tasks().
210
    bool _close_fragment_instance();
211
    void _init_next_report_time();
212
213
    // Id of this query
214
    TUniqueId _query_id;
215
    int _fragment_id;
216
217
    ExecEnv* _exec_env = nullptr;
218
219
    std::atomic_bool _prepared = false;
220
    bool _submitted = false;
221
222
    Pipelines _pipelines;
223
    PipelineId _next_pipeline_id = 0;
224
    std::mutex _task_mutex;
225
    int _closed_tasks = 0;
226
    // After prepared, `_total_tasks` is equal to the size of `_tasks`.
227
    // When submit fail, `_total_tasks` is equal to the number of tasks submitted.
228
    std::atomic<int> _total_tasks = 0;
229
230
    std::unique_ptr<RuntimeProfile> _fragment_level_profile;
231
    bool _is_report_success = false;
232
233
    std::unique_ptr<RuntimeState> _runtime_state;
234
235
    std::shared_ptr<QueryContext> _query_ctx;
236
237
    MonotonicStopWatch _fragment_watcher;
238
    RuntimeProfile::Counter* _prepare_timer = nullptr;
239
    RuntimeProfile::Counter* _init_context_timer = nullptr;
240
    RuntimeProfile::Counter* _build_pipelines_timer = nullptr;
241
    RuntimeProfile::Counter* _plan_local_exchanger_timer = nullptr;
242
    RuntimeProfile::Counter* _prepare_all_pipelines_timer = nullptr;
243
    RuntimeProfile::Counter* _build_tasks_timer = nullptr;
244
245
    std::function<void(RuntimeState*, Status*)> _call_back;
246
    std::atomic_bool _is_fragment_instance_closed = false;
247
248
    // If this is set to false, and '_is_report_success' is false as well,
249
    // This executor will not report status to FE on being cancelled.
250
    bool _is_report_on_cancel;
251
252
    // 0 indicates reporting is in progress or not required
253
    std::atomic_bool _disable_period_report = true;
254
    std::atomic_uint64_t _previous_report_time = 0;
255
256
    DescriptorTbl* _desc_tbl = nullptr;
257
    int _num_instances = 1;
258
259
    int _timeout = -1;
260
    bool _use_serial_source = false;
261
262
    OperatorPtr _root_op = nullptr;
263
    //
264
    /**
265
     * Matrix stores tasks with local runtime states.
266
     * This is a [n * m] matrix. n is parallelism of pipeline engine and m is the number of pipelines.
267
     *
268
     * 2-D matrix:
269
     * +-------------------------+------------+-------+
270
     * |            | Pipeline 0 | Pipeline 1 |  ...  |
271
     * +------------+------------+------------+-------+
272
     * | Instance 0 |  task 0-0  |  task 0-1  |  ...  |
273
     * +------------+------------+------------+-------+
274
     * | Instance 1 |  task 1-0  |  task 1-1  |  ...  |
275
     * +------------+------------+------------+-------+
276
     * | ...                                          |
277
     * +--------------------------------------+-------+
278
     */
279
    std::vector<
280
            std::vector<std::pair<std::shared_ptr<PipelineTask>, std::unique_ptr<RuntimeState>>>>
281
            _tasks;
282
283
    // TODO: remove the _sink and _multi_cast_stream_sink_senders to set both
284
    // of it in pipeline task not the fragment_context
285
#ifdef __clang__
286
#pragma clang diagnostic push
287
#pragma clang diagnostic ignored "-Wshadow-field"
288
#endif
289
    DataSinkOperatorPtr _sink = nullptr;
290
#ifdef __clang__
291
#pragma clang diagnostic pop
292
#endif
293
294
    // `_dag` manage dependencies between pipelines by pipeline ID. the indices will be blocked by members
295
    std::map<PipelineId, std::vector<PipelineId>> _dag;
296
297
    // We use preorder traversal to create an operator tree. When we meet a join node, we should
298
    // build probe operator and build operator in separate pipelines. To do this, we should build
299
    // ProbeSide first, and use `_pipelines_to_build` to store which pipeline the build operator
300
    // is in, so we can build BuildSide once we complete probe side.
301
    struct pipeline_parent_map {
302
        std::map<int, std::vector<PipelinePtr>> _build_side_pipelines;
303
0
        void push(int parent_node_id, PipelinePtr pipeline) {
304
0
            if (!_build_side_pipelines.contains(parent_node_id)) {
305
0
                _build_side_pipelines.insert({parent_node_id, {pipeline}});
306
0
            } else {
307
0
                _build_side_pipelines[parent_node_id].push_back(pipeline);
308
0
            }
309
0
        }
310
0
        void pop(PipelinePtr& cur_pipe, int parent_node_id, int child_idx) {
311
0
            if (!_build_side_pipelines.contains(parent_node_id)) {
312
0
                return;
313
0
            }
314
0
            DCHECK(_build_side_pipelines.contains(parent_node_id));
315
0
            auto& child_pipeline = _build_side_pipelines[parent_node_id];
316
0
            DCHECK(child_idx < child_pipeline.size());
317
0
            cur_pipe = child_pipeline[child_idx];
318
0
        }
319
0
        void clear() { _build_side_pipelines.clear(); }
320
    } _pipeline_parent_map;
321
322
    std::mutex _state_map_lock;
323
324
    int _operator_id = 0;
325
    int _sink_operator_id = 0;
326
    /**
327
     * Some states are shared by tasks in different pipeline task (e.g. local exchange , broadcast join).
328
     *
329
     * local exchange sink 0 ->                               -> local exchange source 0
330
     *                            LocalExchangeSharedState
331
     * local exchange sink 1 ->                               -> local exchange source 1
332
     *
333
     * hash join build sink 0 ->                               -> hash join build source 0
334
     *                              HashJoinSharedState
335
     * hash join build sink 1 ->                               -> hash join build source 1
336
     *
337
     * So we should keep states here.
338
     */
339
    std::map<int,
340
             std::pair<std::shared_ptr<BasicSharedState>, std::vector<std::shared_ptr<Dependency>>>>
341
            _op_id_to_shared_state;
342
343
    std::map<PipelineId, Pipeline*> _pip_id_to_pipeline;
344
    std::vector<std::unique_ptr<RuntimeFilterMgr>> _runtime_filter_mgr_map;
345
346
    //Here are two types of runtime states:
347
    //    - _runtime state is at the Fragment level.
348
    //    - _task_runtime_states is at the task level, unique to each task.
349
350
    std::vector<TUniqueId> _fragment_instance_ids;
351
352
    // Total instance num running on all BEs
353
    int _total_instances = -1;
354
355
    TPipelineFragmentParams _params;
356
    int32_t _parallel_instances = 0;
357
358
    std::atomic<bool> _need_notify_close = false;
359
    // Holds the brpc ClosureGuard for async wait-close during recursive CTE rerun.
360
    // When the PFC finishes closing and is destroyed, the shared_ptr destructor fires
361
    // the ClosureGuard, which completes the brpc response to the RecCTESourceOperatorX.
362
    // Only written by listen_wait_close() from a single rerun_fragment RPC thread.
363
    std::shared_ptr<brpc::ClosureGuard> _wait_close_guard = nullptr;
364
365
    // The recursion round number for recursive CTE fragments.
366
    // Incremented each time the fragment is rebuilt via rerun_fragment(rebuild).
367
    // Used to stamp runtime filter RPCs so stale messages from old rounds are discarded.
368
    uint32_t _rec_cte_stage = 0;
369
};
370
} // namespace doris