Coverage Report

Created: 2026-05-14 21:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/runtime/fragment_mgr.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/fragment_mgr.h"
19
20
#include <brpc/controller.h>
21
#include <bvar/latency_recorder.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/DorisExternalService_types.h>
24
#include <gen_cpp/FrontendService.h>
25
#include <gen_cpp/FrontendService_types.h>
26
#include <gen_cpp/HeartbeatService_types.h>
27
#include <gen_cpp/Metrics_types.h>
28
#include <gen_cpp/PaloInternalService_types.h>
29
#include <gen_cpp/PlanNodes_types.h>
30
#include <gen_cpp/Planner_types.h>
31
#include <gen_cpp/QueryPlanExtra_types.h>
32
#include <gen_cpp/RuntimeProfile_types.h>
33
#include <gen_cpp/Types_types.h>
34
#include <gen_cpp/internal_service.pb.h>
35
#include <pthread.h>
36
#include <sys/time.h>
37
#include <thrift/TApplicationException.h>
38
#include <thrift/Thrift.h>
39
#include <thrift/protocol/TDebugProtocol.h>
40
#include <thrift/transport/TTransportException.h>
41
#include <unistd.h>
42
43
#include <algorithm>
44
#include <cstddef>
45
#include <ctime>
46
47
// IWYU pragma: no_include <bits/chrono.h>
48
#include <chrono> // IWYU pragma: keep
49
#include <cstdint>
50
#include <map>
51
#include <memory>
52
#include <mutex>
53
#include <sstream>
54
#include <unordered_map>
55
#include <unordered_set>
56
#include <utility>
57
58
#include "common/config.h"
59
#include "common/exception.h"
60
#include "common/logging.h"
61
#include "common/object_pool.h"
62
#include "common/status.h"
63
#include "common/utils.h"
64
#include "io/fs/stream_load_pipe.h"
65
#include "pipeline/pipeline_fragment_context.h"
66
#include "runtime/client_cache.h"
67
#include "runtime/descriptors.h"
68
#include "runtime/exec_env.h"
69
#include "runtime/frontend_info.h"
70
#include "runtime/primitive_type.h"
71
#include "runtime/query_context.h"
72
#include "runtime/runtime_query_statistics_mgr.h"
73
#include "runtime/runtime_state.h"
74
#include "runtime/stream_load/new_load_stream_mgr.h"
75
#include "runtime/stream_load/stream_load_context.h"
76
#include "runtime/stream_load/stream_load_executor.h"
77
#include "runtime/thread_context.h"
78
#include "runtime/types.h"
79
#include "runtime/workload_group/workload_group.h"
80
#include "runtime/workload_group/workload_group_manager.h"
81
#include "runtime_filter/runtime_filter_consumer.h"
82
#include "runtime_filter/runtime_filter_mgr.h"
83
#include "service/backend_options.h"
84
#include "util/brpc_client_cache.h"
85
#include "util/debug_points.h"
86
#include "util/debug_util.h"
87
#include "util/doris_metrics.h"
88
#include "util/network_util.h"
89
#include "util/runtime_profile.h"
90
#include "util/thread.h"
91
#include "util/threadpool.h"
92
#include "util/thrift_util.h"
93
#include "util/uid_util.h"
94
95
namespace doris {
96
#include "common/compile_check_begin.h"
97
98
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(fragment_instance_count, MetricUnit::NOUNIT);
99
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(timeout_canceled_fragment_count, MetricUnit::NOUNIT);
100
101
bvar::LatencyRecorder g_fragmentmgr_prepare_latency("doris_FragmentMgr", "prepare");
102
103
bvar::Adder<uint64_t> g_fragment_executing_count("fragment_executing_count");
104
bvar::Status<uint64_t> g_fragment_last_active_time(
105
        "fragment_last_active_time", duration_cast<std::chrono::milliseconds>(
106
                                             std::chrono::system_clock::now().time_since_epoch())
107
                                             .count());
108
109
0
uint64_t get_fragment_executing_count() {
110
0
    return g_fragment_executing_count.get_value();
111
0
}
112
0
uint64_t get_fragment_last_active_time() {
113
0
    return g_fragment_last_active_time.get_value();
114
0
}
115
116
0
std::string to_load_error_http_path(const std::string& file_name) {
117
0
    if (file_name.empty()) {
118
0
        return "";
119
0
    }
120
0
    if (file_name.compare(0, 4, "http") == 0) {
121
0
        return file_name;
122
0
    }
123
0
    std::stringstream url;
124
0
    url << (config::enable_https ? "https" : "http") << "://"
125
0
        << get_host_port(BackendOptions::get_localhost(), config::webserver_port)
126
0
        << "/api/_load_error_log?"
127
0
        << "file=" << file_name;
128
0
    return url.str();
129
0
}
130
131
using apache::thrift::TException;
132
using apache::thrift::transport::TTransportException;
133
134
static Status _do_fetch_running_queries_rpc(const FrontendInfo& fe_info,
135
0
                                            std::unordered_set<TUniqueId>& query_set) {
136
0
    TFetchRunningQueriesResult rpc_result;
137
0
    TFetchRunningQueriesRequest rpc_request;
138
139
0
    Status client_status;
140
0
    const int32_t timeout_ms = 3 * 1000;
141
0
    FrontendServiceConnection rpc_client(ExecEnv::GetInstance()->frontend_client_cache(),
142
0
                                         fe_info.info.coordinator_address, timeout_ms,
143
0
                                         &client_status);
144
    // Abort this fe.
145
0
    if (!client_status.ok()) {
146
0
        LOG_WARNING("Failed to get client for {}, reason is {}",
147
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
148
0
                    client_status.to_string());
149
0
        return Status::InternalError("Failed to get client for {}, reason is {}",
150
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
151
0
                                     client_status.to_string());
152
0
    }
153
154
    // do rpc
155
0
    try {
156
0
        try {
157
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
158
0
        } catch (const apache::thrift::transport::TTransportException& e) {
159
0
            LOG_WARNING("Transport exception reason: {}, reopening", e.what());
160
0
            client_status = rpc_client.reopen(config::thrift_rpc_timeout_ms);
161
0
            if (!client_status.ok()) {
162
0
                LOG_WARNING("Reopen failed, reason: {}", client_status.to_string_no_stack());
163
0
                return Status::InternalError("Reopen failed, reason: {}",
164
0
                                             client_status.to_string_no_stack());
165
0
            }
166
167
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
168
0
        }
169
0
    } catch (apache::thrift::TException& e) {
170
        // During upgrading cluster or meet any other network error.
171
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
172
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address), e.what());
173
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
174
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
175
0
                                     e.what());
176
0
    }
177
178
    // Avoid logic error in frontend.
179
0
    if (!rpc_result.__isset.status || rpc_result.status.status_code != TStatusCode::OK) {
180
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
181
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
182
0
                    doris::to_string(rpc_result.status.status_code));
183
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
184
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
185
0
                                     doris::to_string(rpc_result.status.status_code));
186
0
    }
187
188
0
    if (!rpc_result.__isset.running_queries) {
189
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
190
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
191
0
                                     "running_queries is not set");
192
0
    }
193
194
0
    query_set = std::unordered_set<TUniqueId>(rpc_result.running_queries.begin(),
195
0
                                              rpc_result.running_queries.end());
196
0
    return Status::OK();
197
0
};
198
199
0
static std::map<int64_t, std::unordered_set<TUniqueId>> _get_all_running_queries_from_fe() {
200
0
    const std::map<TNetworkAddress, FrontendInfo>& running_fes =
201
0
            ExecEnv::GetInstance()->get_running_frontends();
202
203
0
    std::map<int64_t, std::unordered_set<TUniqueId>> result;
204
0
    std::vector<FrontendInfo> qualified_fes;
205
206
0
    for (const auto& fe : running_fes) {
207
        // Only consider normal frontend.
208
0
        if (fe.first.port != 0 && fe.second.info.process_uuid != 0) {
209
0
            qualified_fes.push_back(fe.second);
210
0
        } else {
211
0
            return {};
212
0
        }
213
0
    }
214
215
0
    for (const auto& fe_addr : qualified_fes) {
216
0
        const int64_t process_uuid = fe_addr.info.process_uuid;
217
0
        std::unordered_set<TUniqueId> query_set;
218
0
        Status st = _do_fetch_running_queries_rpc(fe_addr, query_set);
219
0
        if (!st.ok()) {
220
            // Empty result, cancel worker will not do anything
221
0
            return {};
222
0
        }
223
224
        // frontend_info and process_uuid has been checked in rpc threads.
225
0
        result[process_uuid] = query_set;
226
0
    }
227
228
0
    return result;
229
0
}
230
231
9
inline uint32_t get_map_id(const TUniqueId& query_id, size_t capacity) {
232
9
    uint32_t value = HashUtil::hash(&query_id.lo, 8, 0);
233
9
    value = HashUtil::hash(&query_id.hi, 8, value);
234
9
    return value % capacity;
235
9
}
236
237
0
inline uint32_t get_map_id(std::pair<TUniqueId, int> key, size_t capacity) {
238
0
    uint32_t value = HashUtil::hash(&key.first.lo, 8, 0);
239
0
    value = HashUtil::hash(&key.first.hi, 8, value);
240
0
    return value % capacity;
241
0
}
242
243
template <typename Key, typename Value, typename ValueType>
244
27
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
245
27
    _internal_map.resize(config::num_query_ctx_map_partitions);
