Coverage Report

Created: 2026-09-02 04:14

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