Coverage Report

Created: 2026-08-04 11:20

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