Coverage Report

Created: 2026-03-30 16:17

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