Coverage Report

Created: 2026-03-19 05:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
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
19.3k
    ExecEnv* exec_env() const { return _exec_env; }
102
103
82.4k
    bool is_timeout(timespec now) const {
104
82.4k
        if (_timeout_second <= 0) {
105
0
            return false;
106
0
        }
107
82.4k
        return _query_watcher.elapsed_time_seconds(now) > _timeout_second;
108
82.4k
    }
109
110
573k
    bool is_single_backend_query() const { return _is_single_backend_query; }
111
112
457k
    void set_single_backend_query(bool is_single_backend_query) {
113
457k
        _is_single_backend_query = is_single_backend_query;
114
457k
    }
115
116
0
    int64_t get_remaining_query_time_seconds() const {
117
0
        timespec now;
118
0
        clock_gettime(CLOCK_MONOTONIC, &now);
119
0
        if (is_timeout(now)) {
120
0
            return -1;
121
0
        }
122
0
        int64_t elapsed_seconds = _query_watcher.elapsed_time_seconds(now);
123
0
        return _timeout_second - elapsed_seconds;
124
0
    }
125
126
    void set_ready_to_execute(Status reason);
127
128
58.2M
    [[nodiscard]] bool is_cancelled() const { return !_exec_status.ok(); }
129
130
    void cancel_all_pipeline_context(const Status& reason, int fragment_id = -1);
131
    std::string print_all_pipeline_context();
132
    void set_pipeline_context(const int fragment_id,
133
                              std::shared_ptr<PipelineFragmentContext> pip_ctx);
134
    void cancel(Status new_status, int fragment_id = -1);
135
136
925k
    [[nodiscard]] Status exec_status() { return _exec_status.status(); }
137
138
    void set_execution_dependency_ready();
139
140
    void set_memory_sufficient(bool sufficient);
141
142
    void set_ready_to_execute_only();
143
144
309k
    bool has_runtime_predicate(int source_node_id) {
145
309k
        return _runtime_predicates.contains(source_node_id);
146
309k
    }
147
148
63.8k
    RuntimePredicate& get_runtime_predicate(int source_node_id) {
149
63.8k
        DCHECK(has_runtime_predicate(source_node_id));
150
63.8k
        return _runtime_predicates.find(source_node_id)->second;
151
63.8k
    }
152
153
2.28k
    void init_runtime_predicates(const std::vector<TTopnFilterDesc>& topn_filter_descs) {
154
2.30k
        for (auto desc : topn_filter_descs) {
155
2.30k
            _runtime_predicates.try_emplace(desc.source_node_id, desc);
156
2.30k
        }
157
2.28k
    }
158
159
    Status set_workload_group(WorkloadGroupPtr& wg);
160
161
103k
    int execution_timeout() const {
162
103k
        return _query_options.__isset.execution_timeout ? _query_options.execution_timeout
163
18.4E
                                                        : _query_options.query_timeout;
164
103k
    }
165
166
3.44k
    int32_t runtime_filter_wait_time_ms() const {
167
3.44k
        return _query_options.runtime_filter_wait_time_ms;
168
3.44k
    }
169
170
0
    int be_exec_version() const {
171
0
        if (!_query_options.__isset.be_exec_version) {
172
0
            return 0;
173
0
        }
174
0
        return _query_options.be_exec_version;
175
0
    }
176
177
82.5k
    [[nodiscard]] int64_t get_fe_process_uuid() const {
178
82.5k
        return _query_options.__isset.fe_process_uuid ? _query_options.fe_process_uuid : 0;
179
82.5k
    }
180
181
1.90k
    bool ignore_runtime_filter_error() const {
182
1.90k
        return _query_options.__isset.ignore_runtime_filter_error
183
1.90k
                       ? _query_options.ignore_runtime_filter_error
184
1.90k
                       : false;
185
1.90k
    }
186
187
0
    bool enable_force_spill() const {
188
0
        return _query_options.__isset.enable_force_spill && _query_options.enable_force_spill;
189
0
    }
190
18.4M
    const TQueryOptions& query_options() const { return _query_options; }
191
8.58k
    bool should_be_shuffled_agg(int node_id) const {
192
8.58k
        return _query_options.__isset.shuffled_agg_ids &&
193
8.58k
               std::any_of(_query_options.shuffled_agg_ids.begin(),
194
8.58k
                           _query_options.shuffled_agg_ids.end(),
195
8.58k
                           [&](const int id) -> bool { return id == node_id; });
196
8.58k
    }
197
198
    // global runtime filter mgr, the runtime filter have remote target or
199
    // need local merge should regist here. before publish() or push_to_remote()
200
    // the runtime filter should do the local merge work
201
628k
    RuntimeFilterMgr* runtime_filter_mgr() { return _runtime_filter_mgr.get(); }
202
203
872k
    TUniqueId query_id() const { return _query_id; }
204
205
628k
    ScannerScheduler* get_scan_scheduler() { return _scan_task_scheduler; }
206
207
33.8k
    ScannerScheduler* get_remote_scan_scheduler() { return _remote_scan_task_scheduler; }
