Coverage Report

Created: 2026-08-06 13:30

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