Coverage Report

Created: 2026-04-24 23:48

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/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
0
uint64_t get_fragment_executing_count() {
109
0
    return g_fragment_executing_count.get_value();
110
0
}
111
0
uint64_t get_fragment_last_active_time() {
112
0
    return g_fragment_last_active_time.get_value();
113
0
}
114
115
0
std::string to_load_error_http_path(const std::string& file_name) {
116
0
    if (file_name.empty()) {
117
0
        return "";
118
0
    }
119
0
    if (file_name.compare(0, 4, "http") == 0) {
120
0
        return file_name;
121
0
    }
122
0
    std::stringstream url;
123
0
    url << (config::enable_https ? "https" : "http") << "://"
124
0
        << get_host_port(BackendOptions::get_localhost(), config::webserver_port)
125
0
        << "/api/_load_error_log?"
126
0
        << "file=" << file_name;
127
0
    return url.str();
128
0
}
129
130
static Status _do_fetch_running_queries_rpc(const FrontendInfo& fe_info,
131
0
                                            std::unordered_set<TUniqueId>& query_set) {
132
0
    TFetchRunningQueriesResult rpc_result;
133
0
    TFetchRunningQueriesRequest rpc_request;
134
135
0
    Status client_status;
136
0
    const int32_t timeout_ms = 3 * 1000;
137
0
    FrontendServiceConnection rpc_client(ExecEnv::GetInstance()->frontend_client_cache(),
138
0
                                         fe_info.info.coordinator_address, timeout_ms,
139
0
                                         &client_status);
140
    // Abort this fe.
141
0
    if (!client_status.ok()) {
142
0
        LOG_WARNING("Failed to get client for {}, reason is {}",
143
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
144
0
                    client_status.to_string());
145
0
        return Status::InternalError("Failed to get client for {}, reason is {}",
146
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
147
0
                                     client_status.to_string());
148
0
    }
149
150
    // do rpc
151
0
    try {
152
0
        try {
153
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
154
0
        } catch (const apache::thrift::transport::TTransportException& e) {
155
0
            LOG_WARNING("Transport exception reason: {}, reopening", e.what());
156
0
            client_status = rpc_client.reopen(config::thrift_rpc_timeout_ms);
157
0
            if (!client_status.ok()) {
158
0
                LOG_WARNING("Reopen failed, reason: {}", client_status.to_string_no_stack());
159
0
                return Status::InternalError("Reopen failed, reason: {}",
160
0
                                             client_status.to_string_no_stack());
161
0
            }
162
163
0
            rpc_client->fetchRunningQueries(rpc_result, rpc_request);
164
0
        }
165
0
    } catch (apache::thrift::TException& e) {
166
        // During upgrading cluster or meet any other network error.
167
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
168
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address), e.what());
169
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
170
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
171
0
                                     e.what());
172
0
    }
173
174
    // Avoid logic error in frontend.
175
0
    if (!rpc_result.__isset.status || rpc_result.status.status_code != TStatusCode::OK) {
176
0
        LOG_WARNING("Failed to fetch running queries from {}, reason: {}",
177
0
                    PrintThriftNetworkAddress(fe_info.info.coordinator_address),
178
0
                    doris::to_string(rpc_result.status.status_code));
179
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
180
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
181
0
                                     doris::to_string(rpc_result.status.status_code));
182
0
    }
183
184
0
    if (!rpc_result.__isset.running_queries) {
185
0
        return Status::InternalError("Failed to fetch running queries from {}, reason: {}",
186
0
                                     PrintThriftNetworkAddress(fe_info.info.coordinator_address),
187
0
                                     "running_queries is not set");
188
0
    }
189
190
0
    query_set = std::unordered_set<TUniqueId>(rpc_result.running_queries.begin(),
191
0
                                              rpc_result.running_queries.end());
192
0
    return Status::OK();
193
0
};
194
195
0
static std::map<int64_t, std::unordered_set<TUniqueId>> _get_all_running_queries_from_fe() {
196
0
    const std::map<TNetworkAddress, FrontendInfo>& running_fes =
197
0
            ExecEnv::GetInstance()->get_running_frontends();
198
199
0
    std::map<int64_t, std::unordered_set<TUniqueId>> result;
200
0
    std::vector<FrontendInfo> qualified_fes;
201
202
0
    for (const auto& fe : running_fes) {
203
        // Only consider normal frontend.
204
0
        if (fe.first.port != 0 && fe.second.info.process_uuid != 0) {
205
0
            qualified_fes.push_back(fe.second);
206
0
        } else {
207
0
            return {};
208
0
        }
209
0
    }
210
211
0
    for (const auto& fe_addr : qualified_fes) {
212
0
        const int64_t process_uuid = fe_addr.info.process_uuid;
213
0
        std::unordered_set<TUniqueId> query_set;
214
0
        Status st = _do_fetch_running_queries_rpc(fe_addr, query_set);
215
0
        if (!st.ok()) {
216
            // Empty result, cancel worker will not do anything
217
0
            return {};
218
0
        }
219
220
        // frontend_info and process_uuid has been checked in rpc threads.
221
0
        result[process_uuid] = query_set;
222
0
    }
223
224
0
    return result;
225
0
}
226
227
5
inline uint32_t get_map_id(const TUniqueId& query_id, size_t capacity) {
228
5
    uint32_t value = HashUtil::hash(&query_id.lo, 8, 0);
229
5
    value = HashUtil::hash(&query_id.hi, 8, value);
230
5
    return value % capacity;
231
5
}
232
233
0
inline uint32_t get_map_id(std::pair<TUniqueId, int> key, size_t capacity) {
234
0
    uint32_t value = HashUtil::hash(&key.first.lo, 8, 0);
235
0
    value = HashUtil::hash(&key.first.hi, 8, value);
236
0
    return value % capacity;
237
0
}
238
239
template <typename Key, typename Value, typename ValueType>
240
27
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
241
27
    _internal_map.resize(config::num_query_ctx_map_partitions);
242
3.48k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
243
3.45k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
244
3.45k
                            phmap::flat_hash_map<Key, Value>()};
245
3.45k
    }
246
27
}
_ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_23PipelineFragmentContextEES5_EC2Ev
Line
Count
Source
240
9
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
241
9
    _internal_map.resize(config::num_query_ctx_map_partitions);
242
1.16k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
243
1.15k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
244
1.15k
                            phmap::flat_hash_map<Key, Value>()};
245
1.15k
    }
246
9
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_EC2Ev
Line
Count
Source
240
9
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
241
9
    _internal_map.resize(config::num_query_ctx_map_partitions);
242
1.16k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
243
1.15k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
244
1.15k
                            phmap::flat_hash_map<Key, Value>()};
245
1.15k
    }
246
9
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_EC2Ev
Line
Count
Source
240
9
ConcurrentContextMap<Key, Value, ValueType>::ConcurrentContextMap() {
241
9
    _internal_map.resize(config::num_query_ctx_map_partitions);
242
1.16k
    for (size_t i = 0; i < config::num_query_ctx_map_partitions; i++) {
243
1.15k
        _internal_map[i] = {std::make_unique<std::shared_mutex>(),
244
1.15k
                            phmap::flat_hash_map<Key, Value>()};
245
1.15k
    }
246
9
}
247
248
template <typename Key, typename Value, typename ValueType>
249
3
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
250
3
    auto id = get_map_id(query_id, _internal_map.size());
251
3
    {
252
3
        std::shared_lock lock(*_internal_map[id].first);
253
3
        auto& map = _internal_map[id].second;
254
3
        auto search = map.find(query_id);
255
3
        if (search != map.end()) {
256
0
            return search->second;
257
0
        }
258
3
        return std::shared_ptr<ValueType>(nullptr);
259
3
    }
