Coverage Report

Created: 2026-08-07 08:28

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