Coverage Report

Created: 2026-07-13 07:44

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