Coverage Report

Created: 2026-11-03 11:22

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