260
3
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E4findERKS1_
Line
Count
Source
249
3
Value ConcurrentContextMap<Key, Value, ValueType>::find(const Key& query_id) {
250
3
    auto id = get_map_id(query_id, _internal_map.size());
251
3
    {
252
3
        std::shared_lock lock(*_internal_map[id].first);
253
3
        auto& map = _internal_map[id].second;
254
3
        auto search = map.find(query_id);
255
3
        if (search != map.end()) {
256
0
            return search->second;
257
0
        }
258
3
        return std::shared_ptr<ValueType>(nullptr);
259
3
    }
260
3
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_23PipelineFragmentContextEES5_E4findERKS3_
261
262
template <typename Key, typename Value, typename ValueType>
263
Status ConcurrentContextMap<Key, Value, ValueType>::apply_if_not_exists(
264
2
        const Key& query_id, std::shared_ptr<ValueType>& query_ctx, ApplyFunction&& function) {
265
2
    auto id = get_map_id(query_id, _internal_map.size());
266
2
    {
267
2
        std::unique_lock lock(*_internal_map[id].first);
268
2
        auto& map = _internal_map[id].second;
269
2
        auto search = map.find(query_id);
270
2
        if (search != map.end()) {
271
0
            query_ctx = search->second.lock();
272
0
        }
273
2
        if (!query_ctx) {
274
2
            return function(map);
275
2
        }
276
0
        return Status::OK();
277
2
    }
278
2
}
279
280
template <typename Key, typename Value, typename ValueType>
281
0
bool ConcurrentContextMap<Key, Value, ValueType>::erase(const Key& query_id) {
282
0
    auto id = get_map_id(query_id, _internal_map.size());
283
0
    std::unique_lock lock(*_internal_map[id].first);
284
0
    auto& map = _internal_map[id].second;
285
0
    return map.erase(query_id) != 0;
286
0
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_23PipelineFragmentContextEES5_E5eraseERKS3_
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E5eraseERKS1_
287
288
template <typename Key, typename Value, typename ValueType>
289
void ConcurrentContextMap<Key, Value, ValueType>::insert(const Key& query_id,
290
0
                                                         std::shared_ptr<ValueType> query_ctx) {
291
0
    auto id = get_map_id(query_id, _internal_map.size());
292
0
    {
293
0
        std::unique_lock lock(*_internal_map[id].first);
294
0
        auto& map = _internal_map[id].second;
295
0
        map.insert({query_id, query_ctx});
296
0
    }
297
0
}
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E6insertERKS1_S4_
Unexecuted instantiation: _ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_23PipelineFragmentContextEES5_E6insertERKS3_S6_
298
299
template <typename Key, typename Value, typename ValueType>
300
27
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
3.45k
    for (auto& pair : _internal_map) {
302
3.45k
        std::unique_lock lock(*pair.first);
303
3.45k
        auto& map = pair.second;
304
3.45k
        map.clear();
305
3.45k
    }
306
27
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt8weak_ptrINS_12QueryContextEES3_E5clearEv
Line
Count
Source
300
9
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
1.15k
    for (auto& pair : _internal_map) {
302
1.15k
        std::unique_lock lock(*pair.first);
303
1.15k
        auto& map = pair.second;
304
1.15k
        map.clear();
305
1.15k
    }
306
9
}
_ZN5doris20ConcurrentContextMapINS_9TUniqueIdESt10shared_ptrINS_12QueryContextEES3_E5clearEv
Line
Count
Source
300
9
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
1.15k
    for (auto& pair : _internal_map) {
302
1.15k
        std::unique_lock lock(*pair.first);
303
1.15k
        auto& map = pair.second;
304
1.15k
        map.clear();
305
1.15k
    }
306
9
}
_ZN5doris20ConcurrentContextMapISt4pairINS_9TUniqueIdEiESt10shared_ptrINS_23PipelineFragmentContextEES5_E5clearEv
Line
Count
Source
300
9
void ConcurrentContextMap<Key, Value, ValueType>::clear() {
301
1.15k
    for (auto& pair : _internal_map) {
302
1.15k
        std::unique_lock lock(*pair.first);
303
1.15k
        auto& map = pair.second;
304
1.15k
        map.clear();
305
1.15k
    }
306
9
}
307
308
FragmentMgr::FragmentMgr(ExecEnv* exec_env)
309
9
        : _exec_env(exec_env), _stop_background_threads_latch(1) {
310
9
    _entity = DorisMetrics::instance()->metric_registry()->register_entity("FragmentMgr");
311
9
    INT_UGAUGE_METRIC_REGISTER(_entity, timeout_canceled_fragment_count);
312
313
9
    auto s = Thread::create(
314
9
            "FragmentMgr", "cancel_timeout_plan_fragment", [this]() { this->cancel_worker(); },
315
9
            &_cancel_thread);
316
9
    CHECK(s.ok()) << s.to_string();
317
318
9
    s = ThreadPoolBuilder("FragmentMgrAsyncWorkThreadPool")
319
9
                .set_min_threads(config::fragment_mgr_async_work_pool_thread_num_min)
320
9
                .set_max_threads(config::fragment_mgr_async_work_pool_thread_num_max)
321
9
                .set_max_queue_size(config::fragment_mgr_async_work_pool_queue_size)
322
9
                .build(&_thread_pool);
323
9
    CHECK(s.ok()) << s.to_string();
324
9
}
325
326
9
FragmentMgr::~FragmentMgr() = default;
327
328
9
void FragmentMgr::stop() {
329
9
    DEREGISTER_HOOK_METRIC(fragment_instance_count);
330
9
    _stop_background_threads_latch.count_down();
331
9
    if (_cancel_thread) {
332
9
        _cancel_thread->join();
333
9
    }
334
335
9
    _thread_pool->shutdown();
336
    // Only me can delete
337
9
    _query_ctx_map.clear();
338
    // in one BE's graceful shutdown, cancel_worker will get related running queries via _get_all_running_queries_from_fe and cancel them.
339
    // 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
340
    // destructred and remove it from _query_ctx_map_delay_delete which is destructring. it's UB.
341
9
    _query_ctx_map_delay_delete.clear();
342
9
    _pipeline_map.clear();
343
9
    {
344
9
        std::lock_guard<std::mutex> lk(_rerunnable_params_lock);
345
9
        _rerunnable_params_map.clear();
346
9
    }
347
9
}
348
349
0
static void empty_function(RuntimeState*, Status*) {}
350
351
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
352
                                       const QuerySource query_source,