246
3.48k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
247
3.45k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
248
3.45k
                            phmap::flat_hash_map<Key, Value>()};
249
3.45k
    }
250
27
}
_ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_EC2Ev
Line
Count
Source
244
9
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
245
9
    _internal_map.resize(config::num_query_ctx_map_partitions);
246
1.16k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
247
1.15k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
248
1.15k
                            phmap::flat_hash_map<Key, Value>()};
249
1.15k
    }
250
9
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_EC2Ev
Line
Count
Source
244
9
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
245
9
    _internal_map.resize(config::num_query_ctx_map_partitions);
246
1.16k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
247
1.15k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
248
1.15k
                            phmap::flat_hash_map<Key, Value>()};
249
1.15k
    }
250
9
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_EC2Ev
Line
Count
Source
244
9
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
245
9
    _internal_map.resize(config::num_query_ctx_map_partitions);
246
1.16k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
247
1.15k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
248
1.15k
                            phmap::flat_hash_map<Key, Value>()};
249
1.15k
    }
250
9
}
251
252
template <typename Key, typename Value, typename ValueType>
253
5
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
254
5
    auto id = get_map_id(query_id, _internal_map.size());
255
5
    {
256
5
        std::shared_lock lock(*_internal_map[id].first);
257
5
        auto& map = _internal_map[id].second;
258
5
        auto search = map.find(query_id);
259
5
        if (search != map.end()) {
260
1
            return search->second;
261
1
        }
262
4
        return std::shared_ptr<ValueType>(nullptr);
263
5
    }
264
5
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E4findERKS1_
Line
Count
Source
253
5
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
254
5
    auto id = get_map_id(query_id, _internal_map.size());
255
5
    {
256
5
        std::shared_lock lock(*_internal_map[id].first);
257
5
        auto& map = _internal_map[id].second;
258
5
        auto search = map.find(query_id);
259
5
        if (search != map.end()) {
260
1
            return search->second;
261
1
        }
262
4
        return std::shared_ptr<ValueType>(nullptr);
263
5
    }