208
209
2.35M
    Dependency* get_execution_dependency() { return _execution_dependency.get(); }
210
3.92M
    Dependency* get_memory_sufficient_dependency() { return _memory_sufficient_dependency.get(); }
211
212
    doris::TaskScheduler* get_pipe_exec_scheduler();
213
214
    void set_merge_controller_handler(
215
295k
            std::shared_ptr<RuntimeFilterMergeControllerEntity>& handler) {
216
295k
        _merge_controller_handler = handler;
217
295k
    }
218
7.81k
    std::shared_ptr<RuntimeFilterMergeControllerEntity> get_merge_controller_handler() const {
219
7.81k
        return _merge_controller_handler;
220
7.81k
    }
221
222
15.2M
    bool is_nereids() const { return _is_nereids; }
223
252k
    std::shared_ptr<ScannerMemShareArbitrator> mem_arb() const { return _mem_arb; }
224
225
7.60M
    WorkloadGroupPtr workload_group() const { return _resource_ctx->workload_group(); }
226
14.9M
    std::shared_ptr<MemTrackerLimiter> query_mem_tracker() const {
227
14.9M
        DCHECK(_resource_ctx->memory_context()->mem_tracker() != nullptr);
228
14.9M
        return _resource_ctx->memory_context()->mem_tracker();
229
14.9M
    }
230
231
1.48M
    int32_t get_slot_count() const {
232
1.48M
        return _query_options.__isset.query_slot_count ? _query_options.query_slot_count : 1;
233
1.48M
    }
234
235
    DescriptorTbl* desc_tbl = nullptr;
236
    bool set_rsc_info = false;
237
    std::string user;
238
    std::string group;
239
    TNetworkAddress coord_addr;
240
    TNetworkAddress current_connect_fe;
241
    TQueryGlobals query_globals;
242
1.24k
    const TQueryGlobals get_query_globals() const { return query_globals; }
243
244
    ObjectPool obj_pool;
245
246
43.6M
    std::shared_ptr<ResourceContext> resource_ctx() { return _resource_ctx; }
247
248
    // plan node id -> TFileScanRangeParams
249
    // only for file scan node
250
    std::map<int, TFileScanRangeParams> file_scan_range_params_map;
251
252
    void add_using_brpc_stub(const TNetworkAddress& network_address,
253
2.87M
                             std::shared_ptr<PBackendService_Stub> brpc_stub) {
254
2.87M
        if (network_address.port == 0) {
255
4.06k
            return;
256
4.06k
        }
257
2.86M
        std::lock_guard<std::mutex> lock(_brpc_stubs_mutex);
258
2.86M
        if (!_using_brpc_stubs.contains(network_address)) {
259
55.3k
            _using_brpc_stubs.emplace(network_address, brpc_stub);
260
55.3k
        }
261
262
2.86M
        DCHECK_EQ(_using_brpc_stubs[network_address].get(), brpc_stub.get());
263
2.86M
    }
264
265
367k
    void set_ai_resources(std::map<std::string, TAIResource> ai_resources) {
266
367k
        _ai_resources =
267
367k
                std::make_shared<std::map<std::string, TAIResource>>(std::move(ai_resources));
268
367k
    }
269
270
63
    const std::shared_ptr<std::map<std::string, TAIResource>>& get_ai_resources() const {
271
63
        return _ai_resources;
272
63
    }
273
274
    std::unordered_map<TNetworkAddress, std::shared_ptr<PBackendService_Stub>>
275
66.3k
    get_using_brpc_stubs() {
276
66.3k
        std::lock_guard<std::mutex> lock(_brpc_stubs_mutex);
277
66.3k
        return _using_brpc_stubs;
278
66.3k
    }
279
280
0
    void set_low_memory_mode() {
281
        // will not return from low memory mode to non-low memory mode.
282
0
        _resource_ctx->task_controller()->set_low_memory_mode(true);
283
0
    }
284
18.3M
    bool low_memory_mode() { return _resource_ctx->task_controller()->low_memory_mode(); }
285
286
3.56M
    bool is_pure_load_task() {
287
3.56M
        return _query_source == QuerySource::STREAM_LOAD ||
288
3.56M
               _query_source == QuerySource::ROUTINE_LOAD ||
289
3.56M
               _query_source == QuerySource::GROUP_COMMIT_LOAD;
290
3.56M
    }
291
292
    void set_load_error_url(std::string error_url);
293
    std::string get_load_error_url();
294
    void set_first_error_msg(std::string error_msg);
295
    std::string get_first_error_msg();
296
297
    Status send_block_to_cte_scan(const TUniqueId& instance_id, int node_id,
298
                                  const google::protobuf::RepeatedPtrField<doris::PBlock>& pblocks,
299
                                  bool eos);
300
    void registe_cte_scan(const TUniqueId& instance_id, int node_id, RecCTEScanLocalState* scan);
301
    void deregiste_cte_scan(const TUniqueId& instance_id, int node_id);
