Coverage Report

Created: 2025-04-11 23:22

/root/doris/be/src/runtime/query_context.h
Line
Count
Source (jump to first uncovered line)
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
24
#include <atomic>
25
#include <memory>
26
#include <mutex>
27
#include <string>
28
#include <unordered_map>
29
30
#include "common/config.h"
31
#include "common/factory_creator.h"
32
#include "common/object_pool.h"
33
#include "runtime/exec_env.h"
34
#include "runtime/memory/mem_tracker_limiter.h"
35
#include "runtime/query_statistics.h"
36
#include "runtime/runtime_filter_mgr.h"
37
#include "runtime/runtime_predicate.h"
38
#include "util/hash_util.hpp"
39
#include "util/threadpool.h"
40
#include "vec/exec/scan/scanner_scheduler.h"
41
#include "vec/runtime/shared_hash_table_controller.h"
42
#include "workload_group/workload_group.h"
43
44
namespace doris {
45
46
namespace pipeline {
47
class PipelineFragmentContext;
48
} // namespace pipeline
49
50
struct ReportStatusRequest {
51
    const Status status;
52
    std::vector<RuntimeState*> runtime_states;
53
    bool done;
54
    TNetworkAddress coord_addr;
55
    TUniqueId query_id;
56
    int fragment_id;
57
    TUniqueId fragment_instance_id;
58
    int backend_num;
59
    RuntimeState* runtime_state;
60
    std::string load_error_url;
61
    std::function<void(const Status&)> cancel_fn;
62
};
63
64
enum class QuerySource {
65
    INTERNAL_FRONTEND,
66
    STREAM_LOAD,
67
    GROUP_COMMIT_LOAD,
68
    ROUTINE_LOAD,
69
    EXTERNAL_CONNECTOR
70
};
71
72
const std::string toString(QuerySource query_source);
73
74
// Save the common components of fragments in a query.
75
// Some components like DescriptorTbl may be very large
76
// that will slow down each execution of fragments when DeSer them every time.
77
class DescriptorTbl;
78
class QueryContext {
79
    ENABLE_FACTORY_CREATOR(QueryContext);
80
81
public:
82
    QueryContext(TUniqueId query_id, ExecEnv* exec_env, const TQueryOptions& query_options,
83
                 TNetworkAddress coord_addr, bool is_pipeline, bool is_nereids,
84
                 TNetworkAddress current_connect_fe, QuerySource query_type);
85
86
    ~QueryContext();
87
88
0
    ExecEnv* exec_env() { return _exec_env; }
89
90
0
    bool is_timeout(timespec now) const {
91
0
        if (_timeout_second <= 0) {
92
0
            return false;
93
0
        }
94
0
        return _query_watcher.elapsed_time_seconds(now) > _timeout_second;
95
0
    }
96
97
0
    void set_thread_token(int concurrency, bool is_serial) {
98
0
        _thread_token = _exec_env->scanner_scheduler()->new_limited_scan_pool_token(
99
0
                is_serial ? ThreadPool::ExecutionMode::SERIAL
100
0
                          : ThreadPool::ExecutionMode::CONCURRENT,
101
0
                concurrency);
102
0
    }
103
104
0
    ThreadPoolToken* get_token() { return _thread_token.get(); }
105
106
    void set_ready_to_execute(Status reason);
107
108
0
    [[nodiscard]] bool is_cancelled() const { return !_exec_status.ok(); }
109
110
    void cancel_all_pipeline_context(const Status& reason, int fragment_id = -1);
111
    std::string print_all_pipeline_context();
112
    void set_pipeline_context(const int fragment_id,
113
                              std::shared_ptr<pipeline::PipelineFragmentContext> pip_ctx);
114
    void cancel(Status new_status, int fragment_id = -1);
115
116
0
    [[nodiscard]] Status exec_status() { return _exec_status.status(); }
117
118
    void set_execution_dependency_ready();
119
120
    void set_ready_to_execute_only();
121
122
0
    std::shared_ptr<vectorized::SharedHashTableController> get_shared_hash_table_controller() {
123
0
        return _shared_hash_table_controller;
124
0
    }
125
126
0
    bool has_runtime_predicate(int source_node_id) {
127
0
        return _runtime_predicates.contains(source_node_id);
128
0
    }
129
130
0
    vectorized::RuntimePredicate& get_runtime_predicate(int source_node_id) {
131
0
        DCHECK(has_runtime_predicate(source_node_id));
132
0
        return _runtime_predicates.find(source_node_id)->second;
133
0
    }
134
135
0
    void init_runtime_predicates(const std::vector<TTopnFilterDesc>& topn_filter_descs) {
136
0
        for (auto desc : topn_filter_descs) {
137
0
            _runtime_predicates.try_emplace(desc.source_node_id, desc);
138
0
        }
139
0
    }
140
141
    void set_workload_group(WorkloadGroupPtr& tg);
142
143
0
    int execution_timeout() const {
144
0
        return _query_options.__isset.execution_timeout ? _query_options.execution_timeout
145
0
                                                        : _query_options.query_timeout;
146
0
    }
147
148
0
    int32_t runtime_filter_wait_time_ms() const {
149
0
        return _query_options.runtime_filter_wait_time_ms;
150
0
    }
151
152
0
    bool runtime_filter_wait_infinitely() const {
153
0
        return _query_options.__isset.runtime_filter_wait_infinitely &&
154
0
               _query_options.runtime_filter_wait_infinitely;
155
0
    }
156
157
0
    int be_exec_version() const {
158
0
        if (!_query_options.__isset.be_exec_version) {
159
0
            return 0;
160
0
        }
161
0
        return _query_options.be_exec_version;
162
0
    }
163
164
0
    [[nodiscard]] int64_t get_fe_process_uuid() const {
165
0
        return _query_options.__isset.fe_process_uuid ? _query_options.fe_process_uuid : 0;
166
0
    }
167
168
0
    bool ignore_runtime_filter_error() const {
169
0
        return _query_options.__isset.ignore_runtime_filter_error
170
0
                       ? _query_options.ignore_runtime_filter_error
171
0
                       : false;
172
0
    }
173
174
    // global runtime filter mgr, the runtime filter have remote target or
175
    // need local merge should regist here. before publish() or push_to_remote()
176
    // the runtime filter should do the local merge work
177
0
    RuntimeFilterMgr* runtime_filter_mgr() { return _runtime_filter_mgr.get(); }
178
179
0
    TUniqueId query_id() const { return _query_id; }
180
181
0
    vectorized::SimplifiedScanScheduler* get_scan_scheduler() { return _scan_task_scheduler; }
182
183
0
    vectorized::SimplifiedScanScheduler* get_remote_scan_scheduler() {
184
0
        return _remote_scan_task_scheduler;
185
0
    }
186
187
0
    pipeline::Dependency* get_execution_dependency() { return _execution_dependency.get(); }
188
189
    void register_query_statistics(std::shared_ptr<QueryStatistics> qs);
190
191
    std::shared_ptr<QueryStatistics> get_query_statistics();
192
193
    void register_memory_statistics();
194
195
    void register_cpu_statistics();
196
197
0
    std::shared_ptr<QueryStatistics> get_cpu_statistics() { return _cpu_statistics; }
198
199
    doris::pipeline::TaskScheduler* get_pipe_exec_scheduler();
200
201
    ThreadPool* get_memtable_flush_pool();
202
203
0
    int64_t mem_limit() const { return _bytes_limit; }
204
205
    void set_merge_controller_handler(
206
0
            std::shared_ptr<RuntimeFilterMergeControllerEntity>& handler) {
207
0
        _merge_controller_handler = handler;
208
0
    }
209
210
0
    bool is_nereids() const { return _is_nereids; }
211
212
0
    WorkloadGroupPtr workload_group() const { return _workload_group; }
213
214
0
    void inc_running_big_mem_op_num() {
215
0
        _running_big_mem_op_num.fetch_add(1, std::memory_order_relaxed);
216
0
    }
217
0
    void dec_running_big_mem_op_num() {
218
0
        _running_big_mem_op_num.fetch_sub(1, std::memory_order_relaxed);
219
0
    }
220
0
    int32_t get_running_big_mem_op_num() {
221
0
        return _running_big_mem_op_num.load(std::memory_order_relaxed);
222
0
    }
223
224
0
    void set_spill_threshold(int64_t spill_threshold) { _spill_threshold = spill_threshold; }
225
0
    int64_t spill_threshold() { return _spill_threshold; }
226
    DescriptorTbl* desc_tbl = nullptr;
227
    bool set_rsc_info = false;
228
    std::string user;
229
    std::string group;
230
    TNetworkAddress coord_addr;
231
    TNetworkAddress current_connect_fe;
232
    TQueryGlobals query_globals;
233
234
    ObjectPool obj_pool;
235
    // MemTracker that is shared by all fragment instances running on this host.
236
    std::shared_ptr<MemTrackerLimiter> query_mem_tracker;
237
238
    // plan node id -> TFileScanRangeParams
239
    // only for file scan node
240
    std::map<int, TFileScanRangeParams> file_scan_range_params_map;
241
242
0
    void update_cpu_time(int64_t delta_cpu_time) {
243
0
        if (_workload_group != nullptr) {
244
0
            _workload_group->update_cpu_time(delta_cpu_time);
245
0
        }
246
0
    }
247
248
    void set_load_error_url(std::string error_url);
249
    std::string get_load_error_url();
250
251
private:
252
    int _timeout_second;
253
    TUniqueId _query_id;
254
    ExecEnv* _exec_env = nullptr;
255
    MonotonicStopWatch _query_watcher;
256
    int64_t _bytes_limit = 0;
257
    bool _is_pipeline = false;
258
    bool _is_nereids = false;
259
    std::atomic<int> _running_big_mem_op_num = 0;
260
261
    // A token used to submit olap scanner to the "_limited_scan_thread_pool",
262
    // This thread pool token is created from "_limited_scan_thread_pool" from exec env.
263
    // And will be shared by all instances of this query.
264
    // So that we can control the max thread that a query can be used to execute.
265
    // If this token is not set, the scanner will be executed in "_scan_thread_pool" in exec env.
266
    std::unique_ptr<ThreadPoolToken> _thread_token;
267
268
    void _init_query_mem_tracker();
269
270
    std::shared_ptr<vectorized::SharedHashTableController> _shared_hash_table_controller;
271
    std::unordered_map<int, vectorized::RuntimePredicate> _runtime_predicates;
272
273
    WorkloadGroupPtr _workload_group = nullptr;
274
    std::unique_ptr<RuntimeFilterMgr> _runtime_filter_mgr;
275
    const TQueryOptions _query_options;
276
277
    // All pipeline tasks use the same query context to report status. So we need a `_exec_status`
278
    // to report the real message if failed.
279
    AtomicStatus _exec_status;
280
281
    doris::pipeline::TaskScheduler* _task_scheduler = nullptr;
282
    vectorized::SimplifiedScanScheduler* _scan_task_scheduler = nullptr;
283
    ThreadPool* _memtable_flush_pool = nullptr;
284
    vectorized::SimplifiedScanScheduler* _remote_scan_task_scheduler = nullptr;
285
    std::unique_ptr<pipeline::Dependency> _execution_dependency;
286
287
    std::shared_ptr<QueryStatistics> _cpu_statistics = nullptr;
288
    // This shared ptr is never used. It is just a reference to hold the object.
289
    // There is a weak ptr in runtime filter manager to reference this object.
290
    std::shared_ptr<RuntimeFilterMergeControllerEntity> _merge_controller_handler;
291
292
    std::map<int, std::weak_ptr<pipeline::PipelineFragmentContext>> _fragment_id_to_pipeline_ctx;
293
    std::mutex _pipeline_map_write_lock;
294
295
    std::atomic<int64_t> _spill_threshold {0};
296
297
    std::mutex _profile_mutex;
298
    timespec _query_arrival_timestamp;
299
    // Distinguish the query source, for query that comes from fe, we will have some memory structure on FE to
300
    // help us manage the query.
301
    QuerySource _query_source;
302
303
    // when fragment of pipeline is closed, it will register its profile to this map by using add_fragment_profile
304
    // flatten profile of one fragment:
305
    // Pipeline 0
306
    //      PipelineTask 0
307
    //              Operator 1
308
    //              Operator 2
309
    //              Scanner
310
    //      PipelineTask 1
311
    //              Operator 1
312
    //              Operator 2
313
    //              Scanner
314
    // Pipeline 1
315
    //      PipelineTask 2
316
    //              Operator 3
317
    //      PipelineTask 3
318
    //              Operator 3
319
    // fragment_id -> list<profile>
320
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>> _profile_map;
321
    std::unordered_map<int, std::shared_ptr<TRuntimeProfileTree>> _load_channel_profile_map;
322
323
    void _report_query_profile();
324
325
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>>
326
    _collect_realtime_query_profile() const;
327
328
    std::mutex _error_url_lock;
329
    std::string _load_error_url;
330
331
public:
332
    // when fragment of pipeline is closed, it will register its profile to this map by using add_fragment_profile
333
    void add_fragment_profile(
334
            int fragment_id,
335
            const std::vector<std::shared_ptr<TRuntimeProfileTree>>& pipeline_profile,
336
            std::shared_ptr<TRuntimeProfileTree> load_channel_profile);
337
338
    TReportExecStatusParams get_realtime_exec_status() const;
339
340
0
    bool enable_profile() const {
341
0
        return _query_options.__isset.enable_profile && _query_options.enable_profile;
342
0
    }
343
344
0
    timespec get_query_arrival_timestamp() const { return this->_query_arrival_timestamp; }
345
0
    QuerySource get_query_source() const { return this->_query_source; }
346
};
347
348
} // namespace doris