264
5
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_E4findERKS3_
265
266
template <typename Key, typename Value, typename ValueType>
267
Status ConcurrentContextMap<Key, Value, ValueType>::apply_if_not_exists(
268
3
        const Key& query_id, std::shared_ptr<ValueType>& query_ctx, ApplyFunction&& function) {
269
3
    auto id = get_map_id(query_id, _internal_map.size());
270
3
    {
271
3
        std::unique_lock lock(*_internal_map[id].first);
272
3
        auto& map = _internal_map[id].second;
273
3
        auto search = map.find(query_id);
274
3
        if (search != map.end()) {
275
0
            query_ctx = search->second.lock();
276
0
        }
277
3
        if (!query_ctx) {
278
3
            return function(map);
279
3
        }
280
0
        return Status::OK();
281
3
    }
282
3
}
283
284
template <typename Key, typename Value, typename ValueType>
285
1
void ConcurrentContextMap<Key, Value, ValueType>::erase(const Key& query_id) {
286
1
    auto id = get_map_id(query_id, _internal_map.size());
287
1
    {
288
1
        std::unique_lock lock(*_internal_map[id].first);
289
1
        auto& map = _internal_map[id].second;
290
1
        map.erase(query_id);
291
1
    }
292
1
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_E5eraseERKS3_
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E5eraseERKS1_
Line
Count
Source
285
1
void ConcurrentContextMap<Key, Value, ValueType>::erase(const Key& query_id) {
286
1
    auto id = get_map_id(query_id, _internal_map.size());
287
1
    {
288
1
        std::unique_lock lock(*_internal_map[id].first);
289
1
        auto& map = _internal_map[id].second;
290
1
        map.erase(query_id);
291
1
    }
292
1
}
293
294
template <typename Key, typename Value, typename ValueType>
295
void ConcurrentContextMap<Key, Value, ValueType>::insert(const Key& query_id,
296
0
                                                         std::shared_ptr<ValueType> query_ctx) {
297
0
    auto id = get_map_id(query_id, _internal_map.size());
298
0
    {
299
0
        std::unique_lock lock(*_internal_map[id].first);
300
0
        auto& map = _internal_map[id].second;
301
0
        map.insert({query_id, query_ctx});
302
0
    }
303
0
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E6insertERKS1_S4_
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_E6insertERKS3_S7_
304
305
template <typename Key, typename Value, typename ValueType>
306
27
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
307
3.45k
    for (auto& pair : _internal_map) {
308
3.45k
        std::unique_lock lock(*pair.first);
309
3.45k
        auto& map = pair.second;
310
3.45k
        map.clear();
311
3.45k
    }
312
27
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E5clearEv
Line
Count
Source
306
9
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
307
1.15k
    for (auto& pair : _internal_map) {
308
1.15k
        std::unique_lock lock(*pair.first);
309
1.15k
        auto& map = pair.second;
310
1.15k
        map.clear();
311
1.15k
    }
312
9
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E5clearEv
Line
Count
Source
306
9
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
307
1.15k
    for (auto& pair : _internal_map) {
308
1.15k
        std::unique_lock lock(*pair.first);
309
1.15k
        auto& map = pair.second;
310
1.15k
        map.clear();
311
1.15k
    }
312
9
}
_ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_8pipeline23PipelineFragmentContextEES6_E5clearEv
Line
Count
Source
306
9
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
307
1.15k
    for (auto& pair : _internal_map) {
308
1.15k
        std::unique_lock lock(*pair.first);
309
1.15k
        auto& map = pair.second;
310
1.15k
        map.clear();
311
1.15k
    }
312
9
}
313
314
FragmentMgr::FragmentMgr(ExecEnv* exec_env)
315
9
        : _exec_env(exec_env), _stop_background_threads_latch(1) {
316
9
    _entity = DorisMetrics::instance()->metric_registry()->register_entity("FragmentMgr");
317
9
    INT_UGAUGE_METRIC_REGISTER(_entity, timeout_canceled_fragment_count);
318
319
9
    auto s = Thread::create(
320
9
            "FragmentMgr", "cancel_timeout_plan_fragment", [this]() { this->cancel_worker(); },
321
9
            &_cancel_thread);
322
9
    CHECK(s.ok()) << s.to_string();
323
324
9
    s = ThreadPoolBuilder("FragmentMgrAsyncWorkThreadPool")
325
9
                .set_min_threads(config::fragment_mgr_async_work_pool_thread_num_min)
326
9
                .set_max_threads(config::fragment_mgr_async_work_pool_thread_num_max)
327
9
                .set_max_queue_size(config::fragment_mgr_async_work_pool_queue_size)
328
9
                .build(&_thread_pool);
329
9
    CHECK(s.ok()) << s.to_string();
330
9
}
331
332
9
FragmentMgr::~FragmentMgr() = default;
333
334
9
void FragmentMgr::stop() {
335
9
    DEREGISTER_HOOK_METRIC(fragment_instance_count);
336
9
    _stop_background_threads_latch.count_down();
337
9
    if (_cancel_thread) {
338
9
        _cancel_thread->join();
339
9
    }
340
341
9
    _thread_pool->shutdown();
342
    // Only me can delete
343
9
    _query_ctx_map.clear();
344
    // in one BE's graceful shutdown, cancel_worker will get related running queries via _get_all_running_queries_from_fe and cancel them.
345
    // so clearing here will not make RF consumer hang. if we dont do this, in ~FragmentMgr() there may be QueryContext in _query_ctx_map_delay_delete
346
    // destructred and remove it from _query_ctx_map_delay_delete which is destructring. it's UB.
347
9
    _query_ctx_map_delay_delete.clear();
348
9
    _pipeline_map.clear();
349
9
}
350
351
0
std::string FragmentMgr::to_http_path(const std::string& file_name) {
352
0
    std::stringstream url;
353
0
    url << "http://" << BackendOptions::get_localhost() << ":" << config::webserver_port
354
0
        << "/api/_download_load?"
355
0
        << "token=" << _exec_env->token() << "&file=" << file_name;
356
0
    return url.str();
357
0
}
358
359
Status FragmentMgr::trigger_pipeline_context_report(
360
0
        const ReportStatusRequest req, std::shared_ptr<pipeline::PipelineFragmentContext>&& ctx) {
361
0
    return _thread_pool->submit_func([this, req, ctx]() {
362
0
        SCOPED_ATTACH_TASK(ctx->get_query_ctx()->query_mem_tracker());
363
0
        coordinator_callback(req);
364
0
        if (!req.done) {
365
0
            ctx->refresh_next_report_time();
366
0
        }
367
0
    });
368
0
}
369
370
// There can only be one of these callbacks in-flight at any moment, because
371
// it is only invoked from the executor's reporting thread.
372
// Also, the reported status will always reflect the most recent execution status,
373
// including the final status when execution finishes.
374
0
void FragmentMgr::coordinator_callback(const ReportStatusRequest& req) {
375
0
    DBUG_EXECUTE_IF("FragmentMgr::coordinator_callback.report_delay", {
376
0
        int random_seconds = req.status.is<ErrorCode::DATA_QUALITY_ERROR>() ? 8 : 2;
377
0
        LOG_INFO("sleep : ").tag("time", random_seconds).tag("query_id", print_id(req.query_id));
378
0
        std::this_thread::sleep_for(std::chrono::seconds(random_seconds));
379
0
        LOG_INFO("sleep done").tag("query_id", print_id(req.query_id));
380
0
    });
381
382
0
    DCHECK(req.status.ok() || req.done); // if !status.ok() => done
383
0
    if (req.coord_addr.hostname == "external") {
384
        // External query (flink/spark read tablets) not need to report to FE.
385
0
        return;
386
0
    }
387
0
    int callback_retries = 10;
388
0
    const int sleep_ms = 1000;
389
0
    Status exec_status = req.status;
390
0
    Status coord_status;
391
0
    std::unique_ptr<FrontendServiceConnection> coord = nullptr;
392
0
    do {
393
0
        coord = std::make_unique<FrontendServiceConnection>(_exec_env->frontend_client_cache(),
394
0
                                                            req.coord_addr, &coord_status);
395
0
        if (!coord_status.ok()) {
396
0
            std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
397
0
        }
398
0
    } while (!coord_status.ok() && callback_retries-- > 0);
399
400
0
    if (!coord_status.ok()) {
401
0
        std::stringstream ss;
402
0
        UniqueId uid(req.query_id.hi, req.query_id.lo);
403
0
        static_cast<void>(req.cancel_fn(Status::InternalError(
404
0
                "query_id: {}, couldn't get a client for {}, reason is {}", uid.to_string(),
405
0
                PrintThriftNetworkAddress(req.coord_addr), coord_status.to_string())));
406
0
        return;
407
0
    }
408
409
0
    TReportExecStatusParams params;
410
0
    params.protocol_version = FrontendServiceVersion::V1;
411
0
    params.__set_query_id(req.query_id);
412
0
    params.__set_backend_num(req.backend_num);
413
0
    params.__set_fragment_instance_id(req.fragment_instance_id);
414
0
    params.__set_fragment_id(req.fragment_id);
415
0
    params.__set_status(exec_status.to_thrift());
416
0
    params.__set_done(req.done);
417
0
    params.__set_query_type(req.runtime_state->query_type());
418
0
    params.__isset.profile = false;
419
420
0
    DCHECK(req.runtime_state != nullptr);
421
422
0
    if (req.runtime_state->query_type() == TQueryType::LOAD) {
423
0
        params.__set_loaded_rows(req.runtime_state->num_rows_load_total());
424
0
        params.__set_loaded_bytes(req.runtime_state->num_bytes_load_total());
425
0
    } else {
426
0
        DCHECK(!req.runtime_states.empty());
427
0
        if (!req.runtime_state->output_files().empty()) {
428
0
            params.__isset.delta_urls = true;
429
0
            for (auto& it : req.runtime_state->output_files()) {
430
0
                params.delta_urls.push_back(to_http_path(it));
431
0
            }
432
0
        }
433
0
        if (!params.delta_urls.empty()) {
434
0
            params.__isset.delta_urls = true;
435
0
        }
436
0
    }
437
438
    // load rows
439
0
    static std::string s_dpp_normal_all = "dpp.norm.ALL";
440
0
    static std::string s_dpp_abnormal_all = "dpp.abnorm.ALL";
441
0
    static std::string s_unselected_rows = "unselected.rows";
442
0
    int64_t num_rows_load_success = 0;
443
0
    int64_t num_rows_load_filtered = 0;
444
0
    int64_t num_rows_load_unselected = 0;
445
0
    if (req.runtime_state->num_rows_load_total() > 0 ||
446
0
        req.runtime_state->num_rows_load_filtered() > 0 ||
447
0
        req.runtime_state->num_finished_range() > 0) {
448
0
        params.__isset.load_counters = true;
449
450
0
        num_rows_load_success = req.runtime_state->num_rows_load_success();
451
0
        num_rows_load_filtered = req.runtime_state->num_rows_load_filtered();
452
0
        num_rows_load_unselected = req.runtime_state->num_rows_load_unselected();
453
0
        params.__isset.fragment_instance_reports = true;
454
0
        TFragmentInstanceReport t;
455
0
        t.__set_fragment_instance_id(req.runtime_state->fragment_instance_id());
456
0
        t.__set_num_finished_range(cast_set<int>(req.runtime_state->num_finished_range()));
457
0
        t.__set_loaded_rows(req.runtime_state->num_rows_load_total());
458
0
        t.__set_loaded_bytes(req.runtime_state->num_bytes_load_total());
459
0
        params.fragment_instance_reports.push_back(t);
460
0
    } else if (!req.runtime_states.empty()) {
461
0
        for (auto* rs : req.runtime_states) {
462
0
            if (rs->num_rows_load_total() > 0 || rs->num_rows_load_filtered() > 0 ||
463
0
                rs->num_finished_range() > 0) {
464
0
                params.__isset.load_counters = true;
465
0
                num_rows_load_success += rs->num_rows_load_success();
466
0
                num_rows_load_filtered += rs->num_rows_load_filtered();
467
0
                num_rows_load_unselected += rs->num_rows_load_unselected();
468
0
                params.__isset.fragment_instance_reports = true;
469
0
                TFragmentInstanceReport t;
470
0
                t.__set_fragment_instance_id(rs->fragment_instance_id());
471
0
                t.__set_num_finished_range(cast_set<int>(rs->num_finished_range()));
472
0
                t.__set_loaded_rows(rs->num_rows_load_total());
473
0
                t.__set_loaded_bytes(rs->num_bytes_load_total());
474
0
                params.fragment_instance_reports.push_back(t);
475
0
            }
476
0
        }
477
0
    }
478
0
    params.load_counters.emplace(s_dpp_normal_all, std::to_string(num_rows_load_success));
479
0
    params.load_counters.emplace(s_dpp_abnormal_all, std::to_string(num_rows_load_filtered));
480
0
    params.load_counters.emplace(s_unselected_rows, std::to_string(num_rows_load_unselected));
481
482
0
    if (!req.load_error_url.empty()) {
483
0
        params.__set_tracking_url(req.load_error_url);
484
0
    }
485
0
    if (!req.first_error_msg.empty()) {
486
0
        params.__set_first_error_msg(req.first_error_msg);
487
0
    }
488
0
    for (auto* rs : req.runtime_states) {
489
0
        if (rs->wal_id() > 0) {
490
0
            params.__set_txn_id(rs->wal_id());
491
0
            params.__set_label(rs->import_label());
492
0
        }
493
0
    }
494
0
    if (!req.runtime_state->export_output_files().empty()) {
495
0
        params.__isset.export_files = true;
496
0
        params.export_files = req.runtime_state->export_output_files();
497
0
    } else if (!req.runtime_states.empty()) {
498
0
        for (auto* rs : req.runtime_states) {
499
0
            if (!rs->export_output_files().empty()) {
500
0
                params.__isset.export_files = true;
501
0
                params.export_files.insert(params.export_files.end(),
502
0
                                           rs->export_output_files().begin(),
503
0
                                           rs->export_output_files().end());
504
0
            }
505
0
        }
506
0
    }
507
0
    if (auto tci = req.runtime_state->tablet_commit_infos(); !tci.empty()) {
508
0
        params.__isset.commitInfos = true;
509
0
        params.commitInfos.insert(params.commitInfos.end(), tci.begin(), tci.end());
510
0
    } else if (!req.runtime_states.empty()) {
511
0
        for (auto* rs : req.runtime_states) {
512
0
            if (auto rs_tci = rs->tablet_commit_infos(); !rs_tci.empty()) {
513
0
                params.__isset.commitInfos = true;
514
0
                params.commitInfos.insert(params.commitInfos.end(), rs_tci.begin(), rs_tci.end());
515
0
            }
516
0
        }
517
0
    }
518
0
    if (auto eti = req.runtime_state->error_tablet_infos(); !eti.empty()) {
519
0
        params.__isset.errorTabletInfos = true;
520
0
        params.errorTabletInfos.insert(params.errorTabletInfos.end(), eti.begin(), eti.end());
521
0
    } else if (!req.runtime_states.empty()) {
522
0
        for (auto* rs : req.runtime_states) {
523
0
            if (auto rs_eti = rs->error_tablet_infos(); !rs_eti.empty()) {
524
0
                params.__isset.errorTabletInfos = true;
525
0
                params.errorTabletInfos.insert(params.errorTabletInfos.end(), rs_eti.begin(),
526
0
                                               rs_eti.end());
527
0
            }
528
0
        }
529
0
    }
530
0
    if (auto hpu = req.runtime_state->hive_partition_updates(); !hpu.empty()) {
531
0
        params.__isset.hive_partition_updates = true;
532
0
        params.hive_partition_updates.insert(params.hive_partition_updates.end(), hpu.begin(),
533
0
                                             hpu.end());
534
0
    } else if (!req.runtime_states.empty()) {
535
0
        for (auto* rs : req.runtime_states) {
536
0
            if (auto rs_hpu = rs->hive_partition_updates(); !rs_hpu.empty()) {
537
0
                params.__isset.hive_partition_updates = true;
538
0
                params.hive_partition_updates.insert(params.hive_partition_updates.end(),
539
0
                                                     rs_hpu.begin(), rs_hpu.end());
540
0
            }
541
0
        }
542
0
    }
543
0
    if (auto icd = req.runtime_state->iceberg_commit_datas(); !icd.empty()) {
544
0
        params.__isset.iceberg_commit_datas = true;
545
0
        params.iceberg_commit_datas.insert(params.iceberg_commit_datas.end(), icd.begin(),
546
0
                                           icd.end());
547
0
    } else if (!req.runtime_states.empty()) {
548
0
        for (auto* rs : req.runtime_states) {
549
0
            if (auto rs_icd = rs->iceberg_commit_datas(); !rs_icd.empty()) {
550
0
                params.__isset.iceberg_commit_datas = true;
551
0
                params.iceberg_commit_datas.insert(params.iceberg_commit_datas.end(),
552
0
                                                   rs_icd.begin(), rs_icd.end());
553
0
            }
554
0
        }
555
0
    }
556
557
    // Send new errors to coordinator
558
0
    req.runtime_state->get_unreported_errors(&(params.error_log));
559
0
    params.__isset.error_log = (!params.error_log.empty());
560
561
0
    if (_exec_env->cluster_info()->backend_id != 0) {
562
0
        params.__set_backend_id(_exec_env->cluster_info()->backend_id);
563
0
    }
564
565
0
    TReportExecStatusResult res;
566
0
    Status rpc_status;
567
568
0
    VLOG_DEBUG << "reportExecStatus params is "
569
0
               << apache::thrift::ThriftDebugString(params).c_str();
570
0
    if (!exec_status.ok()) {
571
0
        LOG(WARNING) << "report error status: " << exec_status.msg()
572
0
                     << " to coordinator: " << req.coord_addr
573
0
                     << ", query id: " << print_id(req.query_id);
574
0
    }
575
0
    try {
576
0
        try {
577
0
            (*coord)->reportExecStatus(res, params);
578
0
        } catch ([[maybe_unused]] TTransportException& e) {
579
#ifndef ADDRESS_SANITIZER
580
            LOG(WARNING) << "Retrying ReportExecStatus. query id: " << print_id(req.query_id)
581
                         << ", instance id: " << print_id(req.fragment_instance_id) << " to "
582
                         << req.coord_addr << ", err: " << e.what();
583
#endif
584
0
            rpc_status = coord->reopen();
585
586
0
            if (!rpc_status.ok()) {
587
                // we need to cancel the execution of this fragment
588
0
                req.cancel_fn(rpc_status);
589
0
                return;
590
0
            }
591
0
            (*coord)->reportExecStatus(res, params);
592
0
        }
593
594
0
        rpc_status = Status::create<false>(res.status);
595
0
    } catch (TException& e) {
596
0
        rpc_status = Status::InternalError("ReportExecStatus() to {} failed: {}",
597
0
                                           PrintThriftNetworkAddress(req.coord_addr), e.what());
598
0
    }
599
600
0
    if (!rpc_status.ok()) {
601
0
        LOG_INFO("Going to cancel query {} since report exec status got rpc failed: {}",
602
0
                 print_id(req.query_id), rpc_status.to_string());
603
        // we need to cancel the execution of this fragment
604
0
        req.cancel_fn(rpc_status);
605
0
    }
606
0
}
607
608
0
static void empty_function(RuntimeState*, Status*) {}
609
610
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
611
                                       const QuerySource query_source,