353
0
                                       const TPipelineFragmentParamsList& parent) {
354
0
    if (params.txn_conf.need_txn) {
355
0
        std::shared_ptr<StreamLoadContext> stream_load_ctx =
356
0
                std::make_shared<StreamLoadContext>(_exec_env);
357
0
        stream_load_ctx->db = params.txn_conf.db;
358
0
        stream_load_ctx->db_id = params.txn_conf.db_id;
359
0
        stream_load_ctx->table = params.txn_conf.tbl;
360
0
        stream_load_ctx->txn_id = params.txn_conf.txn_id;
361
0
        stream_load_ctx->id = UniqueId(params.query_id);
362
0
        stream_load_ctx->put_result.__set_pipeline_params(params);
363
0
        stream_load_ctx->use_streaming = true;
364
0
        stream_load_ctx->load_type = TLoadType::MANUL_LOAD;
365
0
        stream_load_ctx->load_src_type = TLoadSourceType::RAW;
366
0
        stream_load_ctx->label = params.import_label;
367
0
        stream_load_ctx->format = TFileFormatType::FORMAT_CSV_PLAIN;
368
0
        stream_load_ctx->timeout_second = 3600;
369
0
        stream_load_ctx->auth.token = params.txn_conf.token;
370
0
        stream_load_ctx->need_commit_self = true;
371
0
        stream_load_ctx->need_rollback = true;
372
0
        auto pipe = std::make_shared<io::StreamLoadPipe>(
373
0
                io::kMaxPipeBufferedBytes /* max_buffered_bytes */, 64 * 1024 /* min_chunk_size */,
374
0
                -1 /* total_length */, true /* use_proto */);
375
0
        stream_load_ctx->body_sink = pipe;
376
0
        stream_load_ctx->pipe = pipe;
377
0
        stream_load_ctx->max_filter_ratio = params.txn_conf.max_filter_ratio;
378
379
0
        RETURN_IF_ERROR(
380
0
                _exec_env->new_load_stream_mgr()->put(stream_load_ctx->id, stream_load_ctx));
381
382
0
        RETURN_IF_ERROR(
383
0
                _exec_env->stream_load_executor()->execute_plan_fragment(stream_load_ctx, parent));
384
0
        return Status::OK();
385
0
    } else {
386
0
        return exec_plan_fragment(params, query_source, empty_function, parent);
387
0
    }
388
0
}
389
390
// Stage 2. prepare finished. then get FE instruction to execute
391
0
Status FragmentMgr::start_query_execution(const PExecPlanFragmentStartRequest* request) {
392
0
    TUniqueId query_id;
393
0
    query_id.__set_hi(request->query_id().hi());
394
0
    query_id.__set_lo(request->query_id().lo());
395
0
    auto q_ctx = get_query_ctx(query_id);
396
0
    if (q_ctx) {
397
0
        q_ctx->set_ready_to_execute(Status::OK());
398
0
        LOG_INFO("Query {} start execution", print_id(query_id));
399
0
    } else {
400
0
        return Status::InternalError(
401
0
                "Failed to get query fragments context. Query {} may be "
402
0
                "timeout or be cancelled. host: {}",
403
0
                print_id(query_id), BackendOptions::get_localhost());
404
0
    }
405
0
    return Status::OK();
406
0
}
407
408
0
void FragmentMgr::remove_pipeline_context(std::pair<TUniqueId, int> key) {
409
0
    if (_pipeline_map.erase(key)) {
410
0
        int64_t now = duration_cast<std::chrono::milliseconds>(
411
0
                              std::chrono::system_clock::now().time_since_epoch())
412
0
                              .count();
413
0
        g_fragment_executing_count << -1;
414
0
        g_fragment_last_active_time.set_value(now);
415
0
    }
416
0
}
417
418
0
void FragmentMgr::remove_query_context(const TUniqueId& key) {
419
    // Clean up any saved rerunnable params for this query to avoid memory leaks.
420
    // This covers both cancel and normal destruction paths.
421
0
    {
422
0
        std::lock_guard<std::mutex> lk(_rerunnable_params_lock);
423
0
        for (auto it = _rerunnable_params_map.begin(); it != _rerunnable_params_map.end();) {
424
0
            if (it->first.first == key) {
425
0
                it = _rerunnable_params_map.erase(it);
426
0
            } else {
427
0
                ++it;
428
0
            }
429
0
        }
430
0
    }
431
0
    _query_ctx_map_delay_delete.erase(key);
432
#ifndef BE_TEST
433
    _query_ctx_map.erase(key);
434
#endif
435
0
}
436
437
3
std::shared_ptr<QueryContext> FragmentMgr::get_query_ctx(const TUniqueId& query_id) {
438
3
    auto val = _query_ctx_map.find(query_id);
439
3
    if (auto q_ctx = val.lock()) {
440
0
        return q_ctx;
441
0
    }
442
3
    return nullptr;
443
3
}
444
445
Status FragmentMgr::_get_or_create_query_ctx(const TPipelineFragmentParams& params,
446
                                             const TPipelineFragmentParamsList& parent,
447
                                             QuerySource query_source,
448
2
                                             std::shared_ptr<QueryContext>& query_ctx) {
449
2
    auto query_id = params.query_id;
450
2
    DBUG_EXECUTE_IF("FragmentMgr._get_query_ctx.failed", {
451
2
        return Status::InternalError("FragmentMgr._get_query_ctx.failed, query id {}",
452
2
                                     print_id(query_id));
453
2
    });
454
455
    // Find _query_ctx_map, in case some other request has already
456
    // create the query fragments context.
457
2
    query_ctx = get_query_ctx(query_id);
458
2
    if (params.is_simplified_param) {
459
        // Get common components from _query_ctx_map
460
0
        if (!query_ctx) {
461
0
            return Status::InternalError(
462
0
                    "Failed to get query fragments context. Query {} may be timeout or be "
463
0
                    "cancelled. host: {}",
464
0
                    print_id(query_id), BackendOptions::get_localhost());
465
0
        }
466
2
    } else {
467
2
        if (!query_ctx) {
468
2
            RETURN_IF_ERROR(_query_ctx_map.apply_if_not_exists(
469
2
                    query_id, query_ctx,
470
2
                    [&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map)
471
2
                            -> Status {
472
2
                        WorkloadGroupPtr workload_group_ptr = nullptr;
473
2
                        std::vector<uint64_t> wg_id_set;
474
2
                        if (params.__isset.workload_groups && !params.workload_groups.empty()) {
475
2
                            for (auto& wg : params.workload_groups) {
476
2
                                wg_id_set.push_back(wg.id);
477
2
                            }
478
2
                        }
479
2
                        workload_group_ptr = _exec_env->workload_group_mgr()->get_group(wg_id_set);
480
481
                        // First time a fragment of a query arrived. print logs.
482
2
                        LOG(INFO) << "query_id: " << print_id(query_id)
483
2
                                  << ", coord_addr: " << params.coord
484
2
                                  << ", total fragment num on current host: "
485
2
                                  << params.fragment_num_on_host
486
2
                                  << ", fe process uuid: " << params.query_options.fe_process_uuid
487
2
                                  << ", query type: " << params.query_options.query_type
488
2
                                  << ", report audit fe:" << params.current_connect_fe
489
2
                                  << ", use wg:" << workload_group_ptr->id() << ","
490
2
                                  << workload_group_ptr->name();
491
492
                        // This may be a first fragment request of the query.
493
                        // Create the query fragments context.
494
                        // Cross-cluster query: coordinator FE may not belong to local cluster.
495
                        // In that case, cancel_worker() should not cancel it based on local FE liveness.
496
2
                        QuerySource actual_query_source = query_source;
497
2
                        if (query_source == QuerySource::INTERNAL_FRONTEND &&
498
2
                            !_exec_env->get_running_frontends().contains(params.coord)) {
499
2
                            actual_query_source = QuerySource::EXTERNAL_FRONTEND;
500
2
                        }
501
2
                        query_ctx = QueryContext::create(
502
2
                                query_id, _exec_env, params.query_options, params.coord,
503
2
                                params.is_nereids, params.current_connect_fe, actual_query_source);
504
2
                        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(query_ctx->query_mem_tracker());
505
2
                        RETURN_IF_ERROR(DescriptorTbl::create(
506
2
                                &(query_ctx->obj_pool), params.desc_tbl, &(query_ctx->desc_tbl)));
507
                        // set file scan range params
508
2
                        if (params.__isset.file_scan_params) {
509
2
                            query_ctx->file_scan_range_params_map = params.file_scan_params;
510
2
                        }
511
512
2
                        query_ctx->query_globals = params.query_globals;
513
514
2
                        if (params.__isset.resource_info) {
515
2
                            query_ctx->user = params.resource_info.user;
516
2
                            query_ctx->group = params.resource_info.group;
517
2
                            query_ctx->set_rsc_info = true;
518
2
                        }
519
520
2
                        if (params.__isset.ai_resources) {
521
2
                            query_ctx->set_ai_resources(params.ai_resources);
522
2
                        }
523
524
2
                        RETURN_IF_ERROR(query_ctx->set_workload_group(workload_group_ptr));
525
526
2
                        if (parent.__isset.runtime_filter_info) {
527
2
                            auto info = parent.runtime_filter_info;
528
2
                            if (info.__isset.runtime_filter_params) {
529
2
                                auto handler =
530
2
                                        std::make_shared<RuntimeFilterMergeControllerEntity>();
531
2
                                RETURN_IF_ERROR(
532
2
                                        handler->init(query_ctx, info.runtime_filter_params));
533
2
                                query_ctx->set_merge_controller_handler(handler);
534
535
2
                                query_ctx->runtime_filter_mgr()->set_runtime_filter_params(
536
2
                                        info.runtime_filter_params);
537
2
                                if (!handler->empty()) {
538
2
                                    _query_ctx_map_delay_delete.insert(query_id, query_ctx);
539
2
                                }
540
2
                            }
541
2
                            if (info.__isset.topn_filter_descs) {
542
2
                                query_ctx->init_runtime_predicates(info.topn_filter_descs);
543
2
                            }
544
2
                        }
545
546
                        // There is some logic in query ctx's dctor, we could not check if exists and delete the
547
                        // temp query ctx now. For example, the query id maybe removed from workload group's queryset.
548
2
                        map.insert({query_id, query_ctx});
549
2
                        return Status::OK();
550
2
                    }));
551
2
        }
552
2
    }
553
2
    return Status::OK();
554
2
}
555
556
0
std::string FragmentMgr::dump_pipeline_tasks(int64_t duration) {
557
0
    fmt::memory_buffer debug_string_buffer;
558
0
    size_t i = 0;
559
0
    {
560
0
        fmt::format_to(debug_string_buffer,
561
0
                       "{} pipeline fragment contexts are still running! duration_limit={}\n",
562
0
                       _pipeline_map.num_items(), duration);
563
0
        timespec now;
564
0
        clock_gettime(CLOCK_MONOTONIC, &now);
565
566
0
        _pipeline_map.apply([&](phmap::flat_hash_map<std::pair<TUniqueId, int>,
567
0
                                                     std::shared_ptr<PipelineFragmentContext>>& map)
568
0
                                    -> Status {
569
0
            std::set<TUniqueId> query_id_set;
570
0
            for (auto& it : map) {
571
0
                auto elapsed = it.second->elapsed_time() / 1000000000;
572
0
                if (elapsed < duration) {
573
                    // Only display tasks which has been running for more than {duration} seconds.
574
0
                    continue;
575
0
                }
576
0
                if (!query_id_set.contains(it.first.first)) {
577
0
                    query_id_set.insert(it.first.first);
578
0
                    fmt::format_to(
579
0
                            debug_string_buffer, "QueryId: {}, global_runtime_filter_mgr: {}\n",
580
0
                            print_id(it.first.first),
581
0
                            it.second->get_query_ctx()->runtime_filter_mgr()->debug_string());
582
583
0
                    if (it.second->get_query_ctx()->get_merge_controller_handler()) {
584
0
                        fmt::format_to(debug_string_buffer, "{}\n",
585
0
                                       it.second->get_query_ctx()
586
0
                                               ->get_merge_controller_handler()
587
0
                                               ->debug_string());
588
0
                    }
589
0
                }
590
591
0
                auto timeout_second = it.second->timeout_second();
592
0
                fmt::format_to(
593
0
                        debug_string_buffer,
594
0
                        "No.{} (elapse_second={}s, query_timeout_second={}s, is_timeout={}): {}\n",
595
0
                        i, elapsed, timeout_second, it.second->is_timeout(now),
596
0
                        it.second->debug_string());
597
0
                i++;
598
0
            }
599
0
            return Status::OK();
600
0
        });
601
0
    }
602
0
    return fmt::to_string(debug_string_buffer);
603
0
}
604
605
0
std::string FragmentMgr::dump_pipeline_tasks(TUniqueId& query_id) {
606
0
    if (auto q_ctx = get_query_ctx(query_id)) {
607
0
        return q_ctx->print_all_pipeline_context();
608
0
    } else {
609
0
        return fmt::format(
610
0
                "Dump pipeline tasks failed: Query context (query id = {}) not found. \n",
611
0
                print_id(query_id));
612
0
    }
613
0
}
614
615
Status FragmentMgr::exec_plan_fragment(const TPipelineFragmentParams& params,
616
                                       QuerySource query_source, const FinishCallback& cb,
617
0
                                       const TPipelineFragmentParamsList& parent) {
618
0
    VLOG_ROW << "Query: " << print_id(params.query_id) << " exec_plan_fragment params is "
619
0
             << apache::thrift::ThriftDebugString(params).c_str();
620
    // sometimes TPipelineFragmentParams debug string is too long and glog
621
    // will truncate the log line, so print query options seperately for debuggin purpose
622
0
    VLOG_ROW << "Query: " << print_id(params.query_id) << "query options is "
623
0
             << apache::thrift::ThriftDebugString(params.query_options).c_str();
624
625
0
    std::shared_ptr<QueryContext> query_ctx;
626
0
    RETURN_IF_ERROR(_get_or_create_query_ctx(params, parent, query_source, query_ctx));
627
0
    SCOPED_ATTACH_TASK(query_ctx.get()->resource_ctx());
628
    // Set single_backend_query before prepare() so that pipeline local states
629
    // (e.g. StreamingAggLocalState) can read the correct value in their constructors.
630
0
    query_ctx->set_single_backend_query(params.__isset.query_options &&
631
0
                                        params.query_options.__isset.single_backend_query &&
632
0
                                        params.query_options.single_backend_query);
633
0
    int64_t duration_ns = 0;
634
0
    std::shared_ptr<PipelineFragmentContext> context = std::make_shared<PipelineFragmentContext>(
635
0
            query_ctx->query_id(), params, query_ctx, _exec_env, cb);
636
0
    {
637
0
        SCOPED_RAW_TIMER(&duration_ns);
638
0
        Status prepare_st = Status::OK();
639
0
        ASSIGN_STATUS_IF_CATCH_EXCEPTION(prepare_st = context->prepare(_thread_pool.get()),
640
0
                                         prepare_st);
641
0
        DBUG_EXECUTE_IF("FragmentMgr.exec_plan_fragment.prepare_failed", {
642
0
            prepare_st = Status::Aborted("FragmentMgr.exec_plan_fragment.prepare_failed");
643
0
        });
644
0
        if (!prepare_st.ok()) {
645
0
            query_ctx->cancel(prepare_st, params.fragment_id);
646
0
            return prepare_st;
647
0
        }
648
0
    }
649
0
    g_fragmentmgr_prepare_latency << (duration_ns / 1000);
650
651
0
    DBUG_EXECUTE_IF("FragmentMgr.exec_plan_fragment.failed",
652
0
                    { return Status::Aborted("FragmentMgr.exec_plan_fragment.failed"); });
653
0
    {
654
0
        int64_t now = duration_cast<std::chrono::milliseconds>(
655
0
                              std::chrono::system_clock::now().time_since_epoch())
656
0
                              .count();
657
0
        g_fragment_executing_count << 1;
658
0
        g_fragment_last_active_time.set_value(now);
659
660
        // (query_id, fragment_id) is executed only on one BE, locks _pipeline_map.
661
0
        auto res = _pipeline_map.find({params.query_id, params.fragment_id});
662
0
        if (res != nullptr) {
663
0
            return Status::InternalError(
664
0
                    "exec_plan_fragment query_id({}) input duplicated fragment_id({})",
665
0
                    print_id(params.query_id), params.fragment_id);
666
0
        }
667
0
        _pipeline_map.insert({params.query_id, params.fragment_id}, context);
668
0
    }
669
670
    // Save params for recursive CTE child fragments so we can recreate the PFC later.
671
    // For recursive CTE, the child fragment needs to be destroyed and rebuilt between rounds,
672
    // so we save the original params here and use them in rerun_fragment(rebuild).
673
0
    if (params.__isset.need_notify_close && params.need_notify_close) {
674
0
        std::lock_guard<std::mutex> lk(_rerunnable_params_lock);
675
0
        _rerunnable_params_map[{params.query_id, params.fragment_id}] = {
676
0
                .deregister_runtime_filter_ids = {},
677
0
                .params = params,
678
0
                .parent = parent,
679
0
                .finish_callback = cb,
680
0
                .query_ctx = query_ctx};
681
0
    }
682
683
0
    if (!params.__isset.need_wait_execution_trigger || !params.need_wait_execution_trigger) {
684
0
        query_ctx->set_ready_to_execute_only();
685
0
    }
686
687
0
    query_ctx->set_pipeline_context(params.fragment_id, context);
688
689
0
    RETURN_IF_ERROR(context->submit());
690
0
    return Status::OK();
691
0
}
692
693
1
void FragmentMgr::cancel_query(const TUniqueId query_id, const Status reason) {
694
1
    std::shared_ptr<QueryContext> query_ctx = nullptr;
695
1
    {
696
1
        if (auto q_ctx = get_query_ctx(query_id)) {
697
0
            query_ctx = q_ctx;
698
1
        } else {
699
1
            LOG(WARNING) << "Query " << print_id(query_id)
700
1
                         << " does not exists, failed to cancel it";
701
1
            return;
702
1
        }
703
1
    }
704
0
    SCOPED_ATTACH_TASK(query_ctx->resource_ctx());
705
0
    query_ctx->cancel(reason);
706
0
    remove_query_context(query_id);
707
0
    LOG(INFO) << "Query " << print_id(query_id)
708
0
              << " is cancelled and removed. Reason: " << reason.to_string();
709
0
}
710
711
9
void FragmentMgr::cancel_worker() {
712
9
    LOG(INFO) << "FragmentMgr cancel worker start working.";
713
714
9
    timespec check_invalid_query_last_timestamp;
715
9
    clock_gettime(CLOCK_MONOTONIC, &check_invalid_query_last_timestamp);
716
717
14
    do {
718
14
        std::vector<TUniqueId> queries_lost_coordinator;
719
14
        std::vector<TUniqueId> queries_timeout;
720
14
        std::vector<TUniqueId> queries_pipeline_task_leak;
721
        // Fe process uuid -> set<QueryId>
722
14
        std::map<int64_t, std::unordered_set<TUniqueId>> running_queries_on_all_fes;
723
14
        const std::map<TNetworkAddress, FrontendInfo>& running_fes =
724
14
                ExecEnv::GetInstance()->get_running_frontends();
725
726
14
        timespec now;
727
14
        clock_gettime(CLOCK_MONOTONIC, &now);
728
729
14
        if (config::enable_pipeline_task_leakage_detect &&
730
14
            now.tv_sec - check_invalid_query_last_timestamp.tv_sec >
731
0
                    config::pipeline_task_leakage_detect_period_secs) {
732
0
            check_invalid_query_last_timestamp = now;
733
0
            running_queries_on_all_fes = _get_all_running_queries_from_fe();
734
14
        } else {
735
14
            running_queries_on_all_fes.clear();
736
14
        }
737
738
14
        std::vector<std::shared_ptr<PipelineFragmentContext>> ctx;
739
14
        _pipeline_map.apply(
740
14
                [&](phmap::flat_hash_map<std::pair<TUniqueId, int>,
741
1.79k
                                         std::shared_ptr<PipelineFragmentContext>>& map) -> Status {
742
1.79k
                    ctx.reserve(ctx.size() + map.size());
743
1.79k
                    for (auto& pipeline_itr : map) {
744
0
                        ctx.push_back(pipeline_itr.second);
745
0
                    }
746
1.79k
                    return Status::OK();
747
1.79k
                });
748
14
        for (auto& c : ctx) {
749
0
            c->clear_finished_tasks();
750
0
        }
751
752
14
        std::unordered_map<std::shared_ptr<PBackendService_Stub>, BrpcItem> brpc_stub_with_queries;
753
14
        _collect_timeout_queries_and_brpc_items(queries_timeout, brpc_stub_with_queries, now);
754
755
        // We use a very conservative cancel strategy.
756
        // 0. If there are no running frontends, do not cancel any queries.
757
        // 1. If query's process uuid is zero, do not cancel
758
        // 2. If same process uuid, do not cancel
759
        // 3. If fe has zero process uuid, do not cancel
760
14
        if (running_fes.empty() && _query_ctx_map.num_items() != 0) {
761
0
            LOG_EVERY_N(WARNING, 10)
762
0
                    << "Could not find any running frontends, maybe we are upgrading or "
763
0
                       "starting? "
764
0
                    << "We will not cancel any outdated queries in this situation.";
765
14
        } else {
766
14
            _collect_invalid_queries(queries_lost_coordinator, queries_pipeline_task_leak,
767
14
                                     running_queries_on_all_fes, running_fes,
768
14
                                     check_invalid_query_last_timestamp);
769
14
        }
770
771
14
        if (config::enable_brpc_connection_check) {
772
0
            for (auto it : brpc_stub_with_queries) {
773
0
                if (!it.first) {
774
0
                    LOG(WARNING) << "brpc stub is nullptr, skip it.";
775
0
                    continue;
776
0
                }
777
0
                _check_brpc_available(it.first, it.second);
778
0
            }
779
0
        }
780
781
14
        if (!queries_lost_coordinator.empty()) {
782
0
            LOG(INFO) << "There are " << queries_lost_coordinator.size()
783
0
                      << " queries need to be cancelled, coordinator dead or restarted.";
784
0
        }
785
786
14
        for (const auto& qid : queries_timeout) {
787
0
            cancel_query(qid,
788
0
                         Status::Error<ErrorCode::TIMEOUT>(
789
0
                                 "FragmentMgr cancel worker going to cancel timeout instance "));
790
0
        }
791
792
14
        for (const auto& qid : queries_pipeline_task_leak) {
793
            // Cancel the query, and maybe try to report debug info to fe so that we can
794
            // collect debug info by sql or http api instead of search log.
795
0
            cancel_query(qid, Status::Error<ErrorCode::ILLEGAL_STATE>(
796
0
                                      "Potential pipeline task leakage"));
797
0
        }
798
799
14
        for (const auto& qid : queries_lost_coordinator) {
800
0
            cancel_query(qid, Status::Error<ErrorCode::CANCELLED>(
801
0
                                      "Source frontend is not running or restarted"));
802
0
        }
803
804
14
    } while (!_stop_background_threads_latch.wait_for(
805
14
            std::chrono::seconds(config::fragment_mgr_cancel_worker_interval_seconds)));
806
9
    LOG(INFO) << "FragmentMgr cancel worker is going to exit.";
807
9
}
808
809
void FragmentMgr::_collect_timeout_queries_and_brpc_items(
810
        std::vector<TUniqueId>& queries_timeout,
811
        std::unordered_map<std::shared_ptr<PBackendService_Stub>, BrpcItem>& brpc_stub_with_queries,
812
14
        timespec now) {
813
14
    std::vector<std::shared_ptr<QueryContext>> contexts;
814
14
    _query_ctx_map.apply(
815
1.79k
            [&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map) -> Status {
816
1.79k
                for (auto it = map.begin(); it != map.end();) {
817
0
                    if (auto q_ctx = it->second.lock()) {
818
0
                        contexts.push_back(q_ctx);
819
0
                        if (q_ctx->is_timeout(now)) {
820
0
                            LOG_WARNING("Query {} is timeout", print_id(it->first));
821
0
                            queries_timeout.push_back(it->first);
822
0
                        } else if (config::enable_brpc_connection_check) {
823
0
                            auto brpc_stubs = q_ctx->get_using_brpc_stubs();
824
0
                            for (auto& item : brpc_stubs) {
825
0
                                if (!brpc_stub_with_queries.contains(item.second)) {
826
0
                                    brpc_stub_with_queries.emplace(item.second,
827
0
                                                                   BrpcItem {item.first, {q_ctx}});
828
0
                                } else {
829
0
                                    brpc_stub_with_queries[item.second].queries.emplace_back(q_ctx);
830
0
                                }
831
0
                            }
832
0
                        }
833
0
                        ++it;
834
0
                    } else {
835
0
                        it = map.erase(it);
836
0
                    }
837
0
                }
838
1.79k
                return Status::OK();
839
1.79k
            });
840
14
}
841
842
void FragmentMgr::_collect_invalid_queries(
843
        std::vector<TUniqueId>& queries_lost_coordinator,
844
        std::vector<TUniqueId>& queries_pipeline_task_leak,
845
        const std::map<int64_t, std::unordered_set<TUniqueId>>& running_queries_on_all_fes,
846
        const std::map<TNetworkAddress, FrontendInfo>& running_fes,
847
15
        timespec check_invalid_query_last_timestamp) {
848
15
    std::vector<std::shared_ptr<QueryContext>> q_contexts;
849
15
    _query_ctx_map.apply([&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map)
850
1.92k
                                 -> Status {
851
1.92k
        for (const auto& it : map) {
852
1
            if (auto q_ctx = it.second.lock()) {
853
                // Cross-cluster query: coordinator FE is not in local `running_fes`,
854
                // we should not cancel it based on local coordinator liveness.
855
1
                if (q_ctx->get_query_source() == QuerySource::EXTERNAL_FRONTEND) {
856
1
                    continue;
857
1
                }
858
0
                q_contexts.push_back(q_ctx);
859
0
                const int64_t fe_process_uuid = q_ctx->get_fe_process_uuid();
860
861
0
                if (fe_process_uuid == 0) {
862
                    // zero means this query is from a older version fe or
863
                    // this fe is starting
864
0
                    continue;
865
0
                }
866
867
                // If the query is not running on the any frontends, cancel it.
868
0
                if (auto itr = running_queries_on_all_fes.find(fe_process_uuid);
869
0
                    itr != running_queries_on_all_fes.end()) {
870
                    // Query not found on this frontend, and the query arrives before the last check
871
0
                    if (itr->second.find(it.first) == itr->second.end() &&
872
                        // tv_nsec represents the number of nanoseconds that have elapsed since the time point stored in tv_sec.
873
                        // tv_sec is enough, we do not need to check tv_nsec.
874
0
                        q_ctx->get_query_arrival_timestamp().tv_sec <
875
0
                                check_invalid_query_last_timestamp.tv_sec &&
876
0
                        q_ctx->get_query_source() == QuerySource::INTERNAL_FRONTEND) {
877
0
                        queries_pipeline_task_leak.push_back(q_ctx->query_id());
878
0
                        LOG_INFO(
879
0
                                "Query {}, type {} is not found on any frontends, "
880
0
                                "maybe it "
881
0
                                "is leaked.",
882
0
                                print_id(q_ctx->query_id()), toString(q_ctx->get_query_source()));
883
0
                        continue;
884
0
                    }
885
0
                }
886
887
0
                auto itr = running_fes.find(q_ctx->coord_addr);
888
0
                if (itr != running_fes.end()) {
889
0
                    if (fe_process_uuid == itr->second.info.process_uuid ||
890
0
                        itr->second.info.process_uuid == 0) {
891
0
                        continue;
892
0
                    } else {
893
0
                        LOG_WARNING(
894
0
                                "Coordinator of query {} restarted, going to cancel "
895
0
                                "it.",
896
0
                                print_id(q_ctx->query_id()));
897
0
                    }
898
0
                } else {
899
                    // In some rear cases, the rpc port of follower is not updated in time,
900
                    // then the port of this follower will be zero, but acutally it is still running,
901
                    // and be has already received the query from follower.
902
                    // So we need to check if host is in running_fes.
903
0
                    bool fe_host_is_standing = std::any_of(
904
0
                            running_fes.begin(), running_fes.end(), [&q_ctx](const auto& fe) {
905
0
                                return fe.first.hostname == q_ctx->coord_addr.hostname &&
906
0
                                       fe.first.port == 0;
907
0
                            });
908
0
                    if (fe_host_is_standing) {
909
0
                        LOG_WARNING(
910
0
                                "Coordinator {}:{} is not found, but its host is still "
911
0
                                "running with an unstable brpc port, not going to "
912
0
                                "cancel "
913
0
                                "it.",
914
0
                                q_ctx->coord_addr.hostname, q_ctx->coord_addr.port,
915
0
                                print_id(q_ctx->query_id()));
916
0
                        continue;
917
0
                    } else {
918
0
                        LOG_WARNING(
919
0
                                "Could not find target coordinator {}:{} of query {}, "
920
0
                                "going to "
921
0
                                "cancel it.",
922
0
                                q_ctx->coord_addr.hostname, q_ctx->coord_addr.port,
923
0
                                print_id(q_ctx->query_id()));
924
0
                    }
925
0
                }
926
0
            }
927
            // Coordinator of this query has already dead or query context has been released.
928
0
            queries_lost_coordinator.push_back(it.first);
929
0
        }
930
1.92k
        return Status::OK();
931
1.92k
    });
932
15
}
933
934
void FragmentMgr::_check_brpc_available(const std::shared_ptr<PBackendService_Stub>& brpc_stub,
935
0
                                        const BrpcItem& brpc_item) {
936
0
    const std::string message = "hello doris!";
937
0
    std::string error_message;
938
0
    int32_t failed_count = 0;
939
0
    const int64_t check_timeout_ms =
940
0
            std::max<int64_t>(100, config::brpc_connection_check_timeout_ms);
941
942
0
    while (true) {
943
0
        PHandShakeRequest request;
944
0
        request.set_hello(message);
945
0
        PHandShakeResponse response;
946
0
        brpc::Controller cntl;
947
0
        cntl.set_timeout_ms(check_timeout_ms);
948
0
        cntl.set_max_retry(10);
949
0
        brpc_stub->hand_shake(&cntl, &request, &response, nullptr);
950
951
0
        if (cntl.Failed()) {
952
0
            error_message = cntl.ErrorText();
953
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
954
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
955
0
        } else if (response.has_status() && response.status().status_code() == 0) {
956
0
            break;
957
0
        } else {
958
0
            error_message = response.DebugString();
959
0
            LOG(WARNING) << "brpc stub: " << brpc_item.network_address.hostname << ":"
960
0
                         << brpc_item.network_address.port << " check failed: " << error_message;
961
0
        }
962
0
        failed_count++;
963
0
        if (failed_count == 2) {
964
0
            for (const auto& query_wptr : brpc_item.queries) {
965
0
                auto query = query_wptr.lock();
966
0
                if (query && !query->is_cancelled()) {
967
0
                    query->cancel(Status::InternalError("brpc(dest: {}:{}) check failed: {}",
968
0
                                                        brpc_item.network_address.hostname,
969
0
                                                        brpc_item.network_address.port,
970
0
                                                        error_message));
971
0
                }
972
0
            }
973
974
0
            LOG(WARNING) << "remove brpc stub from cache: " << brpc_item.network_address.hostname
975
0
                         << ":" << brpc_item.network_address.port << ", error: " << error_message;
976
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
977
0
                    brpc_item.network_address.hostname, brpc_item.network_address.port);
978
0
            break;
979
0
        }
980
0
    }
