Coverage Report

Created: 2026-10-20 12:15

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