Coverage Report

Created: 2026-02-26 00:50

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