612
0
                                       const TPipelineFragmentParamsList& parent) {
613
0
    if (params.txn_conf.need_txn) {
614
0
        std::shared_ptr<StreamLoadContext> stream_load_ctx =
615
0
                std::make_shared<StreamLoadContext>(_exec_env);
616
0
        stream_load_ctx->db = params.txn_conf.db;
617
0
        stream_load_ctx->db_id = params.txn_conf.db_id;
618
0
        stream_load_ctx->table = params.txn_conf.tbl;
619
0
        stream_load_ctx->txn_id = params.txn_conf.txn_id;
620
0
        stream_load_ctx->id = UniqueId(params.query_id);
621
0
        stream_load_ctx->put_result.__set_pipeline_params(params);
622
0
        stream_load_ctx->use_streaming = true;
623
0
        stream_load_ctx->load_type = TLoadType::MANUL_LOAD;
624
0
        stream_load_ctx->load_src_type = TLoadSourceType::RAW;
625
0
        stream_load_ctx->label = params.import_label;
626
0
        stream_load_ctx->format = TFileFormatType::FORMAT_CSV_PLAIN;
627
0
        stream_load_ctx->timeout_second = 3600;
628
0
        stream_load_ctx->auth.token = params.txn_conf.token;
629
0
        stream_load_ctx->need_commit_self = true;
630
0
        stream_load_ctx->need_rollback = true;
631
0
        auto pipe = std::make_shared<io::StreamLoadPipe>(
632
0
                io::kMaxPipeBufferedBytes /* max_buffered_bytes */, 64 * 1024 /* min_chunk_size */,
633
0
                -1 /* total_length */, true /* use_proto */);
634
0
        stream_load_ctx->body_sink = pipe;
635
0
        stream_load_ctx->pipe = pipe;
636
0
        stream_load_ctx->max_filter_ratio = params.txn_conf.max_filter_ratio;
637
638
0
        RETURN_IF_ERROR(
639
0
                _exec_env->new_load_stream_mgr()->put(stream_load_ctx->id, stream_load_ctx));
640
641
0
        RETURN_IF_ERROR(
642
0
                _exec_env->stream_load_executor()->execute_plan_fragment(stream_load_ctx, parent));
643
0
        return Status::OK();
644
0
    } else {
645
0
        return exec_plan_fragment(params, query_source, empty_function, parent);
646
0
    }
647
0
}
648
649
// Stage 2. prepare finished. then get FE instruction to execute
650
0
Status FragmentMgr::start_query_execution(const PExecPlanFragmentStartRequest* request) {
651
0
    TUniqueId query_id;
652
0
    query_id.__set_hi(request->query_id().hi());
653
0
    query_id.__set_lo(request->query_id().lo());
654
0
    auto q_ctx = get_query_ctx(query_id);
655
0
    if (q_ctx) {
656
0
        q_ctx->set_ready_to_execute(Status::OK());
657
0
        LOG_INFO("Query {} start execution", print_id(query_id));
658
0
    } else {
659
0
        return Status::InternalError(
660
0
                "Failed to get query fragments context. Query {} may be "
661
0
                "timeout or be cancelled. host: {}",
662
0
                print_id(query_id), BackendOptions::get_localhost());
663
0
    }
664
0
    return Status::OK();
665
0
}
666
667
0
void FragmentMgr::remove_pipeline_context(std::pair<TUniqueId, int> key) {
668
0
    int64_t now = duration_cast<std::chrono::milliseconds>(
669
0
                          std::chrono::system_clock::now().time_since_epoch())
670
0
                          .count();
671
0
    g_fragment_executing_count << -1;
672
0
    g_fragment_last_active_time.set_value(now);
673
674
0
    _pipeline_map.erase(key);
675
0
}
676
677
1
void FragmentMgr::remove_query_context(const TUniqueId& key) {
678
1
    _query_ctx_map_delay_delete.erase(key);
679
#ifndef BE_TEST
680
    _query_ctx_map.erase(key);
681
#endif
682
1
}
683
684
5
std::shared_ptr<QueryContext> FragmentMgr::get_query_ctx(const TUniqueId& query_id) {
685
5
    auto val = _query_ctx_map.find(query_id);
686
5
    if (auto q_ctx = val.lock()) {
687
1
        return q_ctx;
688
1
    }
689
4
    return nullptr;
690
5
}
691
692
Status FragmentMgr::_get_or_create_query_ctx(const TPipelineFragmentParams& params,
693
                                             const TPipelineFragmentParamsList& parent,
694
                                             QuerySource query_source,
695
3
                                             std::shared_ptr<QueryContext>& query_ctx) {
696
3
    auto query_id = params.query_id;
697
3
    DBUG_EXECUTE_IF("FragmentMgr._get_query_ctx.failed", {
698
3
        return Status::InternalError("FragmentMgr._get_query_ctx.failed, query id {}",
699
3
                                     print_id(query_id));
700
3
    });
701
702
    // Find _query_ctx_map, in case some other request has already
703
    // create the query fragments context.
704
3
    query_ctx = get_query_ctx(query_id);
705
3
    if (params.is_simplified_param) {
706
        // Get common components from _query_ctx_map
707
0
        if (!query_ctx) {
708
0
            return Status::InternalError(
709
0
                    "Failed to get query fragments context. Query {} may be timeout or be "
710
0
                    "cancelled. host: {}",
711
0
                    print_id(query_id), BackendOptions::get_localhost());
712
0
        }
713
3
    } else {
714
3
        if (!query_ctx) {
715
3
            RETURN_IF_ERROR(_query_ctx_map.apply_if_not_exists(
716
3
                    query_id, query_ctx,
717
3
                    [&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map)
718
3
                            -> Status {
719
3
                        WorkloadGroupPtr workload_group_ptr = nullptr;
720
3
                        std::vector<uint64_t> wg_id_set;
721
3
                        if (params.__isset.workload_groups && !params.workload_groups.empty()) {
722
3
                            for (auto& wg : params.workload_groups) {
723
3
                                wg_id_set.push_back(wg.id);
724
3
                            }
725
3
                        }
726
3
                        workload_group_ptr = _exec_env->workload_group_mgr()->get_group(wg_id_set);
727
728
                        // First time a fragment of a query arrived. print logs.
729
3
                        LOG(INFO) << "query_id: " << print_id(query_id)
730
3
                                  << ", coord_addr: " << params.coord
731
3
                                  << ", total fragment num on current host: "
732
3
                                  << params.fragment_num_on_host
733
3
                                  << ", fe process uuid: " << params.query_options.fe_process_uuid
734
3
                                  << ", query type: " << params.query_options.query_type
735
3
                                  << ", report audit fe:" << params.current_connect_fe
736
3
                                  << ", use wg:" << workload_group_ptr->id() << ","
737
3
                                  << workload_group_ptr->name();
738
739
                        // This may be a first fragment request of the query.
740
                        // Create the query fragments context.
741
                        // Cross-cluster query: coordinator FE may not belong to local cluster.
742
                        // In that case, cancel_worker() should not cancel it based on local FE liveness.
743
3
                        QuerySource actual_query_source = query_source;
744
3
                        if (query_source == QuerySource::INTERNAL_FRONTEND &&
745
3
                            !_exec_env->get_running_frontends().contains(params.coord)) {
746
3
                            actual_query_source = QuerySource::EXTERNAL_FRONTEND;
747
3
                        }
748
3
                        query_ctx = QueryContext::create(
749
3
                                query_id, _exec_env, params.query_options, params.coord,
750
3
                                params.is_nereids, params.current_connect_fe, actual_query_source);
751
3
                        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(query_ctx->query_mem_tracker());
752
3
                        RETURN_IF_ERROR(DescriptorTbl::create(
753
3
                                &(query_ctx->obj_pool), params.desc_tbl, &(query_ctx->desc_tbl)));
754
                        // set file scan range params
755
3
                        if (params.__isset.file_scan_params) {
756
3
                            query_ctx->file_scan_range_params_map = params.file_scan_params;
757
3
                        }
758
759
3
                        query_ctx->query_globals = params.query_globals;
760
761
3
                        if (params.__isset.resource_info) {
762
3
                            query_ctx->user = params.resource_info.user;
763
3
                            query_ctx->group = params.resource_info.group;
764
3
                            query_ctx->set_rsc_info = true;
765
3
                        }
766
767
3
                        if (params.__isset.ai_resources) {
768
3
                            query_ctx->set_ai_resources(params.ai_resources);
769
3
                        }
770
771
3
                        RETURN_IF_ERROR(query_ctx->set_workload_group(workload_group_ptr));
772
773
3
                        if (parent.__isset.runtime_filter_info) {
774
3
                            auto info = parent.runtime_filter_info;
775
3
                            if (info.__isset.runtime_filter_params) {
776
3
                                auto handler =
777
3
                                        std::make_shared<RuntimeFilterMergeControllerEntity>();
778
3
                                RETURN_IF_ERROR(
779
3
                                        handler->init(query_ctx, info.runtime_filter_params));
780
3
                                query_ctx->set_merge_controller_handler(handler);
781
782
3
                                query_ctx->runtime_filter_mgr()->set_runtime_filter_params(
783
3
                                        info.runtime_filter_params);
784
3
                                if (!handler->empty()) {
785
3
                                    _query_ctx_map_delay_delete.insert(query_id, query_ctx);
786
3
                                }
787
3
                            }
788
3
                            if (info.__isset.topn_filter_descs) {
789
3
                                query_ctx->init_runtime_predicates(info.topn_filter_descs);
790
3
                            }
791
3
                        }
792
793
                        // There is some logic in query ctx's dctor, we could not check if exists and delete the
794
                        // temp query ctx now. For example, the query id maybe removed from workload group's queryset.
795
3
                        map.insert({query_id, query_ctx});
796
3
                        return Status::OK();
797
3
                    }));
798
3
        }
799
3
    }
800
3
    return Status::OK();
801
3
}
802
803
0
std::string FragmentMgr::dump_pipeline_tasks(int64_t duration) {
804
0
    fmt::memory_buffer debug_string_buffer;
805
0
    size_t i = 0;
806
0
    {
807
0
        fmt::format_to(debug_string_buffer,
808
0
                       "{} pipeline fragment contexts are still running! duration_limit={}\n",
809
0
                       _pipeline_map.num_items(), duration);
810
0
        timespec now;
811
0
        clock_gettime(CLOCK_MONOTONIC, &now);
812
813
0
        _pipeline_map.apply([&](phmap::flat_hash_map<
814
0
                                    std::pair<TUniqueId, int>,
815
0
                                    std::shared_ptr<pipeline::PipelineFragmentContext>>& map)
816
0
                                    -> Status {
817
0
            std::set<TUniqueId> query_id_set;
818
0
            for (auto& it : map) {
819
0
                auto elapsed = it.second->elapsed_time() / 1000000000;
820
0
                if (elapsed < duration) {
821
                    // Only display tasks which has been running for more than {duration} seconds.
822
0
                    continue;
823
0
                }
824
0
                if (!query_id_set.contains(it.first.first)) {
825
0
                    query_id_set.insert(it.first.first);
826
0
                    fmt::format_to(
827
0
                            debug_string_buffer, "QueryId: {}, global_runtime_filter_mgr: {}\n",
828
0
                            print_id(it.first.first),
829
0
                            it.second->get_query_ctx()->runtime_filter_mgr()->debug_string());
830
831
0
                    if (it.second->get_query_ctx()->get_merge_controller_handler()) {
832
0
                        fmt::format_to(debug_string_buffer, "{}\n",
833
0
                                       it.second->get_query_ctx()
834
0
                                               ->get_merge_controller_handler()
835
0
                                               ->debug_string());
836
0
                    }
837
0
                }
838
839
0
                auto timeout_second = it.second->timeout_second();
840
0
                fmt::format_to(
841
0
                        debug_string_buffer,
842
0
                        "No.{} (elapse_second={}s, query_timeout_second={}s, is_timeout={}): {}\n",
843
0
                        i, elapsed, timeout_second, it.second->is_timeout(now),
844
0
                        it.second->debug_string());
845
0
                i++;
846
0
            }
847
0
            return Status::OK();
848
0
        });
849
0
    }
850
0
    return fmt::to_string(debug_string_buffer);
851
0
}
852
853
0
std::string FragmentMgr::dump_pipeline_tasks(TUniqueId& query_id) {
854
0
    if (auto q_ctx = get_query_ctx(query_id)) {
855
0
        return q_ctx->print_all_pipeline_context();
856
0
    } else {
857
0
        return fmt::format(
858
0
                "Dump pipeline tasks failed: Query context (query id = {}) not found. \n",
859
0
                print_id(query_id));
860
0
    }
861
0
}
862
863
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
864
                                       QuerySource query_source, const FinishCallback& cb,