981
0
}
982
983
0
void FragmentMgr::debug(std::stringstream& ss) {}
984
/*
985
 * 1. resolve opaqued_query_plan to thrift structure
986
 * 2. build TPipelineFragmentParams
987
 */
988
Status FragmentMgr::exec_external_plan_fragment(const TScanOpenParams& params,
989
                                                const TQueryPlanInfo& t_query_plan_info,
990
                                                const TUniqueId& query_id,
991
                                                const TUniqueId& fragment_instance_id,
992
0
                                                std::vector<TScanColumnDesc>* selected_columns) {
993
    // set up desc tbl
994
0
    DescriptorTbl* desc_tbl = nullptr;
995
0
    ObjectPool obj_pool;
996
0
    Status st = DescriptorTbl::create(&obj_pool, t_query_plan_info.desc_tbl, &desc_tbl);
997
0
    if (!st.ok()) {
998
0
        LOG(WARNING) << "open context error: extract DescriptorTbl failure";
999
0
        std::stringstream msg;
1000
0
        msg << " create DescriptorTbl error, should not be modified after returned Doris FE "
1001
0
               "processed";
1002
0
        return Status::InvalidArgument(msg.str());
1003
0
    }
1004
0
    TupleDescriptor* tuple_desc = desc_tbl->get_tuple_descriptor(0);
1005
0
    if (tuple_desc == nullptr) {
1006
0
        LOG(WARNING) << "open context error: extract TupleDescriptor failure";
1007
0
        std::stringstream msg;
1008
0
        msg << " get  TupleDescriptor error, should not be modified after returned Doris FE "
1009
0
               "processed";
1010
0
        return Status::InvalidArgument(msg.str());
1011
0
    }
1012
    // process selected columns form slots
1013
0
    for (const SlotDescriptor* slot : tuple_desc->slots()) {
1014
0
        TScanColumnDesc col;
1015
0
        col.__set_name(slot->col_name());
1016
0
        col.__set_type(to_thrift(slot->type()->get_primitive_type()));
1017
0
        selected_columns->emplace_back(std::move(col));
1018
0
    }
1019
1020
0
    VLOG_QUERY << "BackendService execute open()  TQueryPlanInfo: "
1021
0
               << apache::thrift::ThriftDebugString(t_query_plan_info);
1022
    // assign the param used to execute PlanFragment
1023
0
    TPipelineFragmentParams exec_fragment_params;
1024
0
    exec_fragment_params.protocol_version = (PaloInternalServiceVersion::type)0;
1025
0
    exec_fragment_params.__set_is_simplified_param(false);
1026
0
    exec_fragment_params.__set_fragment(t_query_plan_info.plan_fragment);
1027
0
    exec_fragment_params.__set_desc_tbl(t_query_plan_info.desc_tbl);
1028
1029
    // assign the param used for executing of PlanFragment-self
1030
0
    TPipelineInstanceParams fragment_exec_params;
1031
0
    exec_fragment_params.query_id = query_id;
1032
0
    fragment_exec_params.fragment_instance_id = fragment_instance_id;
1033
0
    exec_fragment_params.coord.hostname = "external";
1034
0
    std::map<::doris::TPlanNodeId, std::vector<TScanRangeParams>> per_node_scan_ranges;
1035
0
    std::vector<TScanRangeParams> scan_ranges;
1036
0
    std::vector<int64_t> tablet_ids = params.tablet_ids;
1037
0
    TNetworkAddress address;
1038
0
    address.hostname = BackendOptions::get_localhost();
1039
0
    address.port = doris::config::be_port;
1040
0
    std::map<int64_t, TTabletVersionInfo> tablet_info = t_query_plan_info.tablet_info;
1041
0
    for (auto tablet_id : params.tablet_ids) {
1042
0
        TPaloScanRange scan_range;
1043
0
        scan_range.db_name = params.database;
1044
0
        scan_range.table_name = params.table;
1045
0
        auto iter = tablet_info.find(tablet_id);
1046
0
        if (iter != tablet_info.end()) {
1047
0
            TTabletVersionInfo info = iter->second;
1048
0
            scan_range.tablet_id = tablet_id;
1049
0
            scan_range.version = std::to_string(info.version);
1050
            // Useless but it is required field in TPaloScanRange
1051
0
            scan_range.version_hash = "0";
1052
0
            scan_range.schema_hash = std::to_string(info.schema_hash);
1053
0
            scan_range.hosts.push_back(address);
1054
0
        } else {
1055
0
            std::stringstream msg;
1056
0
            msg << "tablet_id: " << tablet_id << " not found";
1057
0
            LOG(WARNING) << "tablet_id [ " << tablet_id << " ] not found";
1058
0
            return Status::NotFound(msg.str());
1059
0
        }
1060
0
        TScanRange doris_scan_range;
1061
0
        doris_scan_range.__set_palo_scan_range(scan_range);
1062
0
        TScanRangeParams scan_range_params;
1063
0
        scan_range_params.scan_range = doris_scan_range;
1064
0
        scan_ranges.push_back(scan_range_params);
1065
0
    }
1066
0
    per_node_scan_ranges.insert(std::make_pair((::doris::TPlanNodeId)0, scan_ranges));
1067
0
    fragment_exec_params.per_node_scan_ranges = per_node_scan_ranges;
1068
0
    exec_fragment_params.local_params.push_back(fragment_exec_params);
1069
0
    TQueryOptions query_options;
1070
0
    query_options.batch_size = params.batch_size;
1071
0
    query_options.execution_timeout = params.execution_timeout;
1072
0
    query_options.mem_limit = params.mem_limit;
1073
0
    query_options.query_type = TQueryType::EXTERNAL;
1074
0
    query_options.be_exec_version = BeExecVersionManager::get_newest_version();
1075
0
    exec_fragment_params.__set_query_options(query_options);
1076
0
    VLOG_ROW << "external exec_plan_fragment params is "
1077
0
             << apache::thrift::ThriftDebugString(exec_fragment_params).c_str();
1078
1079
0
    TPipelineFragmentParamsList mocked;
1080
0
    return exec_plan_fragment(exec_fragment_params, QuerySource::EXTERNAL_CONNECTOR, mocked);
1081
0
}
1082
1083
Status FragmentMgr::apply_filterv2(const PPublishFilterRequestV2* request,
1084
0
                                   butil::IOBufAsZeroCopyInputStream* attach_data) {
1085
0
    UniqueId queryid = request->query_id();
1086
0
    TUniqueId query_id;
1087
0
    query_id.__set_hi(queryid.hi);
1088
0
    query_id.__set_lo(queryid.lo);
1089
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1090
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1091
0
        RuntimeFilterMgr* runtime_filter_mgr = q_ctx->runtime_filter_mgr();
1092
0
        DCHECK(runtime_filter_mgr != nullptr);
1093
1094
        // 1. get the target filters
1095
0
        std::vector<std::shared_ptr<RuntimeFilterConsumer>> filters =
1096
0
                runtime_filter_mgr->get_consume_filters(request->filter_id());
1097
1098
        // 2. create the filter wrapper to replace or ignore/disable the target filters
1099
0
        if (!filters.empty()) {
1100
            // Discard stale-stage requests from old recursive CTE rounds.
1101
0
            if (filters[0]->stage() != request->stage()) {
1102
0
                return Status::OK();
1103
0
            }
1104
0
            RETURN_IF_ERROR(filters[0]->assign(*request, attach_data));
1105
0
            std::ranges::for_each(filters, [&](auto& filter) { filter->signal(filters[0].get()); });
1106
0
        }
1107
0
    }
