Coverage Report

Created: 2026-04-17 17:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/fragment_mgr.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/QueryPlanExtra_types.h>
23
#include <gen_cpp/Types_types.h>
24
#include <gen_cpp/types.pb.h>
25
26
#include <cstdint>
27
#include <functional>
28
#include <iosfwd>
29
#include <map>
30
#include <memory>
31
#include <mutex>
32
#include <set>
33
#include <string>
34
#include <unordered_map>
35
#include <vector>
36
37
#include "common/be_mock_util.h"
38
#include "common/metrics/metrics.h"
39
#include "common/status.h"
40
#include "exec/runtime_filter/runtime_filter_mgr.h"
41
#include "runtime/query_context.h"
42
#include "service/http/rest_monitor_iface.h"
43
#include "util/countdown_latch.h"
44
#include "util/hash_util.hpp" // IWYU pragma: keep
45
46
namespace butil {
47
class IOBufAsZeroCopyInputStream;
48
}
49
50
namespace doris {
51
extern bvar::Adder<uint64_t> g_fragment_executing_count;
52
extern bvar::Status<uint64_t> g_fragment_last_active_time;
53
54
class PipelineFragmentContext;
55
class QueryContext;
56
class ExecEnv;
57
class ThreadPool;
58
class PExecPlanFragmentStartRequest;
59
class PMergeFilterRequest;
60
class RuntimeProfile;
61
class RuntimeState;
62
class TPipelineFragmentParams;
63
class TPipelineInstanceParams;
64
class TScanColumnDesc;
65
class TScanOpenParams;
66
class Thread;
67
class WorkloadQueryInfo;
68
69
std::string to_load_error_http_path(const std::string& file_name);
70
71
template <typename Key, typename Value, typename ValueType>
72
class ConcurrentContextMap {
73
public:
74
    using ApplyFunction = std::function<Status(phmap::flat_hash_map<Key, Value>&)>;
75
    ConcurrentContextMap();
76
    Value find(const Key& query_id);
77
    void insert(const Key& query_id, std::shared_ptr<ValueType>);
78
    void clear();
79
    bool erase(const Key& query_id);
80
14
    size_t num_items() const {
81
14
        size_t n = 0;
82
1.79k
        for (auto& pair : _internal_map) {
83
1.79k
            std::shared_lock lock(*pair.first);
84
1.79k
            auto& map = pair.second;
85
1.79k
            n += map.size();
86
1.79k
        }
87
14
        return n;
88
14
    }
_ZNK5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E9num_itemsEv
Line
Count
Source
80
14
    size_t num_items() const {
81
14
        size_t n = 0;
82
1.79k
        for (auto& pair : _internal_map) {
83
1.79k
            std::shared_lock lock(*pair.first);
84
1.79k
            auto& map = pair.second;
85
1.79k
            n += map.size();
86
1.79k
        }
87
14
        return n;
88
14
    }
Unexecuted instantiation: _ZNK5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_23PipelineFragmentContextEES5_E9num_itemsEv
89
43
    void apply(ApplyFunction&& function) {
90
5.50k
        for (auto& pair : _internal_map) {
91
            // TODO: Now only the cancel worker do the GC the _query_ctx_map. each query must
92
            // do erase the finish query unless in _query_ctx_map. Rethink the logic is ok
93
5.50k
            std::unique_lock lock(*pair.first);
94
5.50k
            static_cast<void>(function(pair.second));
95
5.50k
        }
96
43
    }
_ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_23PipelineFragmentContextEES5_E5applyEOSt8functionIFNS_6StatusERN5phmap13flat_hash_mapIS3_S6_NSA_4HashIS3_EENSA_7EqualToIS3_EESaIS1_IKS3_S6_EEEEEE
Line
Count
Source
89
14
    void apply(ApplyFunction&& function) {
90
1.79k
        for (auto& pair : _internal_map) {
91
            // TODO: Now only the cancel worker do the GC the _query_ctx_map. each query must
92
            // do erase the finish query unless in _query_ctx_map. Rethink the logic is ok
93
1.79k
            std::unique_lock lock(*pair.first);
94
1.79k
            static_cast<void>(function(pair.second));
95
1.79k
        }
96
14
    }
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E5applyEOSt8functionIFNS_6StatusERN5phmap13flat_hash_mapIS1_S4_NS8_4HashIS1_EENS8_7EqualToIS1_EESaISt4pairIKS1_S4_EEEEEE
Line
Count
Source
89
29
    void apply(ApplyFunction&& function) {
90
3.71k
        for (auto& pair : _internal_map) {
91
            // TODO: Now only the cancel worker do the GC the _query_ctx_map. each query must
92
            // do erase the finish query unless in _query_ctx_map. Rethink the logic is ok
93
3.71k
            std::unique_lock lock(*pair.first);
94
3.71k
            static_cast<void>(function(pair.second));
95
3.71k
        }
96
29
    }
97
98
    Status apply_if_not_exists(const Key& query_id, std::shared_ptr<ValueType>& query_ctx,
99
                               ApplyFunction&& function);
100
101
private:
102
    // The lock should only be used to protect the structures in fragment manager. Has to be
103
    // used in a very small scope because it may dead lock. For example, if the _lock is used
104
    // in prepare stage, the call path is  prepare --> expr prepare --> may call allocator
105
    // when allocate failed, allocator may call query_is_cancelled, query is callced will also
106
    // call _lock, so that there is dead lock.
107
    std::vector<std::pair<std::unique_ptr<std::shared_mutex>, phmap::flat_hash_map<Key, Value>>>
108
            _internal_map;
109
};
110
111
// This class used to manage all the fragment execute in this instance
112
class FragmentMgr : public RestMonitorIface {
113
public:
114
    using FinishCallback = std::function<void(RuntimeState*, Status*)>;
115
116
    FragmentMgr(ExecEnv* exec_env);
117
    ~FragmentMgr() override;
118
119
    void stop();
120
121
    // execute one plan fragment
122
123
    Status exec_plan_fragment(const TPipelineFragmentParams& params, const QuerySource query_type,
124
                              const TPipelineFragmentParamsList& parent);
125
126
    void remove_pipeline_context(std::pair<TUniqueId, int> key);
127
    void remove_query_context(const TUniqueId& key);
128
129
    // `is_prepare_success` is used by invoker to ensure callback can be handle correctly (eg. stream_load_executor)
130
    Status exec_plan_fragment(const TPipelineFragmentParams& params, const QuerySource query_type,
131
                              const FinishCallback& cb, const TPipelineFragmentParamsList& parent,
132
                              std::shared_ptr<bool> is_prepare_success = nullptr);
133
134
    Status start_query_execution(const PExecPlanFragmentStartRequest* request);
135
136
    // Can be used in both version.
137
    MOCK_FUNCTION void cancel_query(const TUniqueId query_id, const Status reason);
138
139
    void cancel_worker();
140
141
    void debug(std::stringstream& ss) override;
142
143
    // input: TQueryPlanInfo fragment_instance_id
144
    // output: selected_columns
145
    // execute external query, all query info are packed in TScanOpenParams
146
    Status exec_external_plan_fragment(const TScanOpenParams& params,
147
                                       const TQueryPlanInfo& t_query_plan_info,
148
                                       const TUniqueId& query_id,
149
                                       const TUniqueId& fragment_instance_id,
150
                                       std::vector<TScanColumnDesc>* selected_columns);
151
152
    Status apply_filterv2(const PPublishFilterRequestV2* request,
153
                          butil::IOBufAsZeroCopyInputStream* attach_data);
154
155
    Status merge_filter(const PMergeFilterRequest* request,
156
                        butil::IOBufAsZeroCopyInputStream* attach_data);
157
158
    Status send_filter_size(const PSendFilterSizeRequest* request);
159
160
    Status sync_filter_size(const PSyncFilterSizeRequest* request);
161
162
0
    ThreadPool* get_thread_pool() { return _thread_pool.get(); }
163
164
    // When fragment mgr is going to stop, the _stop_background_threads_latch is set to 0
165
    // and other module that use fragment mgr's thread pool should get this signal and exit.
166
0
    bool shutting_down() { return _stop_background_threads_latch.count() == 0; }
167
168
0
    int32_t running_query_num() { return cast_set<int32_t>(_query_ctx_map.num_items()); }
169
170
    std::string dump_pipeline_tasks(int64_t duration = 0);
171
    std::string dump_pipeline_tasks(TUniqueId& query_id);
172
173
    void get_runtime_query_info(std::vector<std::weak_ptr<ResourceContext>>* _resource_ctx_list);
174
175
    Status get_realtime_exec_status(const TUniqueId& query_id,
176
                                    TReportExecStatusParams* exec_status);
177
    // get the query statistics of with a given query id
178
    Status get_query_statistics(const TUniqueId& query_id, TQueryStatistics* query_stats);
179
180
    std::shared_ptr<QueryContext> get_query_ctx(const TUniqueId& query_id);
181
182
    Status transmit_rec_cte_block(const TUniqueId& query_id, const TUniqueId& instance_id,
183
                                  int node_id,
184
                                  const google::protobuf::RepeatedPtrField<PBlock>& pblocks,
185
                                  bool eos);
186
187
    Status rerun_fragment(const std::shared_ptr<brpc::ClosureGuard>& guard,
188
                          const TUniqueId& query_id, int fragment,
189
                          PRerunFragmentParams_Opcode stage);
190
191
    Status reset_global_rf(const TUniqueId& query_id,
192
                           const google::protobuf::RepeatedField<int32_t>& filter_ids);
193
194
private:
195
    struct BrpcItem {
196
        TNetworkAddress network_address;
197
        std::vector<std::weak_ptr<QueryContext>> queries;
198
    };
199
200
    Status _get_or_create_query_ctx(const TPipelineFragmentParams& params,
201
                                    const TPipelineFragmentParamsList& parent,
202
                                    QuerySource query_type,
203
                                    std::shared_ptr<QueryContext>& query_ctx);
204
205
    void _collect_timeout_queries_and_brpc_items(
206
            std::vector<TUniqueId>& queries_timeout,
207
            std::unordered_map<std::shared_ptr<PBackendService_Stub>, BrpcItem>&
208
                    brpc_stub_with_queries,
209
            timespec now);
210
211
    void _collect_invalid_queries(
212
            std::vector<TUniqueId>& queries_lost_coordinator,
213
            std::vector<TUniqueId>& queries_pipeline_task_leak,
214
            const std::map<int64_t, std::unordered_set<TUniqueId>>& running_queries_on_all_fes,
215
            const std::map<TNetworkAddress, FrontendInfo>& running_fes,
216
            timespec check_invalid_query_last_timestamp);
217
218
    void _check_brpc_available(const std::shared_ptr<PBackendService_Stub>& brpc_stub,
219
                               const BrpcItem& brpc_item);
220
221
    // This is input params
222
    ExecEnv* _exec_env = nullptr;
223
224
    // (QueryID, FragmentID) -> PipelineFragmentContext
225
    ConcurrentContextMap<std::pair<TUniqueId, int>, std::shared_ptr<PipelineFragmentContext>,
226
                         PipelineFragmentContext>
227
            _pipeline_map;
228
229
    // Saved params and callback for rerunnable (recursive CTE) fragments.
230
    // Only populated when need_notify_close == true during exec_plan_fragment.
231
    // Lifecycle: created in exec_plan_fragment(), used in rerun_fragment(rebuild)
232
    // to recreate PFC with fresh state, cleaned up in remove_query_context().
233
    struct RerunableFragmentInfo {
234
        // Runtime filter IDs registered by the old PFC, collected during wait_for_destroy.
235
        // These are deregistered from the RuntimeFilterMgr before the new PFC is created.
236
        std::set<int> deregister_runtime_filter_ids;
237
        // Original params from FE, used to recreate the PFC each round.
238
        TPipelineFragmentParams params;
239
        TPipelineFragmentParamsList parent;
240
        FinishCallback finish_callback;
241
        // Hold query_ctx to prevent it from being destroyed while rerunnable fragments exist.
242
        std::shared_ptr<QueryContext> query_ctx;
243
        // Monotonically increasing stage counter, stamps runtime filter RPCs.
244
        uint32_t stage = 0;
245
    };
246
    std::mutex _rerunnable_params_lock;
247
    std::map<std::pair<TUniqueId, int>, RerunableFragmentInfo> _rerunnable_params_map;
248
249
    // query id -> QueryContext
250
    ConcurrentContextMap<TUniqueId, std::weak_ptr<QueryContext>, QueryContext> _query_ctx_map;
251
    // keep query ctx do not delete immediately to make rf coordinator merge filter work well after query eos
252
    ConcurrentContextMap<TUniqueId, std::shared_ptr<QueryContext>, QueryContext>
253
            _query_ctx_map_delay_delete;
254
255
    CountDownLatch _stop_background_threads_latch;
256
    std::shared_ptr<Thread> _cancel_thread;
257
    // This pool is used as global async task pool
258
    std::unique_ptr<ThreadPool> _thread_pool;
259
260
    std::shared_ptr<MetricEntity> _entity;
261
    UIntGauge* timeout_canceled_fragment_count = nullptr;
262
};
263
264
uint64_t get_fragment_executing_count();
265
uint64_t get_fragment_last_active_time();
266
} // namespace doris