865
0
                                       const TPipelineFragmentParamsList& parent) {
866
0
    VLOG_ROW << "Query: " << print_id(params.query_id) << " exec_plan_fragment params is "
867
0
             << apache::thrift::ThriftDebugString(params).c_str();
868
    // sometimes TPipelineFragmentParams debug string is too long and glog
869
    // will truncate the log line, so print query options seperately for debuggin purpose
870
0
    VLOG_ROW << "Query: " << print_id(params.query_id) << "query options is "
871
0
             << apache::thrift::ThriftDebugString(params.query_options).c_str();
872
873
0
    std::shared_ptr<QueryContext> query_ctx;
874
0
    RETURN_IF_ERROR(_get_or_create_query_ctx(params, parent, query_source, query_ctx));
875
0
    SCOPED_ATTACH_TASK(query_ctx.get()->resource_ctx());
876
0
    int64_t duration_ns = 0;
877
0
    std::shared_ptr<pipeline::PipelineFragmentContext> context =
878
0
            std::make_shared<pipeline::PipelineFragmentContext>(
879
0
                    query_ctx->query_id(), params, query_ctx, _exec_env, cb,
880
0
                    [this](const ReportStatusRequest& req, auto&& ctx) {
881
0
                        return this->trigger_pipeline_context_report(req, std::move(ctx));
882
0
                    });
883
0
    {
884
0
        SCOPED_RAW_TIMER(&duration_ns);
885
0
        Status prepare_st = Status::OK();
886
0
        ASSIGN_STATUS_IF_CATCH_EXCEPTION(prepare_st = context->prepare(_thread_pool.get()),
887
0
                                         prepare_st);
888
0
        DBUG_EXECUTE_IF("FragmentMgr.exec_plan_fragment.prepare_failed", {
889
0
            prepare_st = Status::Aborted("FragmentMgr.exec_plan_fragment.prepare_failed");
890
0
        });
891
0
        if (!prepare_st.ok()) {
892
0
            query_ctx->cancel(prepare_st, params.fragment_id);
893
0
            return prepare_st;
894
0
        }
895
0
    }
896
0
    g_fragmentmgr_prepare_latency << (duration_ns / 1000);
897
898
0
    DBUG_EXECUTE_IF("FragmentMgr.exec_plan_fragment.failed",
899
0
                    { return Status::Aborted("FragmentMgr.exec_plan_fragment.failed"); });
900
0
    {
901
0
        int64_t now = duration_cast<std::chrono::milliseconds>(
902
0
                              std::chrono::system_clock::now().time_since_epoch())
903
0
                              .count();
904
0
        g_fragment_executing_count << 1;
905
0
        g_fragment_last_active_time.set_value(now);
906
907
        // (query_id, fragment_id) is executed only on one BE, locks _pipeline_map.
908
0
        auto res = _pipeline_map.find({params.query_id, params.fragment_id});
909
0
        if (res != nullptr) {
910
0
            return Status::InternalError(
911
0
                    "exec_plan_fragment query_id({}) input duplicated fragment_id({})",
912
0
                    print_id(params.query_id), params.fragment_id);
913
0
        }
914
0
        _pipeline_map.insert({params.query_id, params.fragment_id}, context);
915
0
    }
916
917
0
    if (!params.__isset.need_wait_execution_trigger || !params.need_wait_execution_trigger) {
918
0
        query_ctx->set_ready_to_execute_only();
919
0
    }
920
921
0
    query_ctx->set_pipeline_context(params.fragment_id, context);
922
923
0
    RETURN_IF_ERROR(context->submit());
924
0
    return Status::OK();
925
0
}
926
927
2
void FragmentMgr::cancel_query(const TUniqueId query_id, const Status reason) {
928
2
    std::shared_ptr<QueryContext> query_ctx = nullptr;
929
2
    {
930
2
        if (auto q_ctx = get_query_ctx(query_id)) {
931
1
            query_ctx = q_ctx;
932
1
        } else {
933
1
            LOG(WARNING) << "Query " << print_id(query_id)
934
1
                         << " does not exists, failed to cancel it";
935
1
            return;
936
1
        }
937
2
    }
938
1
    SCOPED_ATTACH_TASK(query_ctx->resource_ctx());
939
1
    query_ctx->cancel(reason);
940
1
    remove_query_context(query_id);
941
1
    LOG(INFO) << "Query " << print_id(query_id)
942
1
              << " is cancelled and removed. Reason: " << reason.to_string();
943
1
}
944
945
9
void FragmentMgr::cancel_worker() {
946
9
    LOG(INFO) << "FragmentMgr cancel worker start working.";
947
948
9
    timespec check_invalid_query_last_timestamp;
949
9
    clock_gettime(CLOCK_MONOTONIC, &check_invalid_query_last_timestamp);
950
951
15
    do {
952
15
        std::vector<TUniqueId> queries_lost_coordinator;
953
15
        std::vector<TUniqueId> queries_timeout;
954
15
        std::vector<TUniqueId> queries_pipeline_task_leak;
955
        // Fe process uuid -> set<QueryId>
956
15
        std::map<int64_t, std::unordered_set<TUniqueId>> running_queries_on_all_fes;
957
15
        const std::map<TNetworkAddress, FrontendInfo>& running_fes =
958
15
                ExecEnv::GetInstance()->get_running_frontends();
959
960
15
        timespec now;
961
15
        clock_gettime(CLOCK_MONOTONIC, &now);
962
963
15
        if (config::enable_pipeline_task_leakage_detect &&
964
15
            now.tv_sec - check_invalid_query_last_timestamp.tv_sec >
965
0
                    config::pipeline_task_leakage_detect_period_secs) {
966
0
            check_invalid_query_last_timestamp = now;
967
0
            running_queries_on_all_fes = _get_all_running_queries_from_fe();
968
15
        } else {
969
15
            running_queries_on_all_fes.clear();
970
15
        }
971
972
15
        std::vector<std::shared_ptr<pipeline::PipelineFragmentContext>> ctx;
973
15
        _pipeline_map.apply(
974
15
                [&](phmap::flat_hash_map<std::pair<TUniqueId, int>,
975
15
                                         std::shared_ptr<pipeline::PipelineFragmentContext>>& map)
976
1.92k
                        -> Status {
977
1.92k
                    ctx.reserve(ctx.size() + map.size());
978
1.92k
                    for (auto& pipeline_itr : map) {
979
0
                        ctx.push_back(pipeline_itr.second);
980
0
                    }
981
1.92k
                    return Status::OK();
982
1.92k
                });
983
15
        for (auto& c : ctx) {
984
0
            c->clear_finished_tasks();
985
0
        }
986
987
15
        std::unordered_map<std::shared_ptr<PBackendService_Stub>, BrpcItem> brpc_stub_with_queries;
988
15
        {
989
15
            std::vector<std::shared_ptr<QueryContext>> contexts;
990
15
            _query_ctx_map.apply([&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>&
991
1.92k
                                             map) -> Status {
992
1.92k
                for (auto it = map.begin(); it != map.end();) {
993
2
                    if (auto q_ctx = it->second.lock()) {
994
2
                        contexts.push_back(q_ctx);
995
2
                        if (q_ctx->is_timeout(now)) {
996
0
                            LOG_WARNING("Query {} is timeout", print_id(it->first));
997
0
                            queries_timeout.push_back(it->first);
998
2
                        } else if (config::enable_brpc_connection_check) {
999
0
                            auto brpc_stubs = q_ctx->get_using_brpc_stubs();
1000
0
                            for (auto& item : brpc_stubs) {
1001
0
                                if (!brpc_stub_with_queries.contains(item.second)) {
1002
0
                                    brpc_stub_with_queries.emplace(item.second,
1003
0
                                                                   BrpcItem {item.first, {q_ctx}});
1004
0
                                } else {
1005
0
                                    brpc_stub_with_queries[item.second].queries.emplace_back(q_ctx);
1006
0
                                }
1007
0
                            }
1008
0
                        }
1009
2
                        ++it;
1010
2
                    } else {
1011
0
                        it = map.erase(it);
1012
0
                    }
1013
2
                }
1014
1.92k
                return Status::OK();
1015
1.92k
            });
1016
15
            std::vector<std::shared_ptr<QueryContext>> {}.swap(contexts);
1017
1018
            // We use a very conservative cancel strategy.
1019
            // 0. If there are no running frontends, do not cancel any queries.
1020
            // 1. If query's process uuid is zero, do not cancel
1021
            // 2. If same process uuid, do not cancel
1022
            // 3. If fe has zero process uuid, do not cancel
1023
15
            if (running_fes.empty() && _query_ctx_map.num_items() != 0) {
1024
0
                LOG_EVERY_N(WARNING, 10)
1025
0
                        << "Could not find any running frontends, maybe we are upgrading or "
1026
0
                           "starting? "
1027
0
                        << "We will not cancel any outdated queries in this situation.";
1028
15
            } else {
1029
15
                std::vector<std::shared_ptr<QueryContext>> q_contexts;
1030
15
                _query_ctx_map.apply([&](phmap::flat_hash_map<TUniqueId,
1031
15
                                                              std::weak_ptr<QueryContext>>& map)
1032
1.92k
                                             -> Status {
1033
1.92k
                    for (const auto& it : map) {
1034
2
                        if (auto q_ctx = it.second.lock()) {
1035
                            // Cross-cluster query: coordinator FE is not in local `running_fes`,
1036
                            // we should not cancel it based on local coordinator liveness.
1037
2
                            if (q_ctx->get_query_source() == QuerySource::EXTERNAL_FRONTEND) {
1038
1
                                continue;
1039
1
                            }
1040
1
                            q_contexts.push_back(q_ctx);
1041
1
                            const int64_t fe_process_uuid = q_ctx->get_fe_process_uuid();
1042
1043
1
                            if (fe_process_uuid == 0) {
1044
                                // zero means this query is from a older version fe or
1045
                                // this fe is starting
1046
0
                                continue;
1047
0
                            }
1048
1049
                            // If the query is not running on the any frontends, cancel it.
1050
1
                            if (auto itr = running_queries_on_all_fes.find(fe_process_uuid);
1051
1
                                itr != running_queries_on_all_fes.end()) {
1052
                                // Query not found on this frontend, and the query arrives before the last check
1053
0
                                if (itr->second.find(it.first) == itr->second.end() &&
1054
                                    // tv_nsec represents the number of nanoseconds that have elapsed since the time point stored in tv_sec.
1055
                                    // tv_sec is enough, we do not need to check tv_nsec.
1056
0
                                    q_ctx->get_query_arrival_timestamp().tv_sec <
1057
0
                                            check_invalid_query_last_timestamp.tv_sec &&
1058
0
                                    q_ctx->get_query_source() == QuerySource::INTERNAL_FRONTEND) {
1059
0
                                    queries_pipeline_task_leak.push_back(q_ctx->query_id());
1060
0
                                    LOG_INFO(
1061
0
                                            "Query {}, type {} is not found on any frontends, "
1062
0
                                            "maybe it "
1063
0
                                            "is leaked.",
1064
0
                                            print_id(q_ctx->query_id()),
1065
0
                                            toString(q_ctx->get_query_source()));
1066
0
                                    continue;
1067
0
                                }
1068
0
                            }
1069
1070
1
                            auto itr = running_fes.find(q_ctx->coord_addr);
1071
1
                            if (itr != running_fes.end()) {
1072
0
                                if (fe_process_uuid == itr->second.info.process_uuid ||
1073
0
                                    itr->second.info.process_uuid == 0) {
1074
0
                                    continue;
1075
0
                                } else {
1076
0
                                    LOG_WARNING(
1077
0
                                            "Coordinator of query {} restarted, going to cancel "
1078
0
                                            "it.",
1079
0
                                            print_id(q_ctx->query_id()));
1080
0
                                }
1081
1
                            } else {
1082
                                // In some rear cases, the rpc port of follower is not updated in time,
1083
                                // then the port of this follower will be zero, but acutally it is still running,
1084
                                // and be has already received the query from follower.
1085
                                // So we need to check if host is in running_fes.
1086
1
                                bool fe_host_is_standing =
1087
1
                                        std::any_of(running_fes.begin(), running_fes.end(),
1088
1
                                                    [&q_ctx](const auto& fe) {
1089
1
                                                        return fe.first.hostname ==
1090
1
                                                                       q_ctx->coord_addr.hostname &&
1091
1
                                                               fe.first.port == 0;
1092
1
                                                    });
1093
1
                                if (fe_host_is_standing) {
1094
0
                                    LOG_WARNING(
1095
0
                                            "Coordinator {}:{} is not found, but its host is still "
1096
0
                                            "running with an unstable brpc port, not going to "
1097
0
                                            "cancel "
1098
0
                                            "it.",
1099
0
                                            q_ctx->coord_addr.hostname, q_ctx->coord_addr.port,
1100
0
                                            print_id(q_ctx->query_id()));
1101
0
                                    continue;
1102
1
                                } else {
1103
1
                                    LOG_WARNING(
1104
1
                                            "Could not find target coordinator {}:{} of query {}, "
1105
1
                                            "going to "
1106
1
                                            "cancel it.",
1107
1
                                            q_ctx->coord_addr.hostname, q_ctx->coord_addr.port,
1108
1
                                            print_id(q_ctx->query_id()));
1109
1
                                }
1110
1
                            }
1111
1
                        }
1112
                        // Coordinator of this query has already dead or query context has been released.
1113
1
                        queries_lost_coordinator.push_back(it.first);
1114
1
                    }
1115
1.92k
                    return Status::OK();
1116
1.92k
                });
1117
15
            }
1118
15
        }
1119
1120
15
        if (config::enable_brpc_connection_check) {
1121
0
            for (auto it : brpc_stub_with_queries) {
1122
0
                if (!it.first) {
1123
0
                    LOG(WARNING) << "brpc stub is nullptr, skip it.";
1124
0
                    continue;
1125
0
                }
1126
0
                _check_brpc_available(it.first, it.second);
1127
0
            }
1128
0
        }
1129
1130
15
        if (!queries_lost_coordinator.empty()) {
1131
1
            LOG(INFO) << "There are " << queries_lost_coordinator.size()
1132
1
                      << " queries need to be cancelled, coordinator dead or restarted.";
1133
1
        }
1134
1135
15
        for (const auto& qid : queries_timeout) {
1136
0
            cancel_query(qid,
1137
0
                         Status::Error<ErrorCode::TIMEOUT>(
1138
0
                                 "FragmentMgr cancel worker going to cancel timeout instance "));
1139
0
        }
1140
1141
15
        for (const auto& qid : queries_pipeline_task_leak) {
1142
            // Cancel the query, and maybe try to report debug info to fe so that we can
1143
            // collect debug info by sql or http api instead of search log.
1144
0
            cancel_query(qid, Status::Error<ErrorCode::ILLEGAL_STATE>(
1145
0
                                      "Potential pipeline task leakage"));
1146
0
        }
1147
1148
15
        for (const auto& qid : queries_lost_coordinator) {
1149
1
            cancel_query(qid, Status::Error<ErrorCode::CANCELLED>(
1150
1
                                      "Source frontend is not running or restarted"));
1151
1
        }
1152
1153
15
    } while (!_stop_background_threads_latch.wait_for(
1154
15
            std::chrono::seconds(config::fragment_mgr_cancel_worker_interval_seconds)));
1155
9
    LOG(INFO) << "FragmentMgr cancel worker is going to exit.";
1156
9
}
1157
1158
void FragmentMgr::_check_brpc_available(const std::shared_ptr<PBackendService_Stub>& brpc_stub,
1159
0
                                        const BrpcItem& brpc_item) {
1160
0
    const std::string message = "hello doris!";
1161
0
    std::string error_message;
1162
0
    int32_t failed_count = 0;
1163
0
    const int64_t check_timeout_ms =
1164
0
            std::max<int64_t>(100, config::brpc_connection_check_timeout_ms);
1165
1166
0
    while (true) {
1167
0
        PHandShakeRequest request;
1168
0
        request.set_hello(message);
1169
0
        PHandShakeResponse response;
1170
0
        brpc::Controller cntl;
1171
0
        cntl.set_timeout_ms(check_timeout_ms);
1172
0
        cntl.set_max_retry(10);
1173
0
        brpc_stub->hand_shake(&cntl, &request, &response, nullptr);
1174
1175
0
        if (cntl.Failed()) {
1176
0
            error_message = cntl.ErrorText();
1177
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
1178
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
1179
0
        } else if (response.has_status() && response.status().status_code() == 0) {
1180
0
            break;
1181
0
        } else {
1182
0
            error_message = response.DebugString();
1183
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
1184
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
1185
0
        }
1186
0
        failed_count++;
1187
0
        if (failed_count == 2) {
1188
0
            for (const auto& query_wptr : brpc_item.queries) {
1189
0
                auto query = query_wptr.lock();
1190
0
                if (query && !query->is_cancelled()) {
1191
0
                    query->cancel(Status::InternalError("brpc(dest: {}:{}) check failed: {}",
1192
0
                                                        brpc_item.network_address.hostname,
1193
0
                                                        brpc_item.network_address.port,
1194
0
                                                        error_message));
1195
0
                }
1196
0
            }
1197
1198
0
            LOG(WARNING) << "remove brpc stub from cache: " << brpc_item.network_address.hostname
1199
0
                         << ":" << brpc_item.network_address.port << ", error: " << error_message;
1200
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
1201
0
                    brpc_item.network_address.hostname, brpc_item.network_address.port);
1202
0
            break;
1203
0
        }
1204
0
    }