1108
0
    return Status::OK();
1109
0
}
1110
1111
0
Status FragmentMgr::send_filter_size(const PSendFilterSizeRequest* request) {
1112
0
    UniqueId queryid = request->query_id();
1113
0
    TUniqueId query_id;
1114
0
    query_id.__set_hi(queryid.hi);
1115
0
    query_id.__set_lo(queryid.lo);
1116
1117
0
    if (config::enable_debug_points &&
1118
0
        DebugPoints::instance()->is_enable("FragmentMgr::send_filter_size.return_eof")) {
1119
0
        return Status::EndOfFile("inject FragmentMgr::send_filter_size.return_eof");
1120
0
    }
1121
1122
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1123
0
        return q_ctx->get_merge_controller_handler()->send_filter_size(q_ctx, request);
1124
0
    } else {
1125
0
        return Status::EndOfFile(
1126
0
                "Send filter size failed: Query context (query-id: {}) not found, maybe "
1127
0
                "finished",
1128
0
                queryid.to_string());
1129
0
    }
1130
0
}
1131
1132
0
Status FragmentMgr::sync_filter_size(const PSyncFilterSizeRequest* request) {
1133
0
    UniqueId queryid = request->query_id();
1134
0
    TUniqueId query_id;
1135
0
    query_id.__set_hi(queryid.hi);
1136
0
    query_id.__set_lo(queryid.lo);
1137
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1138
0
        try {
1139
0
            return q_ctx->runtime_filter_mgr()->sync_filter_size(request);
1140
0
        } catch (const Exception& e) {
1141
0
            return Status::InternalError(
1142
0
                    "Sync filter size failed: Query context (query-id: {}) error: {}",
1143
0
                    queryid.to_string(), e.what());
1144
0
        }
1145
0
    } else {
1146
0
        return Status::EndOfFile(
1147
0
                "Sync filter size failed: Query context (query-id: {}) already finished",
1148
0
                queryid.to_string());
1149
0
    }
