Coverage Report

Created: 2026-03-11 10:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/runtime/query_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 <gen_cpp/PaloInternalService_types.h>
21
#include <gen_cpp/RuntimeProfile_types.h>
22
#include <gen_cpp/Types_types.h>
23
#include <glog/logging.h>
24
25
#include <atomic>
26
#include <cstdint>
27
#include <memory>
28
#include <mutex>
29
#include <string>
30
#include <unordered_map>
31
32
#include "common/config.h"
33
#include "common/factory_creator.h"
34
#include "common/object_pool.h"
35
#include "common/status.h"
36
#include "exec/runtime_filter/runtime_filter_mgr.h"
37
#include "exec/scan/scanner_scheduler.h"
38
#include "runtime/exec_env.h"
39
#include "runtime/memory/mem_tracker_limiter.h"
40
#include "runtime/runtime_predicate.h"
41
#include "runtime/workload_group/workload_group.h"
42
#include "runtime/workload_management/resource_context.h"
43
#include "util/hash_util.hpp"
44
#include "util/threadpool.h"
45
46
namespace doris {
47
48
class PipelineFragmentContext;
49
class PipelineTask;
50
class Dependency;
51
class RecCTEScanLocalState;
52
53
struct ReportStatusRequest {
54
    const Status status;
55
    std::vector<RuntimeState*> runtime_states;
56
    bool done;
57
    TNetworkAddress coord_addr;
58
    TUniqueId query_id;
59
    int fragment_id;
60
    TUniqueId fragment_instance_id;
61
    int backend_num;
62
    RuntimeState* runtime_state;
63
    std::string load_error_url;
64
    std::string first_error_msg;
65
    std::function<void(const Status&)> cancel_fn;
66
};
67
68
enum class QuerySource {
69
    INTERNAL_FRONTEND,
70
    STREAM_LOAD,
71
    GROUP_COMMIT_LOAD,
72
    ROUTINE_LOAD,
73
    EXTERNAL_CONNECTOR
74
};
75
76
const std::string toString(QuerySource query_source);
77
78
// Save the common components of fragments in a query.
79
// Some components like DescriptorTbl may be very large
80
// that will slow down each execution of fragments when DeSer them every time.
81
class DescriptorTbl;
82
class QueryContext : public std::enable_shared_from_this<QueryContext> {
83
    ENABLE_FACTORY_CREATOR(QueryContext);
84
85
public:
86
    static std::shared_ptr<QueryContext> create(TUniqueId query_id, ExecEnv* exec_env,
87
                                                const TQueryOptions& query_options,
88
                                                TNetworkAddress coord_addr, bool is_nereids,
89
                                                TNetworkAddress current_connect_fe,
90
                                                QuerySource query_type);
91
92
    // use QueryContext::create, cannot be made private because of ENABLE_FACTORY_CREATOR::create_shared.
93
    QueryContext(TUniqueId query_id, ExecEnv* exec_env, const TQueryOptions& query_options,
94
                 TNetworkAddress coord_addr, bool is_nereids, TNetworkAddress current_connect_fe,
95
                 QuerySource query_type);
96
97
    ~QueryContext();
98
99
    void init_query_task_controller();
100
101
0
    ExecEnv* exec_env() const { return _exec_env; }
102
103
0
    bool is_timeout(timespec now) const {
104
0
        if (_timeout_second <= 0) {
105
0
            return false;
106
0
        }
107
0
        return _query_watcher.elapsed_time_seconds(now) > _timeout_second;
108
0
    }
109
110
0
    int64_t get_remaining_query_time_seconds() const {
111
0
        timespec now;
112
0
        clock_gettime(CLOCK_MONOTONIC, &now);
113
0
        if (is_timeout(now)) {
114
0
            return -1;
115
0
        }
116
0
        int64_t elapsed_seconds = _query_watcher.elapsed_time_seconds(now);
117
0
        return _timeout_second - elapsed_seconds;
118
0
    }
119
120
    void set_ready_to_execute(Status reason);
121
122
2.92M
    [[nodiscard]] bool is_cancelled() const { return !_exec_status.ok(); }
123
124
    void cancel_all_pipeline_context(const Status& reason, int fragment_id = -1);
125
    std::string print_all_pipeline_context();
126
    void set_pipeline_context(const int fragment_id,
127
                              std::shared_ptr<PipelineFragmentContext> pip_ctx);
128
    void cancel(Status new_status, int fragment_id = -1);
129
130
25
    [[nodiscard]] Status exec_status() { return _exec_status.status(); }
131
132
    void set_execution_dependency_ready();
133
134
    void set_memory_sufficient(bool sufficient);
135
136
    void set_ready_to_execute_only();
137
138
42
    bool has_runtime_predicate(int source_node_id) {
139
42
        return _runtime_predicates.contains(source_node_id);
140
42
    }
141
142
0
    RuntimePredicate& get_runtime_predicate(int source_node_id) {
143
0
        DCHECK(has_runtime_predicate(source_node_id));
144
0
        return _runtime_predicates.find(source_node_id)->second;
145
0
    }
146
147
0
    void init_runtime_predicates(const std::vector<TTopnFilterDesc>& topn_filter_descs) {
148
0
        for (auto desc : topn_filter_descs) {
149
0
            _runtime_predicates.try_emplace(desc.source_node_id, desc);
150
0
        }
151
0
    }
152
153
    Status set_workload_group(WorkloadGroupPtr& wg);
154
155
121
    int execution_timeout() const {
156
121
        return _query_options.__isset.execution_timeout ? _query_options.execution_timeout
157
121
                                                        : _query_options.query_timeout;
158
121
    }
159
160
0
    int32_t runtime_filter_wait_time_ms() const {
161
0
        return _query_options.runtime_filter_wait_time_ms;
162
0
    }
163
164
0
    int be_exec_version() const {
165
0
        if (!_query_options.__isset.be_exec_version) {
166
0
            return 0;
167
0
        }
168
0
        return _query_options.be_exec_version;
169
0
    }
170
171
0
    [[nodiscard]] int64_t get_fe_process_uuid() const {
172
0
        return _query_options.__isset.fe_process_uuid ? _query_options.fe_process_uuid : 0;
173
0
    }
174
175
0
    bool ignore_runtime_filter_error() const {
176
0
        return _query_options.__isset.ignore_runtime_filter_error
177
0
                       ? _query_options.ignore_runtime_filter_error
178
0
                       : false;
179
0
    }
180
181
0
    bool enable_force_spill() const {
182
0
        return _query_options.__isset.enable_force_spill && _query_options.enable_force_spill;
183
0
    }
184
93.2k
    const TQueryOptions& query_options() const { return _query_options; }
185
0
    bool should_be_shuffled_agg(int node_id) const {
186
0
        return _query_options.__isset.shuffled_agg_ids &&
187
0
               std::any_of(_query_options.shuffled_agg_ids.begin(),
188
0
                           _query_options.shuffled_agg_ids.end(),
189
0
                           [&](const int id) -> bool { return id == node_id; });
190
0
    }
191
192
    // global runtime filter mgr, the runtime filter have remote target or
193
    // need local merge should regist here. before publish() or push_to_remote()
194
    // the runtime filter should do the local merge work
195
107
    RuntimeFilterMgr* runtime_filter_mgr() { return _runtime_filter_mgr.get(); }
196
197
72.1k
    TUniqueId query_id() const { return _query_id; }
198
199
14
    ScannerScheduler* get_scan_scheduler() { return _scan_task_scheduler; }
200
201
0
    ScannerScheduler* get_remote_scan_scheduler() { return _remote_scan_task_scheduler; }
202
203
72.1k
    Dependency* get_execution_dependency() { return _execution_dependency.get(); }
204
72.2k
    Dependency* get_memory_sufficient_dependency() { return _memory_sufficient_dependency.get(); }
205
206
    doris::TaskScheduler* get_pipe_exec_scheduler();
207
208
    void set_merge_controller_handler(
209
0
            std::shared_ptr<RuntimeFilterMergeControllerEntity>& handler) {
210
0
        _merge_controller_handler = handler;
211
0
    }
212
0
    std::shared_ptr<RuntimeFilterMergeControllerEntity> get_merge_controller_handler() const {
213
0
        return _merge_controller_handler;
214
0
    }
215
216
70
    bool is_nereids() const { return _is_nereids; }
217
218
123k
    WorkloadGroupPtr workload_group() const { return _resource_ctx->workload_group(); }
219
837k
    std::shared_ptr<MemTrackerLimiter> query_mem_tracker() const {
220
837k
        DCHECK(_resource_ctx->memory_context()->mem_tracker() != nullptr);
221
837k
        return _resource_ctx->memory_context()->mem_tracker();
222
837k
    }
223
224
11
    int32_t get_slot_count() const {
225
11
        return _query_options.__isset.query_slot_count ? _query_options.query_slot_count : 1;
226
11
    }
227
228
    DescriptorTbl* desc_tbl = nullptr;
229
    bool set_rsc_info = false;
230
    std::string user;
231
    std::string group;
232
    TNetworkAddress coord_addr;
233
    TNetworkAddress current_connect_fe;
234
    TQueryGlobals query_globals;
235
0
    const TQueryGlobals get_query_globals() const { return query_globals; }
236
237
    ObjectPool obj_pool;
238
239
49.1k
    std::shared_ptr<ResourceContext> resource_ctx() { return _resource_ctx; }
240
241
    // plan node id -> TFileScanRangeParams
242
    // only for file scan node
243
    std::map<int, TFileScanRangeParams> file_scan_range_params_map;
244
245
    void add_using_brpc_stub(const TNetworkAddress& network_address,
246
0
                             std::shared_ptr<PBackendService_Stub> brpc_stub) {
247
0
        if (network_address.port == 0) {
248
0
            return;
249
0
        }
250
0
        std::lock_guard<std::mutex> lock(_brpc_stubs_mutex);
251
0
        if (!_using_brpc_stubs.contains(network_address)) {
252
0
            _using_brpc_stubs.emplace(network_address, brpc_stub);
253
0
        }
254
255
0
        DCHECK_EQ(_using_brpc_stubs[network_address].get(), brpc_stub.get());
256
0
    }
257
258
72.6k
    void set_ai_resources(std::map<std::string, TAIResource> ai_resources) {
259
72.6k
        _ai_resources =
260
72.6k
                std::make_shared<std::map<std::string, TAIResource>>(std::move(ai_resources));
261
72.6k
    }
262
263
63
    const std::shared_ptr<std::map<std::string, TAIResource>>& get_ai_resources() const {
264
63
        return _ai_resources;
265
63
    }
266
267
    std::unordered_map<TNetworkAddress, std::shared_ptr<PBackendService_Stub>>
268
0
    get_using_brpc_stubs() {
269
0
        std::lock_guard<std::mutex> lock(_brpc_stubs_mutex);
270
0
        return _using_brpc_stubs;
271
0
    }
272
273
0
    void set_low_memory_mode() {
274
        // will not return from low memory mode to non-low memory mode.
275
0
        _resource_ctx->task_controller()->set_low_memory_mode(true);
276
0
    }
277
906k
    bool low_memory_mode() { return _resource_ctx->task_controller()->low_memory_mode(); }
278
279
122k
    bool is_pure_load_task() {
280
122k
        return _query_source == QuerySource::STREAM_LOAD ||
281
122k
               _query_source == QuerySource::ROUTINE_LOAD ||
282
122k
               _query_source == QuerySource::GROUP_COMMIT_LOAD;
283
122k
    }
284
285
    void set_load_error_url(std::string error_url);
286
    std::string get_load_error_url();
287
    void set_first_error_msg(std::string error_msg);
288
    std::string get_first_error_msg();
289
290
    Status send_block_to_cte_scan(const TUniqueId& instance_id, int node_id,
291
                                  const google::protobuf::RepeatedPtrField<doris::PBlock>& pblocks,
292
                                  bool eos);
293
    void registe_cte_scan(const TUniqueId& instance_id, int node_id, RecCTEScanLocalState* scan);
294
    void deregiste_cte_scan(const TUniqueId& instance_id, int node_id);
295
296
0
    std::vector<int> get_fragment_ids() {
297
0
        std::vector<int> fragment_ids;
298
0
        for (const auto& it : _fragment_id_to_pipeline_ctx) {
299
0
            fragment_ids.push_back(it.first);
300
0
        }
301
0
        return fragment_ids;
302
0
    }
303
304
    Status reset_global_rf(const google::protobuf::RepeatedField<int32_t>& filter_ids);
305
306
private:
307
    friend class QueryTaskController;
308
309
    int _timeout_second;
310
    TUniqueId _query_id;
311
    ExecEnv* _exec_env = nullptr;
312
    MonotonicStopWatch _query_watcher;
313
    bool _is_nereids = false;
314
315
    std::shared_ptr<ResourceContext> _resource_ctx;
316
317
    void _init_resource_context();
318
    void _init_query_mem_tracker();
319
320
    std::unordered_map<int, RuntimePredicate> _runtime_predicates;
321
322
    std::unique_ptr<RuntimeFilterMgr> _runtime_filter_mgr;
323
    const TQueryOptions _query_options;
324
325
    // All pipeline tasks use the same query context to report status. So we need a `_exec_status`
326
    // to report the real message if failed.
327
    AtomicStatus _exec_status;
328
329
    doris::TaskScheduler* _task_scheduler = nullptr;
330
    ScannerScheduler* _scan_task_scheduler = nullptr;
331
    ScannerScheduler* _remote_scan_task_scheduler = nullptr;
332
    // This dependency indicates if the 2nd phase RPC received from FE.
333
    std::unique_ptr<Dependency> _execution_dependency;
334
    // This dependency indicates if memory is sufficient to execute.
335
    std::unique_ptr<Dependency> _memory_sufficient_dependency;
336
337
    // This shared ptr is never used. It is just a reference to hold the object.
338
    // There is a weak ptr in runtime filter manager to reference this object.
339
    std::shared_ptr<RuntimeFilterMergeControllerEntity> _merge_controller_handler;
340
341
    std::map<int, std::weak_ptr<PipelineFragmentContext>> _fragment_id_to_pipeline_ctx;
342
    std::mutex _pipeline_map_write_lock;
343
344
    std::mutex _profile_mutex;
345
    timespec _query_arrival_timestamp;
346
    // Distinguish the query source, for query that comes from fe, we will have some memory structure on FE to
347
    // help us manage the query.
348
    QuerySource _query_source;
349
350
    std::mutex _brpc_stubs_mutex;
351
    std::unordered_map<TNetworkAddress, std::shared_ptr<PBackendService_Stub>> _using_brpc_stubs;
352
353
    // when fragment of pipeline is closed, it will register its profile to this map by using add_fragment_profile
354
    // flatten profile of one fragment:
355
    // Pipeline 0
356
    //      PipelineTask 0
357
    //              Operator 1
358
    //              Operator 2
359
    //              Scanner
360
    //      PipelineTask 1
361
    //              Operator 1
362
    //              Operator 2
363
    //              Scanner
364
    // Pipeline 1
365
    //      PipelineTask 2
366
    //              Operator 3
367
    //      PipelineTask 3
368
    //              Operator 3
369
    // fragment_id -> list<profile>
370
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>> _profile_map;
371
    std::unordered_map<int, std::shared_ptr<TRuntimeProfileTree>> _load_channel_profile_map;
372
373
    std::shared_ptr<std::map<std::string, TAIResource>> _ai_resources;
374
375
    void _report_query_profile();
376
377
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>>
378
    _collect_realtime_query_profile();
379
380
    std::mutex _error_url_lock;
381
    std::string _load_error_url;
382
    std::string _first_error_msg;
383
384
    // file cache context holders
385
    std::vector<io::BlockFileCache::QueryFileCacheContextHolderPtr> _query_context_holders;
386
    // instance id + node id -> cte scan
387
    std::map<std::pair<TUniqueId, int>, RecCTEScanLocalState*> _cte_scan;
388
    std::mutex _cte_scan_lock;
389
390
public:
391
    // when fragment of pipeline is closed, it will register its profile to this map by using add_fragment_profile
392
    void add_fragment_profile(
393
            int fragment_id,
394
            const std::vector<std::shared_ptr<TRuntimeProfileTree>>& pipeline_profile,
395
            std::shared_ptr<TRuntimeProfileTree> load_channel_profile);
396
397
    TReportExecStatusParams get_realtime_exec_status();
398
399
122k
    bool enable_profile() const {
400
122k
        return _query_options.__isset.enable_profile && _query_options.enable_profile;
401
122k
    }
402
403
0
    timespec get_query_arrival_timestamp() const { return this->_query_arrival_timestamp; }
404
0
    QuerySource get_query_source() const { return this->_query_source; }
405
406
0
    const TQueryOptions get_query_options() const { return _query_options; }
407
};
408
409
} // namespace doris