1205
0
}
1206
1207
0
void FragmentMgr::debug(std::stringstream& ss) {}
1208
/*
1209
 * 1. resolve opaqued_query_plan to thrift structure
1210
 * 2. build TPipelineFragmentParams
1211
 */
1212
Status FragmentMgr::exec_external_plan_fragment(const TScanOpenParams& params,
1213
                                                const TQueryPlanInfo& t_query_plan_info,
1214
                                                const TUniqueId& query_id,
1215
                                                const TUniqueId& fragment_instance_id,
1216
0
                                                std::vector<TScanColumnDesc>* selected_columns) {
1217
    // set up desc tbl
1218
0
    DescriptorTbl* desc_tbl = nullptr;
1219
0
    ObjectPool obj_pool;
1220
0
    Status st = DescriptorTbl::create(&obj_pool, t_query_plan_info.desc_tbl, &desc_tbl);
1221
0
    if (!st.ok()) {
1222
0
        LOG(WARNING) << "open context error: extract DescriptorTbl failure";
1223
0
        std::stringstream msg;
1224
0
        msg << " create DescriptorTbl error, should not be modified after returned Doris FE "
1225
0
               "processed";
1226
0
        return Status::InvalidArgument(msg.str());
1227
0
    }
1228
0
    TupleDescriptor* tuple_desc = desc_tbl->get_tuple_descriptor(0);
1229
0
    if (tuple_desc == nullptr) {
1230
0
        LOG(WARNING) << "open context error: extract TupleDescriptor failure";
1231
0
        std::stringstream msg;
1232
0
        msg << " get  TupleDescriptor error, should not be modified after returned Doris FE "
1233
0
               "processed";
1234
0
        return Status::InvalidArgument(msg.str());
1235
0
    }
1236
    // process selected columns form slots
1237
0
    for (const SlotDescriptor* slot : tuple_desc->slots()) {
1238
0
        TScanColumnDesc col;
1239
0
        col.__set_name(slot->col_name());
1240
0
        col.__set_type(to_thrift(slot->type()->get_primitive_type()));
1241
0
        selected_columns->emplace_back(std::move(col));
1242
0
    }
1243
1244
0
    VLOG_QUERY << "BackendService execute open()  TQueryPlanInfo: "
1245
0
               << apache::thrift::ThriftDebugString(t_query_plan_info);
1246
    // assign the param used to execute PlanFragment
1247
0
    TPipelineFragmentParams exec_fragment_params;
1248
0
    exec_fragment_params.protocol_version = (PaloInternalServiceVersion::type)0;
1249
0
    exec_fragment_params.__set_is_simplified_param(false);
1250
0
    exec_fragment_params.__set_fragment(t_query_plan_info.plan_fragment);
1251
0
    exec_fragment_params.__set_desc_tbl(t_query_plan_info.desc_tbl);
1252
1253
    // assign the param used for executing of PlanFragment-self
1254
0
    TPipelineInstanceParams fragment_exec_params;
1255
0
    exec_fragment_params.query_id = query_id;
1256
0
    fragment_exec_params.fragment_instance_id = fragment_instance_id;
1257
0
    exec_fragment_params.coord.hostname = "external";
1258
0
    std::map<::doris::TPlanNodeId, std::vector<TScanRangeParams>> per_node_scan_ranges;
1259
0
    std::vector<TScanRangeParams> scan_ranges;
1260
0
    std::vector<int64_t> tablet_ids = params.tablet_ids;
1261
0
    TNetworkAddress address;
1262
0
    address.hostname = BackendOptions::get_localhost();
1263
0
    address.port = doris::config::be_port;
1264
0
    std::map<int64_t, TTabletVersionInfo> tablet_info = t_query_plan_info.tablet_info;
1265
0
    for (auto tablet_id : params.tablet_ids) {
1266
0
        TPaloScanRange scan_range;
1267
0
        scan_range.db_name = params.database;
1268
0
        scan_range.table_name = params.table;
1269
0
        auto iter = tablet_info.find(tablet_id);
1270
0
        if (iter != tablet_info.end()) {
1271
0
            TTabletVersionInfo info = iter->second;
1272
0
            scan_range.tablet_id = tablet_id;
1273
0
            scan_range.version = std::to_string(info.version);
1274
            // Useless but it is required field in TPaloScanRange
1275
0
            scan_range.version_hash = "0";
1276
0
            scan_range.schema_hash = std::to_string(info.schema_hash);
1277
0
            scan_range.hosts.push_back(address);
1278
0
        } else {
1279
0
            std::stringstream msg;
1280
0
            msg << "tablet_id: " << tablet_id << " not found";
1281
0
            LOG(WARNING) << "tablet_id [ " << tablet_id << " ] not found";
1282
0
            return Status::NotFound(msg.str());
1283
0
        }
1284
0
        TScanRange doris_scan_range;
1285
0
        doris_scan_range.__set_palo_scan_range(scan_range);
1286
0
        TScanRangeParams scan_range_params;
1287
0
        scan_range_params.scan_range = doris_scan_range;
1288
0
        scan_ranges.push_back(scan_range_params);
1289
0
    }
1290
0
    per_node_scan_ranges.insert(std::make_pair((::doris::TPlanNodeId)0, scan_ranges));
1291
0
    fragment_exec_params.per_node_scan_ranges = per_node_scan_ranges;
1292
0
    exec_fragment_params.local_params.push_back(fragment_exec_params);
1293
0
    TQueryOptions query_options;
1294
0
    query_options.batch_size = params.batch_size;
1295
0
    query_options.execution_timeout = params.execution_timeout;
1296
0
    query_options.mem_limit = params.mem_limit;
1297
0
    query_options.query_type = TQueryType::EXTERNAL;
1298
0
    query_options.be_exec_version = BeExecVersionManager::get_newest_version();
1299
0
    exec_fragment_params.__set_query_options(query_options);
1300
0
    VLOG_ROW << "external exec_plan_fragment params is "
1301
0
             << apache::thrift::ThriftDebugString(exec_fragment_params).c_str();
1302
1303
0
    TPipelineFragmentParamsList mocked;
1304
0
    return exec_plan_fragment(exec_fragment_params, QuerySource::EXTERNAL_CONNECTOR, mocked);
1305
0
}
1306
1307
Status FragmentMgr::apply_filterv2(const PPublishFilterRequestV2* request,
1308
0
                                   butil::IOBufAsZeroCopyInputStream* attach_data) {
1309
0
    UniqueId queryid = request->query_id();
1310
0
    TUniqueId query_id;
1311
0
    query_id.__set_hi(queryid.hi);
1312
0
    query_id.__set_lo(queryid.lo);
1313
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1314
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1315
0
        RuntimeFilterMgr* runtime_filter_mgr = q_ctx->runtime_filter_mgr();
1316
0
        DCHECK(runtime_filter_mgr != nullptr);
1317
1318
        // 1. get the target filters
1319
0
        std::vector<std::shared_ptr<RuntimeFilterConsumer>> filters =
1320
0
                runtime_filter_mgr->get_consume_filters(request->filter_id());
1321
1322
        // 2. create the filter wrapper to replace or ignore/disable the target filters
1323
0
        if (!filters.empty()) {
1324
0
            RETURN_IF_ERROR(filters[0]->assign(*request, attach_data));
1325
0
            std::ranges::for_each(filters, [&](auto& filter) { filter->signal(filters[0].get()); });
1326
0
        }
1327
0
    }
