Coverage Report

Created: 2026-08-24 11:25

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/Partitions_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
class QueryCacheRuntime;
52
53
class Dependency;
54
struct LocalExchangeSharedState;
55
56
class PipelineFragmentContext : public TaskExecutionContext {
57
public:
58
    ENABLE_FACTORY_CREATOR(PipelineFragmentContext);
59
    PipelineFragmentContext(TUniqueId query_id, const TPipelineFragmentParams& request,
60
                            std::shared_ptr<QueryContext> query_ctx, ExecEnv* exec_env,
61
                            const std::function<void(RuntimeState*, Status*)>& call_back);
62
63
    ~PipelineFragmentContext() override;
64
65
    void print_profile(const std::string& extra_info);
66
67
    std::vector<std::shared_ptr<TRuntimeProfileTree>> collect_realtime_profile() const;
68
    std::shared_ptr<TRuntimeProfileTree> collect_realtime_load_channel_profile() const;
69
70
    bool is_timeout(timespec now) const;
71
72
19.8k
    uint64_t elapsed_time() const { return _fragment_watcher.elapsed_time(); }
73
74
0
    int timeout_second() const { return _timeout; }
75
76
    PipelinePtr add_pipeline(PipelinePtr parent = nullptr, int idx = -1);
77
78
212k
    QueryContext* get_query_ctx() { return _query_ctx.get(); }
79
3.16M
    [[nodiscard]] bool is_canceled() const { return _query_ctx->is_cancelled(); }
80
81
    Status prepare(ThreadPool* thread_pool);
82
83
    Status submit();
84
85
1.30k
    void set_is_report_success(bool is_report_success) { _is_report_success = is_report_success; }
86
87
    void cancel(const Status reason);
88
89
    bool notify_close();
90
91
2.88k
    TUniqueId get_query_id() const { return _query_id; }
92
93
6
    [[nodiscard]] int get_fragment_id() const { return _fragment_id; }
94
95
    void decrement_running_task(PipelineId pipeline_id);
96
97
2
    uint32_t rec_cte_stage() const { return _rec_cte_stage; }
98
0
    void set_rec_cte_stage(uint32_t stage) { _rec_cte_stage = stage; }
99
100
    Status send_report(bool done, bool report_query_statistics = false);
101
102
    void trigger_report_if_necessary();
103
    void refresh_next_report_time();
104
105
    std::string debug_string();
106
107
3.26k
    [[nodiscard]] int next_operator_id() { return _operator_id--; }
108
109
5.70k
    [[nodiscard]] int max_operator_id() const { return _operator_id; }
110
111
2.84k
    [[nodiscard]] int next_sink_operator_id() { return _sink_operator_id--; }
112
113
    [[nodiscard]] size_t get_revocable_size(bool* has_running_task) const;
114
115
    [[nodiscard]] std::vector<PipelineTask*> get_revocable_tasks() const;
116
117
152
    void clear_finished_tasks() {
118
152
        if (_need_notify_close) {
119
0
            return;
120
0
        }
121
304
        for (size_t j = 0; j < _tasks.size(); j++) {
122
424
            for (size_t i = 0; i < _tasks[j].size(); i++) {
123
272
                _tasks[j][i].first->stop_if_finished();
124
272
            }
125
152
        }
126
152
    }
127
128
    std::string get_load_error_url();
129
    std::string get_first_error_msg();
130
131
    std::set<int> get_deregister_runtime_filter() const;
132
133
    // Store the brpc ClosureGuard so the RPC response is deferred until this PFC is destroyed.
134
    // When need_send_report_on_destruction is true (final_close), arm the final report and do not
135
    // store the guard (let it fire on return to complete the RPC). The report is sent only after
136
    // the last target task closes.
137
    //
138
    // Thread safety: This method is NOT thread-safe. It reads/writes _wait_close_guard without
139
    // synchronization. Currently it is only called from rerun_fragment() which is invoked
140
    // sequentially by RecCTESourceOperatorX (a serial operator) — one opcode at a time per
141
    // fragment. Do NOT call this concurrently from multiple threads.
142
    Status listen_wait_close(const std::shared_ptr<brpc::ClosureGuard>& guard,
143
3
                             bool need_send_report_on_destruction) {
144
3
        if (_wait_close_guard) {
145
0
            return Status::InternalError("Already listening wait close");
146
0
        }
147
3
        if (need_send_report_on_destruction) {
148
3
            std::lock_guard<std::mutex> l(_task_mutex);
149
3
            _send_report_on_close = true;
150
3
        } else {
151
0
            _wait_close_guard = guard;
152
0
        }
153
3
        return Status::OK();
154
3
    }
155
156
private:
157
    bool _finish_load_fragment();
158
    void _coordinator_callback(const ReportStatusRequest& req);
159
    void _append_external_file_commit_data(const ReportStatusRequest& req,
160
                                           TReportExecStatusParams* params) const;
161
    std::string _to_http_path(const std::string& file_name) const;
162
163
    void _release_resource();
164
165
    Status _build_and_prepare_full_pipeline(ThreadPool* thread_pool);
166
167
    Status _build_pipelines(ObjectPool* pool, const DescriptorTbl& descs, OperatorPtr* root,
168
                            PipelinePtr cur_pipe);
169
    Status _create_tree_helper(ObjectPool* pool, const std::vector<TPlanNode>& tnodes,
170
                               const DescriptorTbl& descs, OperatorPtr parent, int* node_idx,
171
                               OperatorPtr* root, PipelinePtr& cur_pipe, int child_idx,
172
                               const bool followed_by_shuffled_join,
173
                               const bool require_bucket_distribution);
174
175
    Status _create_operator(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs,
176
                            OperatorPtr& op, PipelinePtr& cur_pipe, int parent_idx, int child_idx,
177
                            const bool followed_by_shuffled_join,
178
                            const bool require_bucket_distribution, OperatorPtr& cache_op);
179
    template <bool is_intersect>
180
    Status _build_operators_for_set_operation_node(ObjectPool* pool, const TPlanNode& tnode,
181
                                                   const DescriptorTbl& descs, OperatorPtr& op,
182
                                                   PipelinePtr& cur_pipe,
183
                                                   std::vector<DataSinkOperatorPtr>& sink_ops);
184
185
    Status _create_data_sink(ObjectPool* pool, const TDataSink& thrift_sink,
186
                             const std::vector<TExpr>& output_exprs,
187
                             const TPipelineFragmentParams& params, const RowDescriptor& row_desc,
188
                             RuntimeState* state, DescriptorTbl& desc_tbl,
189
                             PipelineId cur_pipeline_id);
190
    Status _plan_local_exchange(int num_buckets,
191
                                const std::map<int, int>& bucket_seq_to_instance_idx,
192
                                const std::map<int, int>& shuffle_idx_to_instance_idx);
193
    Status _plan_local_exchange(int num_buckets, int pip_idx, PipelinePtr pip,
194
                                const std::map<int, int>& bucket_seq_to_instance_idx,
195
                                const std::map<int, int>& shuffle_idx_to_instance_idx);
196
    void _inherit_pipeline_properties(const DataDistribution& data_distribution,
197
                                      PipelinePtr pipe_with_source, PipelinePtr pipe_with_sink);
198
    Status _add_local_exchange(int pip_idx, int idx, int node_id, ObjectPool* pool,
199
                               PipelinePtr cur_pipe, DataDistribution data_distribution,
200
                               bool* do_local_exchange, int num_buckets,
201
                               const std::map<int, int>& bucket_seq_to_instance_idx,
202
                               const std::map<int, int>& shuffle_idx_to_instance_idx);
203
    Status _add_local_exchange_impl(int idx, ObjectPool* pool, PipelinePtr cur_pipe,
204
                                    PipelinePtr new_pip, DataDistribution data_distribution,
205
                                    bool* do_local_exchange, int num_buckets,
206
                                    const std::map<int, int>& bucket_seq_to_instance_idx,
207
                                    const std::map<int, int>& shuffle_idx_to_instance_idx);
208
209
    Status _build_pipeline_tasks(ThreadPool* thread_pool);
210
    Status _build_pipeline_tasks_for_instance(
211
            int instance_idx,
212
            const std::vector<std::shared_ptr<RuntimeProfile>>& pipeline_id_to_profile);
213
    // Close the fragment instance and return true if the caller should call
214
    // remove_pipeline_context() **after** releasing _task_mutex. This avoids
215
    // holding _task_mutex while acquiring _pipeline_map's shard lock, which
216
    // would create an ABBA deadlock with dump_pipeline_tasks().
217
    bool _close_fragment_instance();
218
    void _init_next_report_time();
219
220
    // Id of this query
221
    TUniqueId _query_id;
222
    int _fragment_id;
223
224
    ExecEnv* _exec_env = nullptr;
225
226
    std::atomic_bool _prepared = false;
227
    bool _submitted = false;
228
229
    Pipelines _pipelines;
230
    PipelineId _next_pipeline_id = 0;
231
    std::mutex _task_mutex;
232
    int _closed_tasks = 0;
233
    // After prepared, `_total_tasks` is equal to the size of `_tasks`.
234
    // When submit fail, `_total_tasks` is equal to the number of tasks submitted.
235
    std::atomic<int> _total_tasks = 0;
236
237
    std::unique_ptr<RuntimeProfile> _fragment_level_profile;
238
    // This is used by loading process to report Fragment exec status to FE, FE need fragment status to
239
    // check if the loading process is finished. And during the report, BE will send the loading message to FE,
240
    // for example the loading error, commit rows num etc.
241
    bool _is_report_success = false;
242
243
    std::unique_ptr<RuntimeState> _runtime_state;
244
245
    std::shared_ptr<QueryContext> _query_ctx;
246
247
    MonotonicStopWatch _fragment_watcher;
248
    RuntimeProfile::Counter* _prepare_timer = nullptr;
249
    RuntimeProfile::Counter* _init_context_timer = nullptr;
250
    RuntimeProfile::Counter* _build_pipelines_timer = nullptr;
251
    RuntimeProfile::Counter* _plan_local_exchanger_timer = nullptr;
252
    RuntimeProfile::Counter* _prepare_all_pipelines_timer = nullptr;
253
    RuntimeProfile::Counter* _build_tasks_timer = nullptr;
254
255
    std::function<void(RuntimeState*, Status*)> _call_back;
256
    std::atomic_bool _is_fragment_instance_closed = false;
257
258
    // 0 indicates reporting is in progress or not required
259
    std::atomic_bool _disable_period_report = true;
260
    std::atomic_uint64_t _previous_report_time = 0;
261
262
    DescriptorTbl* _desc_tbl = nullptr;
263
    int _num_instances = 1;
264
265
    int _timeout = -1;
266
    bool _use_serial_source = false;
267
268
    OperatorPtr _root_op = nullptr;
269
    //
270
    /**
271
     * Matrix stores tasks with local runtime states.
272
     * This is a [n * m] matrix. n is parallelism of pipeline engine and m is the number of pipelines.
273
     *
274
     * 2-D matrix:
275
     * +-------------------------+------------+-------+
276
     * |            | Pipeline 0 | Pipeline 1 |  ...  |
277
     * +------------+------------+------------+-------+
278
     * | Instance 0 |  task 0-0  |  task 0-1  |  ...  |
279
     * +------------+------------+------------+-------+
280
     * | Instance 1 |  task 1-0  |  task 1-1  |  ...  |
281
     * +------------+------------+------------+-------+
282
     * | ...                                          |
283
     * +--------------------------------------+-------+
284
     */
285
    std::vector<
286
            std::vector<std::pair<std::shared_ptr<PipelineTask>, std::unique_ptr<RuntimeState>>>>
287
            _tasks;
288
289
    // TODO: remove the _sink and _multi_cast_stream_sink_senders to set both
290
    // of it in pipeline task not the fragment_context
291
#ifdef __clang__
292
#pragma clang diagnostic push
293
#pragma clang diagnostic ignored "-Wshadow-field"
294
#endif
295
    DataSinkOperatorPtr _sink = nullptr;
296
#ifdef __clang__
297
#pragma clang diagnostic pop
298
#endif
299
300
    // `_dag` manage dependencies between pipelines by pipeline ID. the indices will be blocked by members
301
    std::map<PipelineId, std::vector<PipelineId>> _dag;
302
303
    // We use preorder traversal to create an operator tree. When we meet a join node, we should
304
    // build probe operator and build operator in separate pipelines. To do this, we should build
305
    // ProbeSide first, and use `_pipelines_to_build` to store which pipeline the build operator
306
    // is in, so we can build BuildSide once we complete probe side.
307
    struct pipeline_parent_map {
308
        std::map<int, std::vector<PipelinePtr>> _build_side_pipelines;
309
528
        void push(int parent_node_id, PipelinePtr pipeline) {
310
528
            if (!_build_side_pipelines.contains(parent_node_id)) {
311
264
                _build_side_pipelines.insert({parent_node_id, {pipeline}});
312
264
            } else {
313
264
                _build_side_pipelines[parent_node_id].push_back(pipeline);
314
264
            }
315
528
        }
316
2.86k
        void pop(PipelinePtr& cur_pipe, int parent_node_id, int child_idx) {
317
2.86k
            if (!_build_side_pipelines.contains(parent_node_id)) {
318
2.33k
                return;
319
2.33k
            }
320
2.86k
            DCHECK(_build_side_pipelines.contains(parent_node_id));
321
530
            auto& child_pipeline = _build_side_pipelines[parent_node_id];
322
530
            DCHECK(child_idx < child_pipeline.size());
323
530
            cur_pipe = child_pipeline[child_idx];
324
530
        }
325
1.30k
        void clear() { _build_side_pipelines.clear(); }
326
    } _pipeline_parent_map;
327
328
    std::mutex _state_map_lock;
329
330
    // Start from -1 so all operator IDs are negative. This avoids collision with
331
    // unpaired sinks (OlapTableSink etc.) whose hardcoded dest_id=0 would otherwise
332
    // match the first operator's ID when FE-planned LocalExchangeNode is the root.
333
    int _operator_id = -1;
334
    int _sink_operator_id = -1;
335
    /**
336
     * Some states are shared by tasks in different pipeline task (e.g. local exchange , broadcast join).
337
     *
338
     * local exchange sink 0 ->                               -> local exchange source 0
339
     *                            LocalExchangeSharedState
340
     * local exchange sink 1 ->                               -> local exchange source 1
341
     *
342
     * hash join build sink 0 ->                               -> hash join build source 0
343
     *                              HashJoinSharedState
344
     * hash join build sink 1 ->                               -> hash join build source 1
345
     *
346
     * So we should keep states here.
347
     */
348
    std::map<int,
349
             std::pair<std::shared_ptr<BasicSharedState>, std::vector<std::shared_ptr<Dependency>>>>
350
            _op_id_to_shared_state;
351
352
    std::map<PipelineId, Pipeline*> _pip_id_to_pipeline;
353
    std::vector<std::unique_ptr<RuntimeFilterMgr>> _runtime_filter_mgr_map;
354
355
    // Deferred exchanger creation info for FE-planned local exchanges.
356
    // Exchanger sender count depends on the upstream pipeline's final num_tasks,
357
    // which is only known after the full plan tree is built (child operators like
358
    // serial ExchangeNode may reduce num_tasks). So we defer exchanger creation
359
    // until after _build_pipelines completes.
360
    struct DeferredExchangerInfo {
361
        std::shared_ptr<LocalExchangeSharedState> shared_state;
362
        PipelinePtr upstream_pipe;
363
        TLocalPartitionType::type partition_type;
364
        int num_partitions;
365
        int free_blocks_limit;
366
        int local_exchange_id;
367
        int sink_id;
368
    };
369
    std::vector<DeferredExchangerInfo> _deferred_exchangers;
370
    Status _create_deferred_local_exchangers();
371
    // After _build_pipelines, propagate _num_instances from FE-planned LOCAL_EXCHANGE
372
    // pipelines upward through the DAG to ancestor pipelines that inherited reduced
373
    // num_tasks from a serial operator.
374
    void _propagate_local_exchange_num_tasks();
375
376
    //Here are two types of runtime states:
377
    //    - _runtime state is at the Fragment level.
378
    //    - _task_runtime_states is at the task level, unique to each task.
379
380
    std::vector<TUniqueId> _fragment_instance_ids;
381
382
    // Total instance num running on all BEs
383
    int _total_instances = -1;
384
385
    TPipelineFragmentParams _params;
386
    int32_t _parallel_instances = 0;
387
388
    // Query cache context of this fragment, shared by the olap scan operator
389
    // and the cache source operator so both consume the same per-instance
390
    // cache decision (HIT / INCREMENTAL / MISS). Created lazily when the
391
    // fragment carries a query_cache_param. See QueryCacheRuntime.
392
    std::shared_ptr<QueryCacheRuntime> _query_cache_runtime;
393
394
    std::atomic<bool> _need_notify_close = false;
395
    // Protected by _task_mutex. Recursive FINAL_CLOSE arms this before notify_close(), so either
396
    // that call or the last task close submits the report, but never both.
397
    bool _send_report_on_close = false;
398
    bool _final_report_submitted = false;
399
    // Holds the brpc ClosureGuard for async wait-close during recursive CTE rerun.
400
    // When the PFC finishes closing and is destroyed, the shared_ptr destructor fires
401
    // the ClosureGuard, which completes the brpc response to the RecCTESourceOperatorX.
402
    // Only written by listen_wait_close() from a single rerun_fragment RPC thread.
403
    std::shared_ptr<brpc::ClosureGuard> _wait_close_guard = nullptr;
404
405
    // The recursion round number for recursive CTE fragments.
406
    // Incremented each time the fragment is rebuilt via rerun_fragment(rebuild).
407
    // Used to stamp runtime filter RPCs so stale messages from old rounds are discarded.
408
    uint32_t _rec_cte_stage = 0;
409
};
410
} // namespace doris