Coverage Report

Created: 2026-03-05 19:59

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