1328
0
    return Status::OK();
1329
0
}
1330
1331
0
Status FragmentMgr::send_filter_size(const PSendFilterSizeRequest* request) {
1332
0
    UniqueId queryid = request->query_id();
1333
0
    TUniqueId query_id;
1334
0
    query_id.__set_hi(queryid.hi);
1335
0
    query_id.__set_lo(queryid.lo);
1336
1337
0
    if (config::enable_debug_points &&
1338
0
        DebugPoints::instance()->is_enable("FragmentMgr::send_filter_size.return_eof")) {
1339
0
        return Status::EndOfFile("inject FragmentMgr::send_filter_size.return_eof");
1340
0
    }
1341
1342
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1343
0
        return q_ctx->get_merge_controller_handler()->send_filter_size(q_ctx, request);
1344
0
    } else {
1345
0
        return Status::EndOfFile(
1346
0
                "Send filter size failed: Query context (query-id: {}) not found, maybe "
1347
0
                "finished",
1348
0
                queryid.to_string());
1349
0
    }
1350
0
}
1351
1352
0
Status FragmentMgr::sync_filter_size(const PSyncFilterSizeRequest* request) {
1353
0
    UniqueId queryid = request->query_id();
1354
0
    TUniqueId query_id;
1355
0
    query_id.__set_hi(queryid.hi);
1356
0
    query_id.__set_lo(queryid.lo);
1357
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1358
0
        try {
1359
0
            return q_ctx->runtime_filter_mgr()->sync_filter_size(request);
1360
0
        } catch (const Exception& e) {
1361
0
            return Status::InternalError(
1362
0
                    "Sync filter size failed: Query context (query-id: {}) error: {}",
1363
0
                    queryid.to_string(), e.what());
1364
0
        }
1365
0
    } else {
1366
0
        return Status::EndOfFile(
1367
0
                "Sync filter size failed: Query context (query-id: {}) already finished",
1368
0
                queryid.to_string());
1369
0
    }
