Coverage Report

Created: 2025-03-12 11:32

/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
    RuntimeProfile* profile = nullptr;
54
    RuntimeProfile* load_channel_profile = nullptr;
55
    bool done;
56
    TNetworkAddress coord_addr;
57
    TUniqueId query_id;
58
    int fragment_id;
59
    TUniqueId fragment_instance_id;
60
    int backend_num;
61
    RuntimeState* runtime_state;
62
    std::function<void(const Status&)> cancel_fn;
63
};
64
65
enum class QuerySource {
66
    INTERNAL_FRONTEND,
67
    STREAM_LOAD,
68
    GROUP_COMMIT_LOAD,
69
    ROUTINE_LOAD,
70
    EXTERNAL_CONNECTOR
71
};
72
73
const std::string toString(QuerySource query_source);
74
75
// Save the common components of fragments in a query.
76
// Some components like DescriptorTbl may be very large
77
// that will slow down each execution of fragments when DeSer them every time.
78
class DescriptorTbl;
79
class QueryContext {
80
    ENABLE_FACTORY_CREATOR(QueryContext);
81
82
public:
83
    QueryContext(TUniqueId query_id, ExecEnv* exec_env, const TQueryOptions& query_options,
84
                 TNetworkAddress coord_addr, bool is_pipeline, bool is_nereids,
85
                 TNetworkAddress current_connect_fe, QuerySource query_type);
86
87
    ~QueryContext();
88
89
0
    ExecEnv* exec_env() { return _exec_env; }
90
91
0
    bool is_timeout(timespec now) const {
92
0
        if (_timeout_second <= 0) {
93
0
            return false;
94
0
        }
95
0
        return _query_watcher.elapsed_time_seconds(now) > _timeout_second;
96
0
    }
97
98
0
    void set_thread_token(int concurrency, bool is_serial) {
99
0
        _thread_token = _exec_env->scanner_scheduler()->new_limited_scan_pool_token(
100
0
                is_serial ? ThreadPool::ExecutionMode::SERIAL
101
0
                          : ThreadPool::ExecutionMode::CONCURRENT,
102
0
                concurrency);
103
0
    }
104
105
0
    ThreadPoolToken* get_token() { return _thread_token.get(); }
106
107
    void set_ready_to_execute(Status reason);
108
109
0
    [[nodiscard]] bool is_cancelled() const { return !_exec_status.ok(); }
110
111
    void cancel_all_pipeline_context(const Status& reason, int fragment_id = -1);
112
    std::string print_all_pipeline_context();
113
    void set_pipeline_context(const int fragment_id,
114
                              std::shared_ptr<pipeline::PipelineFragmentContext> pip_ctx);
115
    void cancel(Status new_status, int fragment_id = -1);
116
117
0
    [[nodiscard]] Status exec_status() { return _exec_status.status(); }
118
119
    void set_execution_dependency_ready();
120
121
    void set_ready_to_execute_only();
122
123
0
    std::shared_ptr<vectorized::SharedHashTableController> get_shared_hash_table_controller() {
124
0
        return _shared_hash_table_controller;
125
0
    }
126
127
0
    bool has_runtime_predicate(int source_node_id) {
128
0
        return _runtime_predicates.contains(source_node_id);
129
0
    }
130
131
0
    vectorized::RuntimePredicate& get_runtime_predicate(int source_node_id) {
132
0
        DCHECK(has_runtime_predicate(source_node_id));
133
0
        return _runtime_predicates.find(source_node_id)->second;
134
0
    }
135
136
0
    void init_runtime_predicates(const std::vector<TTopnFilterDesc>& topn_filter_descs) {
137
0
        for (auto desc : topn_filter_descs) {
138
0
            _runtime_predicates.try_emplace(desc.source_node_id, desc);
139
0
        }
140
0
    }
141
142
    void set_workload_group(WorkloadGroupPtr& tg);
143
144
0
    int execution_timeout() const {
145
0
        return _query_options.__isset.execution_timeout ? _query_options.execution_timeout
146
0
                                                        : _query_options.query_timeout;
147
0
    }
148
149
0
    int32_t runtime_filter_wait_time_ms() const {
150
0
        return _query_options.runtime_filter_wait_time_ms;
151
0
    }
152
153
0
    bool runtime_filter_wait_infinitely() const {
154
0
        return _query_options.__isset.runtime_filter_wait_infinitely &&
155
0
               _query_options.runtime_filter_wait_infinitely;
156
0
    }
157
158
0
    int be_exec_version() const {
159
0
        if (!_query_options.__isset.be_exec_version) {
160
0
            return 0;
161
0
        }
162
0
        return _query_options.be_exec_version;
163
0
    }
164
165
0
    [[nodiscard]] int64_t get_fe_process_uuid() const {
166
0
        return _query_options.__isset.fe_process_uuid ? _query_options.fe_process_uuid : 0;
167
0
    }
168
169
0
    bool ignore_runtime_filter_error() const {
170
0
        return _query_options.__isset.ignore_runtime_filter_error
171
0
                       ? _query_options.ignore_runtime_filter_error
172
0
                       : false;
173
0
    }
174
175
    // global runtime filter mgr, the runtime filter have remote target or
176
    // need local merge should regist here. before publish() or push_to_remote()
177
    // the runtime filter should do the local merge work
178
0
    RuntimeFilterMgr* runtime_filter_mgr() { return _runtime_filter_mgr.get(); }
179
180
0
    TUniqueId query_id() const { return _query_id; }
181
182
0
    vectorized::SimplifiedScanScheduler* get_scan_scheduler() { return _scan_task_scheduler; }
183
184
0
    vectorized::SimplifiedScanScheduler* get_remote_scan_scheduler() {
185
0
        return _remote_scan_task_scheduler;
186
0
    }
187
188
0
    pipeline::Dependency* get_execution_dependency() { return _execution_dependency.get(); }
189
190
    void register_query_statistics(std::shared_ptr<QueryStatistics> qs);
191
192
    std::shared_ptr<QueryStatistics> get_query_statistics();
193
194
    void register_memory_statistics();
195
196
    void register_cpu_statistics();
197
198
0
    std::shared_ptr<QueryStatistics> get_cpu_statistics() { return _cpu_statistics; }
199
200
    doris::pipeline::TaskScheduler* get_pipe_exec_scheduler();
201
202
    ThreadPool* get_memtable_flush_pool();
203
204
0
    int64_t mem_limit() const { return _bytes_limit; }
205
206
    void set_merge_controller_handler(
207
0
            std::shared_ptr<RuntimeFilterMergeControllerEntity>& handler) {
208
0
        _merge_controller_handler = handler;
209
0
    }
210
211
0
    bool is_nereids() const { return _is_nereids; }
212
213
0
    WorkloadGroupPtr workload_group() const { return _workload_group; }
214
215
0
    void inc_running_big_mem_op_num() {
216
0
        _running_big_mem_op_num.fetch_add(1, std::memory_order_relaxed);
217
0
    }
218
0
    void dec_running_big_mem_op_num() {
219
0
        _running_big_mem_op_num.fetch_sub(1, std::memory_order_relaxed);
220
0
    }
221
0
    int32_t get_running_big_mem_op_num() {
222
0
        return _running_big_mem_op_num.load(std::memory_order_relaxed);
223
0
    }
224
225
0
    void set_spill_threshold(int64_t spill_threshold) { _spill_threshold = spill_threshold; }
226
0
    int64_t spill_threshold() { return _spill_threshold; }
227
    DescriptorTbl* desc_tbl = nullptr;
228
    bool set_rsc_info = false;
229
    std::string user;
230
    std::string group;
231
    TNetworkAddress coord_addr;
232
    TNetworkAddress current_connect_fe;
233
    TQueryGlobals query_globals;
234
235
    ObjectPool obj_pool;
236
    // MemTracker that is shared by all fragment instances running on this host.
237
    std::shared_ptr<MemTrackerLimiter> query_mem_tracker;
238
239
    std::vector<TUniqueId> fragment_instance_ids;
240
241
    // plan node id -> TFileScanRangeParams
242
    // only for file scan node
243
    std::map<int, TFileScanRangeParams> file_scan_range_params_map;
244
245
0
    void update_cpu_time(int64_t delta_cpu_time) {
246
0
        if (_workload_group != nullptr) {
247
0
            _workload_group->update_cpu_time(delta_cpu_time);
248
0
        }
249
0
    }
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
public:
329
    // when fragment of pipeline is closed, it will register its profile to this map by using add_fragment_profile
330
    void add_fragment_profile(
331
            int fragment_id,
332
            const std::vector<std::shared_ptr<TRuntimeProfileTree>>& pipeline_profile,
333
            std::shared_ptr<TRuntimeProfileTree> load_channel_profile);
334
335
    TReportExecStatusParams get_realtime_exec_status() const;
336
337
0
    bool enable_profile() const {
338
0
        return _query_options.__isset.enable_profile && _query_options.enable_profile;
339
0
    }
340
341
0
    timespec get_query_arrival_timestamp() const { return this->_query_arrival_timestamp; }
342
0
    QuerySource get_query_source() const { return this->_query_source; }
343
};
344
345
} // namespace doris