Coverage Report

Created: 2026-04-18 15:51

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