1370
0
}
1371
1372
Status FragmentMgr::merge_filter(const PMergeFilterRequest* request,
1373
0
                                 butil::IOBufAsZeroCopyInputStream* attach_data) {
1374
0
    UniqueId queryid = request->query_id();
1375
1376
0
    TUniqueId query_id;
1377
0
    query_id.__set_hi(queryid.hi);
1378
0
    query_id.__set_lo(queryid.lo);
1379
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1380
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1381
0
        if (!q_ctx->get_merge_controller_handler()) {
1382
0
            return Status::InternalError("Merge filter failed: Merge controller handler is null");
1383
0
        }
1384
0
        return q_ctx->get_merge_controller_handler()->merge(q_ctx, request, attach_data);
1385
0
    } else {
1386
0
        return Status::EndOfFile(
1387
0
                "Merge filter size failed: Query context (query-id: {}) already finished",
1388
0
                queryid.to_string());
1389
0
    }
1390
0
}
1391
1392
void FragmentMgr::get_runtime_query_info(
1393
0
        std::vector<std::weak_ptr<ResourceContext>>* _resource_ctx_list) {
1394
0
    std::vector<std::shared_ptr<QueryContext>> contexts;
1395
0
    _query_ctx_map.apply(
1396
0
            [&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map) -> Status {
1397
0
                for (auto iter = map.begin(); iter != map.end();) {
1398
0
                    if (auto q_ctx = iter->second.lock()) {
1399
0
                        _resource_ctx_list->push_back(q_ctx->resource_ctx());
1400
0
                        contexts.push_back(q_ctx);
1401
0
                        iter++;
1402
0
                    } else {
1403
0
                        iter = map.erase(iter);
1404
0
                    }
1405
0
                }
1406
0
                return Status::OK();
1407
0
            });
1408
0
}
1409
1410
Status FragmentMgr::get_realtime_exec_status(const TUniqueId& query_id,
1411
0
                                             TReportExecStatusParams* exec_status) {
1412
0
    if (exec_status == nullptr) {
1413
0
        return Status::InvalidArgument("exes_status is nullptr");
1414
0
    }
1415
1416
0
    std::shared_ptr<QueryContext> query_context = get_query_ctx(query_id);
1417
0
    if (query_context == nullptr) {
1418
0
        return Status::NotFound("Query {} not found or released", print_id(query_id));
1419
0
    }
1420
1421
0
    *exec_status = query_context->get_realtime_exec_status();
1422
1423
0
    return Status::OK();
1424
0
}
1425
1426
0
Status FragmentMgr::get_query_statistics(const TUniqueId& query_id, TQueryStatistics* query_stats) {
1427
0
    if (query_stats == nullptr) {
1428
0
        return Status::InvalidArgument("query_stats is nullptr");
1429
0
    }
1430
1431
0
    return ExecEnv::GetInstance()->runtime_query_statistics_mgr()->get_query_statistics(
1432
0
            print_id(query_id), query_stats);
1433
0
}
1434
1435
#include "common/compile_check_end.h"
1436
1437
} // namespace doris