302
303
0
    std::vector<int> get_fragment_ids() {
304
0
        std::vector<int> fragment_ids;
305
0
        for (const auto& it : _fragment_id_to_pipeline_ctx) {
306
0
            fragment_ids.push_back(it.first);
307
0
        }
308
0
        return fragment_ids;
309
0
    }
310
311
    Status reset_global_rf(const google::protobuf::RepeatedField<int32_t>& filter_ids);
312
313
private:
314
    friend class QueryTaskController;
315
316
    int _timeout_second;
317
    TUniqueId _query_id;
318
    ExecEnv* _exec_env = nullptr;
319
    MonotonicStopWatch _query_watcher;
320
    bool _is_nereids = false;
321
322
    std::shared_ptr<ResourceContext> _resource_ctx;
323
324
    void _init_resource_context();
325
    void _init_query_mem_tracker();
326
327
    std::unordered_map<int, RuntimePredicate> _runtime_predicates;
328
329
    std::unique_ptr<RuntimeFilterMgr> _runtime_filter_mgr;
330
    const TQueryOptions _query_options;
331
332
    // All pipeline tasks use the same query context to report status. So we need a `_exec_status`
333
    // to report the real message if failed.
334
    AtomicStatus _exec_status;
335
336
    doris::TaskScheduler* _task_scheduler = nullptr;
337
    ScannerScheduler* _scan_task_scheduler = nullptr;
338
    ScannerScheduler* _remote_scan_task_scheduler = nullptr;
339
    // This dependency indicates if the 2nd phase RPC received from FE.
340
    std::unique_ptr<Dependency> _execution_dependency;
341
    // This dependency indicates if memory is sufficient to execute.
342
    std::unique_ptr<Dependency> _memory_sufficient_dependency;
343
344
    // This shared ptr is never used. It is just a reference to hold the object.
345
    // There is a weak ptr in runtime filter manager to reference this object.
346
    std::shared_ptr<RuntimeFilterMergeControllerEntity> _merge_controller_handler;
347
348
    std::map<int, std::weak_ptr<PipelineFragmentContext>> _fragment_id_to_pipeline_ctx;
349
    std::mutex _pipeline_map_write_lock;
350
351
    std::mutex _profile_mutex;
352
    timespec _query_arrival_timestamp;
353
    // Distinguish the query source, for query that comes from fe, we will have some memory structure on FE to
354
    // help us manage the query.
355
    QuerySource _query_source;
356
357
    std::mutex _brpc_stubs_mutex;
358
    std::unordered_map<TNetworkAddress, std::shared_ptr<PBackendService_Stub>> _using_brpc_stubs;
359
360
    // when fragment of pipeline is closed, it will register its profile to this map by using add_fragment_profile
361
    // flatten profile of one fragment:
362
    // Pipeline 0
363
    //      PipelineTask 0
364
    //              Operator 1
365
    //              Operator 2
366
    //              Scanner
367
    //      PipelineTask 1
368
    //              Operator 1
369
    //              Operator 2
370
    //              Scanner
371
    // Pipeline 1
372
    //      PipelineTask 2
373
    //              Operator 3
374
    //      PipelineTask 3
375
    //              Operator 3
376
    // fragment_id -> list<profile>
377
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>> _profile_map;
378
    std::unordered_map<int, std::shared_ptr<TRuntimeProfileTree>> _load_channel_profile_map;
379
380
    std::shared_ptr<std::map<std::string, TAIResource>> _ai_resources;
381
382
    void _report_query_profile();
383
384
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>>
385
    _collect_realtime_query_profile();
386
387
    std::mutex _error_url_lock;
388
    std::string _load_error_url;
389
    std::string _first_error_msg;
390
391
    bool _is_single_backend_query = false;
392
393
    // file cache context holders
394
    std::vector<io::BlockFileCache::QueryFileCacheContextHolderPtr> _query_context_holders;
395
    // instance id + node id -> cte scan
396
    std::map<std::pair<TUniqueId, int>, RecCTEScanLocalState*> _cte_scan;
397
    std::mutex _cte_scan_lock;
398
    std::shared_ptr<ScannerMemShareArbitrator> _mem_arb = nullptr;
399
400
public:
401
    // when fragment of pipeline is closed, it will register its profile to this map by using add_fragment_profile
402
    void add_fragment_profile(
403
            int fragment_id,
404
            const std::vector<std::shared_ptr<TRuntimeProfileTree>>& pipeline_profile,
405
            std::shared_ptr<TRuntimeProfileTree> load_channel_profile);
406
407
    TReportExecStatusParams get_realtime_exec_status();
408
409
879k
    bool enable_profile() const {
410
879k
        return _query_options.__isset.enable_profile && _query_options.enable_profile;
411
879k
    }
412
413
0
    timespec get_query_arrival_timestamp() const { return this->_query_arrival_timestamp; }
414
9.23k
    QuerySource get_query_source() const { return this->_query_source; }
415
416
917k
    const TQueryOptions get_query_options() const { return _query_options; }
417
};
418
419
} // namespace doris