1150
0
}
1151
1152
Status FragmentMgr::merge_filter(const PMergeFilterRequest* request,
1153
0
                                 butil::IOBufAsZeroCopyInputStream* attach_data) {
1154
0
    UniqueId queryid = request->query_id();
1155
1156
0
    TUniqueId query_id;
1157
0
    query_id.__set_hi(queryid.hi);
1158
0
    query_id.__set_lo(queryid.lo);
1159
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1160
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1161
0
        if (!q_ctx->get_merge_controller_handler()) {
1162
0
            return Status::InternalError("Merge filter failed: Merge controller handler is null");
1163
0
        }
1164
0
        return q_ctx->get_merge_controller_handler()->merge(q_ctx, request, attach_data);
1165
0
    } else {
1166
0
        return Status::EndOfFile(
1167
0
                "Merge filter size failed: Query context (query-id: {}) already finished",
1168
0
                queryid.to_string());
1169
0
    }
1170
0
}
1171
1172
void FragmentMgr::get_runtime_query_info(
1173
0
        std::vector<std::weak_ptr<ResourceContext>>* _resource_ctx_list) {
1174
0
    std::vector<std::shared_ptr<QueryContext>> contexts;
1175
0
    _query_ctx_map.apply(
1176
0
            [&](phmap::flat_hash_map<TUniqueId, std::weak_ptr<QueryContext>>& map) -> Status {
1177
0
                for (auto iter = map.begin(); iter != map.end();) {
1178
0
                    if (auto q_ctx = iter->second.lock()) {
1179
0
                        _resource_ctx_list->push_back(q_ctx->resource_ctx());
1180
0
                        contexts.push_back(q_ctx);
1181
0
                        iter++;
1182
0
                    } else {
1183
0
                        iter = map.erase(iter);
1184
0
                    }
1185
0
                }
1186
0
                return Status::OK();
1187
0
            });
1188
0
}
1189
1190
Status FragmentMgr::get_realtime_exec_status(const TUniqueId& query_id,
1191
0
                                             TReportExecStatusParams* exec_status) {
1192
0
    if (exec_status == nullptr) {
1193
0
        return Status::InvalidArgument("exes_status is nullptr");
1194
0
    }
1195
1196
0
    std::shared_ptr<QueryContext> query_context = get_query_ctx(query_id);
1197
0
    if (query_context == nullptr) {
1198
0
        return Status::NotFound("Query {} not found or released", print_id(query_id));
1199
0
    }
1200
1201
0
    *exec_status = query_context->get_realtime_exec_status();
1202
1203
0
    return Status::OK();
1204
0
}
1205
1206
0
Status FragmentMgr::get_query_statistics(const TUniqueId& query_id, TQueryStatistics* query_stats) {
1207
0
    if (query_stats == nullptr) {
1208
0
        return Status::InvalidArgument("query_stats is nullptr");
1209
0
    }
1210
1211
0
    return ExecEnv::GetInstance()->runtime_query_statistics_mgr()->get_query_statistics(
1212
0
            print_id(query_id), query_stats);
1213
0
}
1214
1215
Status FragmentMgr::transmit_rec_cte_block(
1216
        const TUniqueId& query_id, const TUniqueId& instance_id, int node_id,
1217
0
        const google::protobuf::RepeatedPtrField<doris::PBlock>& pblocks, bool eos) {
1218
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1219
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1220
0
        return q_ctx->send_block_to_cte_scan(instance_id, node_id, pblocks, eos);
1221
0
    } else {
1222
0
        return Status::EndOfFile(
1223
0
                "Transmit rec cte block failed: Query context (query-id: {}) not found, maybe "
1224
0
                "finished",
1225
0
                print_id(query_id));
1226
0
    }
