Coverage Report

Created: 2026-10-15 07:33

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