Coverage Report

Created: 2026-08-15 01:19

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