Coverage Report

Created: 2026-03-13 03:47

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