Coverage Report

Created: 2026-07-15 10:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/query_context.cpp
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
#include "runtime/query_context.h"
19
20
#include <fmt/core.h>
21
#include <gen_cpp/FrontendService_types.h>
22
#include <gen_cpp/RuntimeProfile_types.h>
23
#include <gen_cpp/Types_types.h>
24
#include <glog/logging.h>
25
26
#include <algorithm>
27
#include <memory>
28
#include <mutex>
29
#include <utility>
30
#include <vector>
31
32
#include "cloud/config.h"
33
#include "common/logging.h"
34
#include "common/status.h"
35
#include "exec/operator/rec_cte_scan_operator.h"
36
#include "exec/pipeline/dependency.h"
37
#include "exec/pipeline/pipeline_fragment_context.h"
38
#include "exec/runtime_filter/runtime_filter_definitions.h"
39
#include "exec/spill/spill_file_manager.h"
40
#include "io/cache/remote_scan_cache_write_limiter.h"
41
#include "runtime/exec_env.h"
42
#include "runtime/fragment_mgr.h"
43
#include "runtime/memory/heap_profiler.h"
44
#include "runtime/runtime_query_statistics_mgr.h"
45
#include "runtime/runtime_state.h"
46
#include "runtime/thread_context.h"
47
#include "runtime/workload_group/workload_group_manager.h"
48
#include "runtime/workload_management/query_task_controller.h"
49
#include "storage/olap_common.h"
50
#include "util/mem_info.h"
51
#include "util/uid_util.h"
52
53
namespace doris {
54
55
class DelayReleaseToken : public Runnable {
56
    ENABLE_FACTORY_CREATOR(DelayReleaseToken);
57
58
public:
59
0
    DelayReleaseToken(std::unique_ptr<ThreadPoolToken>&& token) { token_ = std::move(token); }
60
    ~DelayReleaseToken() override = default;
61
0
    void run() override {}
62
    std::unique_ptr<ThreadPoolToken> token_;
63
};
64
65
0
const std::string toString(QuerySource queryType) {
66
0
    switch (queryType) {
67
0
    case QuerySource::INTERNAL_FRONTEND:
68
0
        return "INTERNAL_FRONTEND";
69
0
    case QuerySource::STREAM_LOAD:
70
0
        return "STREAM_LOAD";
71
0
    case QuerySource::GROUP_COMMIT_LOAD:
72
0
        return "EXTERNAL_QUERY";
73
0
    case QuerySource::ROUTINE_LOAD:
74
0
        return "ROUTINE_LOAD";
75
0
    case QuerySource::EXTERNAL_CONNECTOR:
76
0
        return "EXTERNAL_CONNECTOR";
77
0
    case QuerySource::EXTERNAL_FRONTEND:
78
0
        return "EXTERNAL_FRONTEND";
79
0
    default:
80
0
        return "UNKNOWN";
81
0
    }
82
0
}
83
84
std::shared_ptr<QueryContext> QueryContext::create(TUniqueId query_id, ExecEnv* exec_env,
85
                                                   const TQueryOptions& query_options,
86
                                                   TNetworkAddress coord_addr, bool is_nereids,
87
                                                   TNetworkAddress current_connect_fe,
88
302k
                                                   QuerySource query_type) {
89
302k
    auto ctx = QueryContext::create_shared(query_id, exec_env, query_options, coord_addr,
90
302k
                                           is_nereids, current_connect_fe, query_type);
91
302k
    ctx->init_query_task_controller();
92
302k
    return ctx;
93
302k
}
94
95
QueryContext::QueryContext(TUniqueId query_id, ExecEnv* exec_env,
96
                           const TQueryOptions& query_options, TNetworkAddress coord_addr,
97
                           bool is_nereids, TNetworkAddress current_connect_fe,
98
                           QuerySource query_source)
99
425k
        : _timeout_second(-1),
100
425k
          _query_id(std::move(query_id)),
101
425k
          _exec_env(exec_env),
102
425k
          _is_nereids(is_nereids),
103
425k
          _query_options(query_options),
104
425k
          _query_source(query_source) {
105
425k
    _init_resource_context();
106
425k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(query_mem_tracker());
107
425k
    _query_watcher.start();
108
425k
    _execution_dependency = Dependency::create_unique(-1, -1, "ExecutionDependency", false);
109
425k
    _memory_sufficient_dependency =
110
425k
            Dependency::create_unique(-1, -1, "MemorySufficientDependency", true);
111
112
425k
    _runtime_filter_mgr = std::make_unique<RuntimeFilterMgr>(true);
113
114
425k
    _timeout_second = query_options.execution_timeout;
115
116
425k
    bool initialize_context_holder =
117
425k
            config::enable_file_cache && config::enable_file_cache_query_limit &&
118
425k
            query_options.__isset.enable_file_cache && query_options.enable_file_cache &&
119
425k
            query_options.__isset.file_cache_query_limit_percent &&
120
425k
            query_options.file_cache_query_limit_percent < 100;
121
122
    // Initialize file cache context holders
123
425k
    if (initialize_context_holder) {
124
10
        _query_context_holders = io::FileCacheFactory::instance()->get_query_context_holders(
125
10
                _query_id, query_options.file_cache_query_limit_percent);
126
10
    }
127
128
425k
    const bool initialize_remote_scan_cache_write_limiter =
129
425k
            config::is_cloud_mode() && config::enable_file_cache &&
130
425k
            query_options.__isset.file_cache_query_limit_bytes &&
131
425k
            query_options.file_cache_query_limit_bytes >= 0 &&
132
425k
            query_options.query_type == TQueryType::SELECT;
133
425k
    if (initialize_remote_scan_cache_write_limiter) {
134
3
        _remote_scan_cache_write_limiter = std::make_unique<io::RemoteScanCacheWriteLimiter>(
135
3
                _query_id, query_options.file_cache_query_limit_bytes);
136
3
    }
137
138
425k
    bool is_query_type_valid = query_options.query_type == TQueryType::SELECT ||
139
425k
                               query_options.query_type == TQueryType::LOAD ||
140
425k
                               query_options.query_type == TQueryType::EXTERNAL;
141
425k
    DCHECK_EQ(is_query_type_valid, true);
142
143
425k
    this->coord_addr = coord_addr;
144
    // current_connect_fe is used for report query statistics
145
425k
    this->current_connect_fe = current_connect_fe;
146
    // external query has no current_connect_fe
147
425k
    if (query_options.query_type != TQueryType::EXTERNAL) {
148
300k
        bool is_report_fe_addr_valid =
149
300k
                !this->current_connect_fe.hostname.empty() && this->current_connect_fe.port != 0;
150
300k
        DCHECK_EQ(is_report_fe_addr_valid, true);
151
300k
    }
152
425k
    clock_gettime(CLOCK_MONOTONIC, &this->_query_arrival_timestamp);
153
425k
    DorisMetrics::instance()->query_ctx_cnt->increment(1);
154
425k
    _mem_arb = MemShareArbitrator::create_shared(
155
425k
            query_id, query_options.mem_limit,
156
425k
            query_options.__isset.max_scan_mem_ratio ? query_options.max_scan_mem_ratio : 1.0);
157
425k
}
158
159
423k
void QueryContext::_init_query_mem_tracker() {
160
423k
    bool has_query_mem_limit = _query_options.__isset.mem_limit && (_query_options.mem_limit > 0);
161
423k
    int64_t bytes_limit = has_query_mem_limit ? _query_options.mem_limit : -1;
162
423k
    if (bytes_limit > MemInfo::mem_limit() || bytes_limit == -1) {
163
177k
        VLOG_NOTICE << "Query memory limit " << PrettyPrinter::print(bytes_limit, TUnit::BYTES)
164
181
                    << " exceeds process memory limit of "
165
181
                    << PrettyPrinter::print(MemInfo::mem_limit(), TUnit::BYTES)
166
181
                    << " OR is -1. Using process memory limit instead.";
167
177k
        bytes_limit = MemInfo::mem_limit();
168
177k
    }
169
    // If the query is a pure load task(streamload, routine load, group commit), then it should not use
170
    // memlimit per query to limit their memory usage.
171
423k
    if (is_pure_load_task()) {
172
127k
        bytes_limit = MemInfo::mem_limit();
173
127k
    }
174
423k
    std::shared_ptr<MemTrackerLimiter> query_mem_tracker;
175
423k
    if (_query_options.query_type == TQueryType::SELECT) {
176
260k
        query_mem_tracker = MemTrackerLimiter::create_shared(
177
260k
                MemTrackerLimiter::Type::QUERY, fmt::format("Query#Id={}", print_id(_query_id)),
178
260k
                bytes_limit);
179
260k
    } else if (_query_options.query_type == TQueryType::LOAD) {
180
39.4k
        query_mem_tracker = MemTrackerLimiter::create_shared(
181
39.4k
                MemTrackerLimiter::Type::LOAD, fmt::format("Load#Id={}", print_id(_query_id)),
182
39.4k
                bytes_limit);
183
122k
    } else if (_query_options.query_type == TQueryType::EXTERNAL) { // spark/flink/etc..
184
122k
        query_mem_tracker = MemTrackerLimiter::create_shared(
185
122k
                MemTrackerLimiter::Type::QUERY, fmt::format("External#Id={}", print_id(_query_id)),
186
122k
                bytes_limit);
187
122k
    } else {
188
514
        LOG(FATAL) << "__builtin_unreachable";
189
514
        __builtin_unreachable();
190
514
    }
191
422k
    if (_query_options.__isset.is_report_success && _query_options.is_report_success) {
192
35.8k
        query_mem_tracker->enable_print_log_usage();
193
35.8k
    }
194
195
    // If enable reserve memory, not enable check limit, because reserve memory will check it.
196
    // If reserve enabled, even if the reserved memory size is smaller than the actual requested memory,
197
    // and the query memory consumption is larger than the limit, we do not expect the query to fail
198
    // after `check_limit` returns an error, but to run as long as possible,
199
    // and will enter the paused state and try to spill when the query reserves next time.
200
    // If the workload group or process runs out of memory, it will be forced to cancel.
201
422k
    query_mem_tracker->set_enable_check_limit(!(_query_options.__isset.enable_reserve_memory &&
202
423k
                                                _query_options.enable_reserve_memory));
203
422k
    _resource_ctx->memory_context()->set_mem_tracker(query_mem_tracker);
204
422k
}
205
206
424k
void QueryContext::_init_resource_context() {
207
424k
    _resource_ctx = ResourceContext::create_shared();
208
424k
    _init_query_mem_tracker();
209
424k
}
210
211
419k
void QueryContext::init_query_task_controller() {
212
419k
    _resource_ctx->set_task_controller(QueryTaskController::create(shared_from_this()));
213
419k
    _resource_ctx->task_controller()->set_task_id(_query_id);
214
419k
    _resource_ctx->task_controller()->set_fe_addr(current_connect_fe);
215
419k
    _resource_ctx->task_controller()->set_query_type(_query_options.query_type);
216
419k
#ifndef BE_TEST
217
419k
    _exec_env->runtime_query_statistics_mgr()->register_resource_context(print_id(_query_id),
218
419k
                                                                         _resource_ctx);
219
419k
#endif
220
419k
}
221
222
424k
QueryContext::~QueryContext() {
223
424k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(query_mem_tracker());
224
    // query mem tracker consumption is equal to 0, it means that after QueryContext is created,
225
    // it is found that query already exists in _query_ctx_map, and query mem tracker is not used.
226
    // query mem tracker consumption is not equal to 0 after use, because there is memory consumed
227
    // on query mem tracker, released on other trackers.
228
424k
    std::string mem_tracker_msg;
229
424k
    if (query_mem_tracker()->peak_consumption() != 0) {
230
301k
        mem_tracker_msg = fmt::format(
231
301k
                "deregister query/load memory tracker, queryId={}, Limit={}, CurrUsed={}, "
232
301k
                "PeakUsed={}",
233
301k
                print_id(_query_id), PrettyPrinter::print_bytes(query_mem_tracker()->limit()),
234
301k
                PrettyPrinter::print_bytes(query_mem_tracker()->consumption()),
235
301k
                PrettyPrinter::print_bytes(query_mem_tracker()->peak_consumption()));
236
301k
    }
237
424k
    _resource_ctx->task_controller()->finish();
238
239
424k
    if (enable_profile()) {
240
1.57k
        _report_query_profile();
241
1.57k
    }
242
243
424k
    _runtime_filter_mgr.reset();
244
424k
    _execution_dependency.reset();
245
424k
    _runtime_predicates.clear();
246
424k
    file_scan_range_params_map.clear();
247
424k
    obj_pool.clear();
248
424k
    _merge_controller_handler.reset();
249
250
424k
    DorisMetrics::instance()->query_ctx_cnt->increment(-1);
251
    // fragment_mgr is nullptr in unittest
252
424k
    if (ExecEnv::GetInstance()->fragment_mgr()) {
253
301k
        ExecEnv::GetInstance()->fragment_mgr()->remove_query_context(this->_query_id);
254
301k
    }
255
    // the only one msg shows query's end. any other msg should append to it if need.
256
424k
    timespec now;
257
424k
    clock_gettime(CLOCK_MONOTONIC, &now);
258
424k
    int64_t elapsed_ms = (now.tv_sec - _query_arrival_timestamp.tv_sec) * 1000LL +
259
424k
                         (now.tv_nsec - _query_arrival_timestamp.tv_nsec) / 1000000LL;
260
424k
    LOG_INFO("Query {} deconstructed, elapsed_ms: {}, mem_tracker: {}", print_id(this->_query_id),
261
424k
             elapsed_ms, mem_tracker_msg);
262
424k
}
263
264
270k
void QueryContext::set_ready_to_execute(Status reason) {
265
270k
    set_execution_dependency_ready();
266
270k
    _exec_status.update(reason);
267
270k
}
268
269
174k
void QueryContext::set_ready_to_execute_only() {
270
174k
    set_execution_dependency_ready();
271
174k
}
272
273
445k
void QueryContext::set_execution_dependency_ready() {
274
445k
    _execution_dependency->set_ready();
275
445k
}
276
277
46
void QueryContext::set_memory_sufficient(bool sufficient) {
278
46
    if (sufficient) {
279
17
        {
280
17
            _memory_sufficient_dependency->set_ready();
281
17
            _resource_ctx->task_controller()->reset_paused_reason();
282
17
        }
283
29
    } else {
284
29
        _memory_sufficient_dependency->block();
285
29
        _resource_ctx->task_controller()->add_paused_count();
286
29
    }
287
46
}
288
289
160k
void QueryContext::cancel(Status new_status, int fragment_id) {
290
160k
    if (!_exec_status.update(new_status)) {
291
15.9k
        return;
292
15.9k
    }
293
    // Tasks should be always runnable.
294
144k
    _execution_dependency->set_always_ready();
295
144k
    _memory_sufficient_dependency->set_always_ready();
296
144k
    if ((new_status.is<ErrorCode::MEM_LIMIT_EXCEEDED>() ||
297
144k
         new_status.is<ErrorCode::MEM_ALLOC_FAILED>()) &&
298
144k
        _query_options.__isset.dump_heap_profile_when_mem_limit_exceeded &&
299
144k
        _query_options.dump_heap_profile_when_mem_limit_exceeded) {
300
        // if query is cancelled because of query mem limit exceeded, dump heap profile
301
        // at the time of cancellation can get the most accurate memory usage for problem analysis
302
0
        auto wg = workload_group();
303
0
        auto log_str = fmt::format(
304
0
                "Query {} canceled because of memory limit exceeded, dumping memory "
305
0
                "detail profiles. wg: {}. {}",
306
0
                print_id(_query_id), wg ? wg->debug_string() : "null",
307
0
                doris::ProcessProfile::instance()->memory_profile()->process_memory_detail_str());
308
0
        LOG_LONG_STRING(INFO, log_str);
309
0
        std::string dot = HeapProfiler::instance()->dump_heap_profile_to_dot();
310
0
        if (!dot.empty()) {
311
0
            dot += "\n-------------------------------------------------------\n";
312
0
            dot += "Copy the text after `digraph` in the above output to "
313
0
                   "http://www.webgraphviz.com to generate a dot graph.\n"
314
0
                   "after start heap profiler, if there is no operation, will print `No nodes "
315
0
                   "to "
316
0
                   "print`."
317
0
                   "If there are many errors: `addr2line: Dwarf Error`,"
318
0
                   "or other FAQ, reference doc: "
319
0
                   "https://doris.apache.org/community/developer-guide/debug-tool/#4-qa\n";
320
0
            auto nest_log_str =
321
0
                    fmt::format("Query {}, dump heap profile to dot: {}", print_id(_query_id), dot);
322
0
            LOG_LONG_STRING(INFO, nest_log_str);
323
0
        }
324
0
    }
325
326
144k
    set_ready_to_execute(new_status);
327
144k
    cancel_all_pipeline_context(new_status, fragment_id);
328
144k
}
329
330
23
void QueryContext::set_load_error_url(std::string error_url) {
331
23
    std::lock_guard<std::mutex> lock(_error_url_lock);
332
23
    _load_error_url = error_url;
333
23
}
334
335
50.9k
std::string QueryContext::get_load_error_url() {
336
50.9k
    std::lock_guard<std::mutex> lock(_error_url_lock);
337
50.9k
    return _load_error_url;
338
50.9k
}
339
340
23
void QueryContext::set_first_error_msg(std::string error_msg) {
341
23
    std::lock_guard<std::mutex> lock(_error_url_lock);
342
23
    _first_error_msg = error_msg;
343
23
}
344
345
50.9k
std::string QueryContext::get_first_error_msg() {
346
50.9k
    std::lock_guard<std::mutex> lock(_error_url_lock);
347
50.9k
    return _first_error_msg;
348
50.9k
}
349
350
144k
void QueryContext::cancel_all_pipeline_context(const Status& reason, int fragment_id) {
351
144k
    std::vector<std::weak_ptr<PipelineFragmentContext>> ctx_to_cancel;
352
144k
    {
353
144k
        std::lock_guard<std::mutex> lock(_pipeline_map_write_lock);
354
253k
        for (auto& [f_id, f_context] : _fragment_id_to_pipeline_ctx) {
355
253k
            if (fragment_id == f_id) {
356
1.40k
                continue;
357
1.40k
            }
358
252k
            ctx_to_cancel.push_back(f_context);
359
252k
        }
360
144k
    }
361
252k
    for (auto& f_context : ctx_to_cancel) {
362
252k
        if (auto pipeline_ctx = f_context.lock()) {
363
13.4k
            pipeline_ctx->cancel(reason);
364
13.4k
        }
365
252k
    }
366
144k
}
367
368
0
std::string QueryContext::print_all_pipeline_context() {
369
0
    std::vector<std::weak_ptr<PipelineFragmentContext>> ctx_to_print;
370
0
    fmt::memory_buffer debug_string_buffer;
371
0
    size_t i = 0;
372
0
    {
373
0
        fmt::format_to(debug_string_buffer, "{} pipeline fragment contexts in query {}. \n",
374
0
                       _fragment_id_to_pipeline_ctx.size(), print_id(_query_id));
375
376
0
        {
377
0
            std::lock_guard<std::mutex> lock(_pipeline_map_write_lock);
378
0
            for (auto& [f_id, f_context] : _fragment_id_to_pipeline_ctx) {
379
0
                ctx_to_print.push_back(f_context);
380
0
            }
381
0
        }
382
0
        for (auto& f_context : ctx_to_print) {
383
0
            if (auto pipeline_ctx = f_context.lock()) {
384
0
                auto elapsed = pipeline_ctx->elapsed_time() / 1000000000.0;
385
0
                fmt::format_to(debug_string_buffer,
386
0
                               "No.{} (elapse_second={}s, fragment_id={}) : {}\n", i, elapsed,
387
0
                               pipeline_ctx->get_fragment_id(), pipeline_ctx->debug_string());
388
0
                i++;
389
0
            }
390
0
        }
391
0
    }
392
0
    return fmt::to_string(debug_string_buffer);
393
0
}
394
395
void QueryContext::set_pipeline_context(const int fragment_id,
396
454k
                                        std::shared_ptr<PipelineFragmentContext> pip_ctx) {
397
454k
    std::lock_guard<std::mutex> lock(_pipeline_map_write_lock);
398
    // Use insert_or_assign instead of insert to support overwriting old entries
399
    // when recursive CTE recreates PipelineFragmentContext between rounds.
400
454k
    _fragment_id_to_pipeline_ctx.insert_or_assign(fragment_id, pip_ctx);
401
454k
}
402
403
6.05M
doris::TaskScheduler* QueryContext::get_pipe_exec_scheduler() {
404
6.05M
    if (!_task_scheduler) {
405
0
        throw Exception(Status::InternalError("task_scheduler is null"));
406
0
    }
407
6.05M
    return _task_scheduler;
408
6.05M
}
409
410
300k
Status QueryContext::set_workload_group(WorkloadGroupPtr& wg) {
411
300k
    _resource_ctx->set_workload_group(wg);
412
    // Should add query first, the workload group will not be deleted,
413
    // then visit workload group's resource
414
    // see task_group_manager::delete_workload_group_by_ids
415
300k
    RETURN_IF_ERROR(workload_group()->add_resource_ctx(_query_id, _resource_ctx));
416
417
300k
    workload_group()->get_query_scheduler(&_task_scheduler, &_scan_task_scheduler,
418
300k
                                          &_remote_scan_task_scheduler);
419
300k
    return Status::OK();
420
300k
}
421
422
void QueryContext::add_fragment_profile(
423
        int fragment_id, const std::vector<std::shared_ptr<TRuntimeProfileTree>>& pipeline_profiles,
424
3.22k
        std::shared_ptr<TRuntimeProfileTree> load_channel_profile) {
425
3.22k
    if (pipeline_profiles.empty()) {
426
0
        std::string msg = fmt::format("Add pipeline profile failed, query {}, fragment {}",
427
0
                                      print_id(this->_query_id), fragment_id);
428
0
        LOG_ERROR(msg);
429
0
        DCHECK(false) << msg;
430
0
        return;
431
0
    }
432
433
3.22k
#ifndef NDEBUG
434
9.44k
    for (const auto& p : pipeline_profiles) {
435
18.4E
        DCHECK(p != nullptr) << fmt::format("Add pipeline profile failed, query {}, fragment {}",
436
18.4E
                                            print_id(this->_query_id), fragment_id);
437
9.44k
    }
438
3.22k
#endif
439
440
3.22k
    std::lock_guard<std::mutex> l(_profile_mutex);
441
18.4E
    VLOG_ROW << fmt::format(
442
18.4E
            "Query add fragment profile, query {}, fragment {}, pipeline profile count {} ",
443
18.4E
            print_id(this->_query_id), fragment_id, pipeline_profiles.size());
444
445
3.22k
    _profile_map.insert(std::make_pair(fragment_id, pipeline_profiles));
446
447
3.22k
    if (load_channel_profile != nullptr) {
448
3.22k
        _load_channel_profile_map.insert(std::make_pair(fragment_id, load_channel_profile));
449
3.22k
    }
450
3.22k
}
451
452
1.57k
void QueryContext::_report_query_profile() {
453
1.57k
    std::lock_guard<std::mutex> lg(_profile_mutex);
454
455
3.16k
    for (auto& [fragment_id, fragment_profile] : _profile_map) {
456
3.16k
        std::shared_ptr<TRuntimeProfileTree> load_channel_profile = nullptr;
457
458
3.16k
        if (_load_channel_profile_map.contains(fragment_id)) {
459
3.16k
            load_channel_profile = _load_channel_profile_map[fragment_id];
460
3.16k
        }
461
462
3.16k
        ExecEnv::GetInstance()->runtime_query_statistics_mgr()->register_fragment_profile(
463
3.16k
                _query_id, this->coord_addr, fragment_id, fragment_profile, load_channel_profile);
464
3.16k
    }
465
466
1.57k
    ExecEnv::GetInstance()->runtime_query_statistics_mgr()->trigger_profile_reporting();
467
1.57k
}
468
469
std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>>
470
0
QueryContext::_collect_realtime_query_profile() {
471
0
    std::unordered_map<int, std::vector<std::shared_ptr<TRuntimeProfileTree>>> res;
472
0
    std::lock_guard<std::mutex> lock(_pipeline_map_write_lock);
473
0
    for (const auto& [fragment_id, fragment_ctx_wptr] : _fragment_id_to_pipeline_ctx) {
474
0
        if (auto fragment_ctx = fragment_ctx_wptr.lock()) {
475
0
            if (fragment_ctx == nullptr) {
476
0
                std::string msg =
477
0
                        fmt::format("PipelineFragmentContext is nullptr, query {} fragment_id: {}",
478
0
                                    print_id(_query_id), fragment_id);
479
0
                LOG_ERROR(msg);
480
0
                DCHECK(false) << msg;
481
0
                continue;
482
0
            }
483
484
0
            auto profile = fragment_ctx->collect_realtime_profile();
485
486
0
            if (profile.empty()) {
487
0
                std::string err_msg = fmt::format(
488
0
                        "Get nothing when collecting profile, query {}, fragment_id: {}",
489
0
                        print_id(_query_id), fragment_id);
490
0
                LOG_ERROR(err_msg);
491
0
                DCHECK(false) << err_msg;
492
0
                continue;
493
0
            }
494
495
0
            res.insert(std::make_pair(fragment_id, profile));
496
0
        }
497
0
    }
498
499
0
    return res;
500
0
}
501
502
0
TReportExecStatusParams QueryContext::get_realtime_exec_status() {
503
0
    TReportExecStatusParams exec_status;
504
505
0
    auto realtime_query_profile = _collect_realtime_query_profile();
506
0
    std::vector<std::shared_ptr<TRuntimeProfileTree>> load_channel_profiles;
507
508
0
    for (auto load_channel_profile : _load_channel_profile_map) {
509
0
        if (load_channel_profile.second != nullptr) {
510
0
            load_channel_profiles.push_back(load_channel_profile.second);
511
0
        }
512
0
    }
513
514
0
    exec_status = RuntimeQueryStatisticsMgr::create_report_exec_status_params(
515
0
            this->_query_id, std::move(realtime_query_profile), std::move(load_channel_profiles),
516
0
            /*is_done=*/false);
517
518
0
    return exec_status;
519
0
}
520
521
Status QueryContext::send_block_to_cte_scan(
522
        const TUniqueId& instance_id, int node_id,
523
4.22k
        const google::protobuf::RepeatedPtrField<doris::PBlock>& pblocks, bool eos) {
524
4.22k
    std::unique_lock<std::mutex> l(_cte_scan_lock);
525
4.22k
    auto it = _cte_scan.find(std::make_pair(instance_id, node_id));
526
4.22k
    if (it == _cte_scan.end()) {
527
0
        return Status::InternalError("RecCTEScan not found for instance {}, node {}",
528
0
                                     print_id(instance_id), node_id);
529
0
    }
530
4.22k
    for (const auto& pblock : pblocks) {
531
2.28k
        RETURN_IF_ERROR(it->second->add_block(pblock));
532
2.28k
    }
533
4.22k
    if (eos) {
534
2.18k
        it->second->set_ready();
535
2.18k
    }
536
4.22k
    return Status::OK();
537
4.22k
}
538
539
void QueryContext::registe_cte_scan(const TUniqueId& instance_id, int node_id,
540
2.18k
                                    RecCTEScanLocalState* scan) {
541
2.18k
    std::unique_lock<std::mutex> l(_cte_scan_lock);
542
2.18k
    auto key = std::make_pair(instance_id, node_id);
543
2.18k
    DCHECK(!_cte_scan.contains(key)) << "Duplicate registe cte scan for instance "
544
0
                                     << print_id(instance_id) << ", node " << node_id;
545
2.18k
    _cte_scan.emplace(key, scan);
546
2.18k
}
547
548
2.17k
void QueryContext::deregiste_cte_scan(const TUniqueId& instance_id, int node_id) {
549
2.17k
    std::lock_guard<std::mutex> l(_cte_scan_lock);
550
2.17k
    auto key = std::make_pair(instance_id, node_id);
551
18.4E
    DCHECK(_cte_scan.contains(key)) << "Duplicate deregiste cte scan for instance "
552
18.4E
                                    << print_id(instance_id) << ", node " << node_id;
553
2.17k
    _cte_scan.erase(key);
554
2.17k
}
555
556
2.04k
Status QueryContext::reset_global_rf(const google::protobuf::RepeatedField<int32_t>& filter_ids) {
557
2.04k
    if (_merge_controller_handler) {
558
2.04k
        return _merge_controller_handler->reset_global_rf(this, filter_ids);
559
2.04k
    }
560
0
    return Status::OK();
561
2.04k
}
562
563
455k
void QueryContext::add_total_task_num(int delta) {
564
455k
    if (auto* qtc = dynamic_cast<QueryTaskController*>(_resource_ctx->task_controller())) {
565
454k
        qtc->add_total_task_num(delta);
566
454k
    }
567
455k
}
568
569
2.13M
void QueryContext::inc_finished_task_num() {
570
2.13M
    if (auto* qtc = dynamic_cast<QueryTaskController*>(_resource_ctx->task_controller())) {
571
2.13M
        qtc->inc_finished_task_num();
572
2.13M
    }
573
2.13M
}
574
575
} // namespace doris