Coverage Report

Created: 2026-09-08 15:57

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