1227
0
}
1228
1229
// Orchestrates the recursive CTE fragment lifecycle through 4 phases:
1230
//
1231
// wait_for_destroy: collect deregister RF IDs, store brpc closure, trigger old PFC close
1232
// rebuild: increment stage, deregister old RFs, create+prepare new PFC from saved params
1233
// submit: submit the new PFC's pipeline tasks for execution
1234
// final_close: async wait for close, send final report, clean up (last round only)
1235
//
1236
// The brpc ClosureGuard is stored in the PFC so the RPC response is deferred until
1237
// the PFC is fully destroyed. This gives the caller (RecCTESourceOperatorX) a
1238
// synchronization point to know when the old PFC has finished all its tasks.
1239
Status FragmentMgr::rerun_fragment(const std::shared_ptr<brpc::ClosureGuard>& guard,
1240
                                   const TUniqueId& query_id, int fragment_id,
1241
0
                                   PRerunFragmentParams_Opcode stage) {
1242
0
    if (stage == PRerunFragmentParams::WAIT_FOR_DESTROY ||
1243
0
        stage == PRerunFragmentParams::FINAL_CLOSE) {
1244
0
        auto fragment_ctx = _pipeline_map.find({query_id, fragment_id});
1245
0
        if (!fragment_ctx) {
1246
0
            return Status::NotFound("Fragment context (query-id: {}, fragment-id: {}) not found",
1247
0
                                    print_id(query_id), fragment_id);
1248
0
        }
1249
1250
0
        if (stage == PRerunFragmentParams::WAIT_FOR_DESTROY) {
1251
0
            std::unique_lock<std::mutex> lk(_rerunnable_params_lock);
1252
0
            auto it = _rerunnable_params_map.find({query_id, fragment_id});
1253
0
            if (it == _rerunnable_params_map.end()) {
1254
0
                lk.unlock();
1255
0
                auto st = fragment_ctx->listen_wait_close(guard, true);
1256
0
                if (!st.ok()) {
1257
0
                    LOG(WARNING) << fmt::format(
1258
0
                            "wait_for_destroy fragment context (query-id: {}, fragment-id: "
1259
0
                            "{}) failed: {}",
1260
0
                            print_id(query_id), fragment_id, st.to_string());
1261
0
                }
1262
0
                return Status::NotFound(
1263
0
                        "Rerunnable params (query-id: {}, fragment-id: {}) not found",
1264
0
                        print_id(query_id), fragment_id);
1265
0
            }
1266
1267
0
            it->second.deregister_runtime_filter_ids.merge(
1268
0
                    fragment_ctx->get_deregister_runtime_filter());
1269
0
        }
1270
1271
0
        auto* query_ctx = fragment_ctx->get_query_ctx();
1272
0
        SCOPED_ATTACH_TASK(query_ctx);
1273
0
        RETURN_IF_ERROR(
1274
0
                fragment_ctx->listen_wait_close(guard, stage == PRerunFragmentParams::FINAL_CLOSE));
1275
0
        fragment_ctx->notify_close();
1276
0
        return Status::OK();
1277
0
    } else if (stage == PRerunFragmentParams::REBUILD) {
1278
0
        auto q_ctx = get_query_ctx(query_id);
1279
0
        if (!q_ctx) {
1280
0
            return Status::NotFound(
1281
0
                    "rerun_fragment: Query context (query-id: {}) not found, maybe finished",
1282
0
                    print_id(query_id));
1283
0
        }
1284
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1285
0
        RerunableFragmentInfo info;
1286
0
        {
1287
0
            std::lock_guard<std::mutex> lk(_rerunnable_params_lock);
1288
0
            auto it = _rerunnable_params_map.find({query_id, fragment_id});
1289
0
            if (it == _rerunnable_params_map.end()) {
1290
0
                return Status::NotFound("rebuild (query-id: {}, fragment-id: {}) not found",
1291
0
                                        print_id(query_id), fragment_id);
1292
0
            }
1293
0
            it->second.stage++;
1294
            // Deregister old runtime filters so new ones can be registered in the new PFC.
1295
0
            for (int32_t filter_id : it->second.deregister_runtime_filter_ids) {
1296
0
                q_ctx->runtime_filter_mgr()->remove_filter(filter_id);
1297
0
            }
1298
0
            info = it->second;
1299
0
        }
1300
1301
0
        auto context = std::make_shared<PipelineFragmentContext>(
1302
0
                q_ctx->query_id(), info.params, q_ctx, _exec_env, info.finish_callback);
1303
        // Propagate the recursion stage so that runtime filters created by this PFC
1304
        // carry the correct stage number.
1305
0
        context->set_rec_cte_stage(info.stage);
1306
1307
0
        Status prepare_st = Status::OK();
1308
0
        ASSIGN_STATUS_IF_CATCH_EXCEPTION(prepare_st = context->prepare(_thread_pool.get()),
1309
0
                                         prepare_st);
1310
0
        if (!prepare_st.ok()) {
1311
0
            q_ctx->cancel(prepare_st, info.params.fragment_id);
1312
0
            return prepare_st;
1313
0
        }
1314
1315
        // Insert new PFC into _pipeline_map (old one was removed)
1316
0
        _pipeline_map.insert({info.params.query_id, info.params.fragment_id}, context);
1317
1318
        // Update QueryContext mapping (must support overwrite)
1319
0
        q_ctx->set_pipeline_context(info.params.fragment_id, context);
1320
0
        return Status::OK();
1321
1322
0
    } else if (stage == PRerunFragmentParams::SUBMIT) {
1323
0
        auto fragment_ctx = _pipeline_map.find({query_id, fragment_id});
1324
0
        if (!fragment_ctx) {
1325
0
            return Status::NotFound("Fragment context (query-id: {}, fragment-id: {}) not found",
1326
0
                                    print_id(query_id), fragment_id);
1327
0
        }
1328
0
        return fragment_ctx->submit();
1329
0
    } else {
1330
0
        return Status::InvalidArgument("Unknown rerun fragment opcode: {}", stage);
1331
0
    }
1332
0
}
1333
1334
Status FragmentMgr::reset_global_rf(const TUniqueId& query_id,
1335
0
                                    const google::protobuf::RepeatedField<int32_t>& filter_ids) {
1336
0
    if (auto q_ctx = get_query_ctx(query_id)) {
1337
0
        SCOPED_ATTACH_TASK(q_ctx.get());
1338
0
        return q_ctx->reset_global_rf(filter_ids);
1339
0
    } else {
1340
0
        return Status::NotFound(
1341
0
                "reset_fragment: Query context (query-id: {}) not found, maybe finished",
1342
0
                print_id(query_id));
1343
0
    }
1344
0
}
1345
1346
#include "common/compile_check_end.h"
1347
1348
} // namespace doris