Coverage Report

Created: 2026-03-23 10:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/pipeline/pipeline_fragment_context.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 "exec/pipeline/pipeline_fragment_context.h"
19
20
#include <gen_cpp/DataSinks_types.h>
21
#include <gen_cpp/PaloInternalService_types.h>
22
#include <gen_cpp/PlanNodes_types.h>
23
#include <pthread.h>
24
25
#include <algorithm>
26
#include <cstdlib>
27
// IWYU pragma: no_include <bits/chrono.h>
28
#include <fmt/format.h>
29
30
#include <chrono> // IWYU pragma: keep
31
#include <map>
32
#include <memory>
33
#include <ostream>
34
#include <utility>
35
36
#include "cloud/config.h"
37
#include "common/cast_set.h"
38
#include "common/config.h"
39
#include "common/exception.h"
40
#include "common/logging.h"
41
#include "common/status.h"
42
#include "exec/exchange/local_exchange_sink_operator.h"
43
#include "exec/exchange/local_exchange_source_operator.h"
44
#include "exec/exchange/local_exchanger.h"
45
#include "exec/exchange/vdata_stream_mgr.h"
46
#include "exec/operator/aggregation_sink_operator.h"
47
#include "exec/operator/aggregation_source_operator.h"
48
#include "exec/operator/analytic_sink_operator.h"
49
#include "exec/operator/analytic_source_operator.h"
50
#include "exec/operator/assert_num_rows_operator.h"
51
#include "exec/operator/blackhole_sink_operator.h"
52
#include "exec/operator/cache_sink_operator.h"
53
#include "exec/operator/cache_source_operator.h"
54
#include "exec/operator/datagen_operator.h"
55
#include "exec/operator/dict_sink_operator.h"
56
#include "exec/operator/distinct_streaming_aggregation_operator.h"
57
#include "exec/operator/empty_set_operator.h"
58
#include "exec/operator/es_scan_operator.h"
59
#include "exec/operator/exchange_sink_operator.h"
60
#include "exec/operator/exchange_source_operator.h"
61
#include "exec/operator/file_scan_operator.h"
62
#include "exec/operator/group_commit_block_sink_operator.h"
63
#include "exec/operator/group_commit_scan_operator.h"
64
#include "exec/operator/hashjoin_build_sink.h"
65
#include "exec/operator/hashjoin_probe_operator.h"
66
#include "exec/operator/hive_table_sink_operator.h"
67
#include "exec/operator/iceberg_table_sink_operator.h"
68
#include "exec/operator/jdbc_scan_operator.h"
69
#include "exec/operator/jdbc_table_sink_operator.h"
70
#include "exec/operator/local_merge_sort_source_operator.h"
71
#include "exec/operator/materialization_opertor.h"
72
#include "exec/operator/maxcompute_table_sink_operator.h"
73
#include "exec/operator/memory_scratch_sink_operator.h"
74
#include "exec/operator/meta_scan_operator.h"
75
#include "exec/operator/multi_cast_data_stream_sink.h"
76
#include "exec/operator/multi_cast_data_stream_source.h"
77
#include "exec/operator/nested_loop_join_build_operator.h"
78
#include "exec/operator/nested_loop_join_probe_operator.h"
79
#include "exec/operator/olap_scan_operator.h"
80
#include "exec/operator/olap_table_sink_operator.h"
81
#include "exec/operator/olap_table_sink_v2_operator.h"
82
#include "exec/operator/partition_sort_sink_operator.h"
83
#include "exec/operator/partition_sort_source_operator.h"
84
#include "exec/operator/partitioned_aggregation_sink_operator.h"
85
#include "exec/operator/partitioned_aggregation_source_operator.h"
86
#include "exec/operator/partitioned_hash_join_probe_operator.h"
87
#include "exec/operator/partitioned_hash_join_sink_operator.h"
88
#include "exec/operator/rec_cte_anchor_sink_operator.h"
89
#include "exec/operator/rec_cte_scan_operator.h"
90
#include "exec/operator/rec_cte_sink_operator.h"
91
#include "exec/operator/rec_cte_source_operator.h"
92
#include "exec/operator/repeat_operator.h"
93
#include "exec/operator/result_file_sink_operator.h"
94
#include "exec/operator/result_sink_operator.h"
95
#include "exec/operator/schema_scan_operator.h"
96
#include "exec/operator/select_operator.h"
97
#include "exec/operator/set_probe_sink_operator.h"
98
#include "exec/operator/set_sink_operator.h"
99
#include "exec/operator/set_source_operator.h"
100
#include "exec/operator/sort_sink_operator.h"
101
#include "exec/operator/sort_source_operator.h"
102
#include "exec/operator/spill_iceberg_table_sink_operator.h"
103
#include "exec/operator/spill_sort_sink_operator.h"
104
#include "exec/operator/spill_sort_source_operator.h"
105
#include "exec/operator/streaming_aggregation_operator.h"
106
#include "exec/operator/table_function_operator.h"
107
#include "exec/operator/tvf_table_sink_operator.h"
108
#include "exec/operator/union_sink_operator.h"
109
#include "exec/operator/union_source_operator.h"
110
#include "exec/pipeline/dependency.h"
111
#include "exec/pipeline/pipeline_task.h"
112
#include "exec/pipeline/task_scheduler.h"
113
#include "exec/runtime_filter/runtime_filter_mgr.h"
114
#include "exec/sort/topn_sorter.h"
115
#include "exec/spill/spill_file.h"
116
#include "io/fs/stream_load_pipe.h"
117
#include "load/stream_load/new_load_stream_mgr.h"
118
#include "runtime/exec_env.h"
119
#include "runtime/fragment_mgr.h"
120
#include "runtime/result_block_buffer.h"
121
#include "runtime/result_buffer_mgr.h"
122
#include "runtime/runtime_state.h"
123
#include "runtime/thread_context.h"
124
#include "service/backend_options.h"
125
#include "util/countdown_latch.h"
126
#include "util/debug_util.h"
127
#include "util/uid_util.h"
128
129
namespace doris {
130
#include "common/compile_check_begin.h"
131
PipelineFragmentContext::PipelineFragmentContext(
132
        TUniqueId query_id, const TPipelineFragmentParams& request,
133
        std::shared_ptr<QueryContext> query_ctx, ExecEnv* exec_env,
134
        const std::function<void(RuntimeState*, Status*)>& call_back,
135
        report_status_callback report_status_cb)
136
337k
        : _query_id(std::move(query_id)),
137
337k
          _fragment_id(request.fragment_id),
138
337k
          _exec_env(exec_env),
139
337k
          _query_ctx(std::move(query_ctx)),
140
337k
          _call_back(call_back),
141
337k
          _is_report_on_cancel(true),
142
337k
          _report_status_cb(std::move(report_status_cb)),
143
337k
          _params(request),
144
337k
          _parallel_instances(_params.__isset.parallel_instances ? _params.parallel_instances : 0),
145
337k
          _need_notify_close(request.__isset.need_notify_close ? request.need_notify_close
146
337k
                                                               : false) {
147
337k
    _fragment_watcher.start();
148
337k
}
149
150
338k
PipelineFragmentContext::~PipelineFragmentContext() {
151
338k
    LOG_INFO("PipelineFragmentContext::~PipelineFragmentContext")
152
338k
            .tag("query_id", print_id(_query_id))
153
338k
            .tag("fragment_id", _fragment_id);
154
338k
    _release_resource();
155
338k
    {
156
        // The memory released by the query end is recorded in the query mem tracker.
157
338k
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_query_ctx->query_mem_tracker());
158
338k
        _runtime_state.reset();
159
338k
        _query_ctx.reset();
160
338k
    }
161
338k
}
162
163
1.45k
bool PipelineFragmentContext::is_timeout(timespec now) const {
164
1.45k
    if (_timeout <= 0) {
165
0
        return false;
166
0
    }
167
1.45k
    return _fragment_watcher.elapsed_time_seconds(now) > _timeout;
168
1.45k
}
169
170
// Must not add lock in this method. Because it will call query ctx cancel. And
171
// QueryCtx cancel will call fragment ctx cancel. And Also Fragment ctx's running
172
// Method like exchange sink buffer will call query ctx cancel. If we add lock here
173
// There maybe dead lock.
174
7.06k
void PipelineFragmentContext::cancel(const Status reason) {
175
7.06k
    LOG_INFO("PipelineFragmentContext::cancel")
176
7.06k
            .tag("query_id", print_id(_query_id))
177
7.06k
            .tag("fragment_id", _fragment_id)
178
7.06k
            .tag("reason", reason.to_string());
179
7.06k
    {
180
7.06k
        std::lock_guard<std::mutex> l(_task_mutex);
181
7.06k
        if (_closed_tasks >= _total_tasks) {
182
            // All tasks in this PipelineXFragmentContext already closed.
183
199
            return;
184
199
        }
185
7.06k
    }
186
    // Timeout is a special error code, we need print current stack to debug timeout issue.
187
6.86k
    if (reason.is<ErrorCode::TIMEOUT>()) {
188
8
        auto dbg_str = fmt::format("PipelineFragmentContext is cancelled due to timeout:\n{}",
189
8
                                   debug_string());
190
8
        LOG_LONG_STRING(WARNING, dbg_str);
191
8
    }
192
193
    // `ILLEGAL_STATE` means queries this fragment belongs to was not found in FE (maybe finished)
194
6.86k
    if (reason.is<ErrorCode::ILLEGAL_STATE>()) {
195
0
        LOG_WARNING("PipelineFragmentContext is cancelled due to illegal state : {}",
196
0
                    debug_string());
197
0
    }
198
199
6.86k
    if (reason.is<ErrorCode::MEM_LIMIT_EXCEEDED>() || reason.is<ErrorCode::MEM_ALLOC_FAILED>()) {
200
0
        print_profile("cancel pipeline, reason: " + reason.to_string());
201
0
    }
202
203
6.86k
    if (auto error_url = get_load_error_url(); !error_url.empty()) {
204
22
        _query_ctx->set_load_error_url(error_url);
205
22
    }
206
207
6.86k
    if (auto first_error_msg = get_first_error_msg(); !first_error_msg.empty()) {
208
22
        _query_ctx->set_first_error_msg(first_error_msg);
209
22
    }
210
211
6.86k
    _query_ctx->cancel(reason, _fragment_id);
212
6.86k
    if (reason.is<ErrorCode::LIMIT_REACH>()) {
213
94
        _is_report_on_cancel = false;
214
6.76k
    } else {
215
21.6k
        for (auto& id : _fragment_instance_ids) {
216
21.6k
            LOG(WARNING) << "PipelineFragmentContext cancel instance: " << print_id(id);
217
21.6k
        }
218
6.76k
    }
219
    // Get pipe from new load stream manager and send cancel to it or the fragment may hang to wait read from pipe
220
    // For stream load the fragment's query_id == load id, it is set in FE.
221
6.86k
    auto stream_load_ctx = _exec_env->new_load_stream_mgr()->get(_query_id);
222
6.86k
    if (stream_load_ctx != nullptr) {
223
30
        stream_load_ctx->pipe->cancel(reason.to_string());
224
        // Set error URL here because after pipe is cancelled, stream load execution may return early.
225
        // We need to set the error URL at this point to ensure error information is properly
226
        // propagated to the client.
227
30
        stream_load_ctx->error_url = get_load_error_url();
228
30
        stream_load_ctx->first_error_msg = get_first_error_msg();
229
30
    }
230
231
21.9k
    for (auto& tasks : _tasks) {
232
44.2k
        for (auto& task : tasks) {
233
44.2k
            task.first->terminate();
234
44.2k
        }
235
21.9k
    }
236
6.86k
}
237
238
539k
PipelinePtr PipelineFragmentContext::add_pipeline(PipelinePtr parent, int idx) {
239
539k
    PipelineId id = _next_pipeline_id++;
240
539k
    auto pipeline = std::make_shared<Pipeline>(
241
539k
            id, parent ? std::min(parent->num_tasks(), _num_instances) : _num_instances,
242
539k
            parent ? parent->num_tasks() : _num_instances);
243
539k
    if (idx >= 0) {
244
75.4k
        _pipelines.insert(_pipelines.begin() + idx, pipeline);
245
464k
    } else {
246
464k
        _pipelines.emplace_back(pipeline);
247
464k
    }
248
539k
    if (parent) {
249
197k
        parent->set_children(pipeline);
250
197k
    }
251
539k
    return pipeline;
252
539k
}
253
254
340k
Status PipelineFragmentContext::_build_and_prepare_full_pipeline(ThreadPool* thread_pool) {
255
340k
    {
256
340k
        SCOPED_TIMER(_build_pipelines_timer);
257
        // 2. Build pipelines with operators in this fragment.
258
340k
        auto root_pipeline = add_pipeline();
259
340k
        RETURN_IF_ERROR(_build_pipelines(_runtime_state->obj_pool(), *_query_ctx->desc_tbl,
260
340k
                                         &_root_op, root_pipeline));
261
262
        // 3. Create sink operator
263
340k
        if (!_params.fragment.__isset.output_sink) {
264
0
            return Status::InternalError("No output sink in this fragment!");
265
0
        }
266
340k
        RETURN_IF_ERROR(_create_data_sink(_runtime_state->obj_pool(), _params.fragment.output_sink,
267
340k
                                          _params.fragment.output_exprs, _params,
268
340k
                                          root_pipeline->output_row_desc(), _runtime_state.get(),
269
340k
                                          *_desc_tbl, root_pipeline->id()));
270
340k
        RETURN_IF_ERROR(_sink->init(_params.fragment.output_sink));
271
340k
        RETURN_IF_ERROR(root_pipeline->set_sink(_sink));
272
273
463k
        for (PipelinePtr& pipeline : _pipelines) {
274
18.4E
            DCHECK(pipeline->sink() != nullptr) << pipeline->operators().size();
275
463k
            RETURN_IF_ERROR(pipeline->sink()->set_child(pipeline->operators().back()));
276
463k
        }
277
340k
    }
278
    // 4. Build local exchanger
279
340k
    if (_runtime_state->enable_local_shuffle()) {
280
338k
        SCOPED_TIMER(_plan_local_exchanger_timer);
281
338k
        RETURN_IF_ERROR(_plan_local_exchange(_params.num_buckets,
282
338k
                                             _params.bucket_seq_to_instance_idx,
283
338k
                                             _params.shuffle_idx_to_instance_idx));
284
338k
    }
285
286
    // 5. Initialize global states in pipelines.
287
540k
    for (PipelinePtr& pipeline : _pipelines) {
288
540k
        SCOPED_TIMER(_prepare_all_pipelines_timer);
289
540k
        pipeline->children().clear();
290
540k
        RETURN_IF_ERROR(pipeline->prepare(_runtime_state.get()));
291
540k
    }
292
293
339k
    {
294
339k
        SCOPED_TIMER(_build_tasks_timer);
295
        // 6. Build pipeline tasks and initialize local state.
296
339k
        RETURN_IF_ERROR(_build_pipeline_tasks(thread_pool));
297
339k
    }
298
299
338k
    return Status::OK();
300
339k
}
301
302
337k
Status PipelineFragmentContext::prepare(ThreadPool* thread_pool) {
303
337k
    if (_prepared) {
304
0
        return Status::InternalError("Already prepared");
305
0
    }
306
337k
    if (_params.__isset.query_options && _params.query_options.__isset.execution_timeout) {
307
337k
        _timeout = _params.query_options.execution_timeout;
308
337k
    }
309
310
337k
    _fragment_level_profile = std::make_unique<RuntimeProfile>("PipelineContext");
311
337k
    _prepare_timer = ADD_TIMER(_fragment_level_profile, "PrepareTime");
312
337k
    SCOPED_TIMER(_prepare_timer);
313
337k
    _build_pipelines_timer = ADD_TIMER(_fragment_level_profile, "BuildPipelinesTime");
314
337k
    _init_context_timer = ADD_TIMER(_fragment_level_profile, "InitContextTime");
315
337k
    _plan_local_exchanger_timer = ADD_TIMER(_fragment_level_profile, "PlanLocalLocalExchangerTime");
316
337k
    _build_tasks_timer = ADD_TIMER(_fragment_level_profile, "BuildTasksTime");
317
337k
    _prepare_all_pipelines_timer = ADD_TIMER(_fragment_level_profile, "PrepareAllPipelinesTime");
318
337k
    {
319
337k
        SCOPED_TIMER(_init_context_timer);
320
337k
        cast_set(_num_instances, _params.local_params.size());
321
337k
        _total_instances =
322
337k
                _params.__isset.total_instances ? _params.total_instances : _num_instances;
323
324
337k
        auto* fragment_context = this;
325
326
337k
        if (_params.query_options.__isset.is_report_success) {
327
337k
            fragment_context->set_is_report_success(_params.query_options.is_report_success);
328
337k
        }
329
330
        // 1. Set up the global runtime state.
331
337k
        _runtime_state = RuntimeState::create_unique(
332
337k
                _params.query_id, _params.fragment_id, _params.query_options,
333
337k
                _query_ctx->query_globals, _exec_env, _query_ctx.get());
334
337k
        _runtime_state->set_task_execution_context(shared_from_this());
335
337k
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_runtime_state->query_mem_tracker());
336
337k
        if (_params.__isset.backend_id) {
337
335k
            _runtime_state->set_backend_id(_params.backend_id);
338
335k
        }
339
337k
        if (_params.__isset.import_label) {
340
240
            _runtime_state->set_import_label(_params.import_label);
341
240
        }
342
337k
        if (_params.__isset.db_name) {
343
192
            _runtime_state->set_db_name(_params.db_name);
344
192
        }
345
337k
        if (_params.__isset.load_job_id) {
346
0
            _runtime_state->set_load_job_id(_params.load_job_id);
347
0
        }
348
349
337k
        if (_params.is_simplified_param) {
350
117k
            _desc_tbl = _query_ctx->desc_tbl;
351
219k
        } else {
352
219k
            DCHECK(_params.__isset.desc_tbl);
353
219k
            RETURN_IF_ERROR(DescriptorTbl::create(_runtime_state->obj_pool(), _params.desc_tbl,
354
219k
                                                  &_desc_tbl));
355
219k
        }
356
337k
        _runtime_state->set_desc_tbl(_desc_tbl);
357
337k
        _runtime_state->set_num_per_fragment_instances(_params.num_senders);
358
337k
        _runtime_state->set_load_stream_per_node(_params.load_stream_per_node);
359
337k
        _runtime_state->set_total_load_streams(_params.total_load_streams);
360
337k
        _runtime_state->set_num_local_sink(_params.num_local_sink);
361
362
        // init fragment_instance_ids
363
337k
        const auto target_size = _params.local_params.size();
364
337k
        _fragment_instance_ids.resize(target_size);
365
1.21M
        for (size_t i = 0; i < _params.local_params.size(); i++) {
366
874k
            auto fragment_instance_id = _params.local_params[i].fragment_instance_id;
367
874k
            _fragment_instance_ids[i] = fragment_instance_id;
368
874k
        }
369
337k
    }
370
371
337k
    RETURN_IF_ERROR(_build_and_prepare_full_pipeline(thread_pool));
372
373
336k
    _init_next_report_time();
374
375
336k
    _prepared = true;
376
336k
    return Status::OK();
377
337k
}
378
379
Status PipelineFragmentContext::_build_pipeline_tasks_for_instance(
380
        int instance_idx,
381
878k
        const std::vector<std::shared_ptr<RuntimeProfile>>& pipeline_id_to_profile) {
382
878k
    const auto& local_params = _params.local_params[instance_idx];
383
878k
    auto fragment_instance_id = local_params.fragment_instance_id;
384
878k
    auto runtime_filter_mgr = std::make_unique<RuntimeFilterMgr>(false);
385
878k
    std::map<PipelineId, PipelineTask*> pipeline_id_to_task;
386
878k
    auto get_shared_state = [&](PipelinePtr pipeline)
387
878k
            -> std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
388
1.63M
                                       std::vector<std::shared_ptr<Dependency>>>> {
389
1.63M
        std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
390
1.63M
                                std::vector<std::shared_ptr<Dependency>>>>
391
1.63M
                shared_state_map;
392
2.09M
        for (auto& op : pipeline->operators()) {
393
2.09M
            auto source_id = op->operator_id();
394
2.09M
            if (auto iter = _op_id_to_shared_state.find(source_id);
395
2.09M
                iter != _op_id_to_shared_state.end()) {
396
535k
                shared_state_map.insert({source_id, iter->second});
397
535k
            }
398
2.09M
        }
399
1.63M
        for (auto sink_to_source_id : pipeline->sink()->dests_id()) {
400
1.62M
            if (auto iter = _op_id_to_shared_state.find(sink_to_source_id);
401
1.62M
                iter != _op_id_to_shared_state.end()) {
402
256k
                shared_state_map.insert({sink_to_source_id, iter->second});
403
256k
            }
404
1.62M
        }
405
1.63M
        return shared_state_map;
406
1.63M
    };
407
408
2.78M
    for (size_t pip_idx = 0; pip_idx < _pipelines.size(); pip_idx++) {
409
1.90M
        auto& pipeline = _pipelines[pip_idx];
410
1.90M
        if (pipeline->num_tasks() > 1 || instance_idx == 0) {
411
1.62M
            auto task_runtime_state = RuntimeState::create_unique(
412
1.62M
                    local_params.fragment_instance_id, _params.query_id, _params.fragment_id,
413
1.62M
                    _params.query_options, _query_ctx->query_globals, _exec_env, _query_ctx.get());
414
1.62M
            {
415
                // Initialize runtime state for this task
416
1.62M
                task_runtime_state->set_query_mem_tracker(_query_ctx->query_mem_tracker());
417
418
1.62M
                task_runtime_state->set_task_execution_context(shared_from_this());
419
1.62M
                task_runtime_state->set_be_number(local_params.backend_num);
420
1.62M
                if (_need_notify_close) {
421
                    // rec cte require child rf to wait infinitely to make sure all rpc done
422
11.4k
                    task_runtime_state->set_force_make_rf_wait_infinite();
423
11.4k
                }
424
425
1.62M
                if (_params.__isset.backend_id) {
426
1.62M
                    task_runtime_state->set_backend_id(_params.backend_id);
427
1.62M
                }
428
1.62M
                if (_params.__isset.import_label) {
429
241
                    task_runtime_state->set_import_label(_params.import_label);
430
241
                }
431
1.62M
                if (_params.__isset.db_name) {
432
193
                    task_runtime_state->set_db_name(_params.db_name);
433
193
                }
434
1.62M
                if (_params.__isset.load_job_id) {
435
0
                    task_runtime_state->set_load_job_id(_params.load_job_id);
436
0
                }
437
1.62M
                if (_params.__isset.wal_id) {
438
114
                    task_runtime_state->set_wal_id(_params.wal_id);
439
114
                }
440
1.62M
                if (_params.__isset.content_length) {
441
31
                    task_runtime_state->set_content_length(_params.content_length);
442
31
                }
443
444
1.62M
                task_runtime_state->set_desc_tbl(_desc_tbl);
445
1.62M
                task_runtime_state->set_per_fragment_instance_idx(local_params.sender_id);
446
1.62M
                task_runtime_state->set_num_per_fragment_instances(_params.num_senders);
447
1.62M
                task_runtime_state->resize_op_id_to_local_state(max_operator_id());
448
1.62M
                task_runtime_state->set_max_operator_id(max_operator_id());
449
1.62M
                task_runtime_state->set_load_stream_per_node(_params.load_stream_per_node);
450
1.62M
                task_runtime_state->set_total_load_streams(_params.total_load_streams);
451
1.62M
                task_runtime_state->set_num_local_sink(_params.num_local_sink);
452
453
1.62M
                task_runtime_state->set_runtime_filter_mgr(runtime_filter_mgr.get());
454
1.62M
            }
455
1.62M
            auto cur_task_id = _total_tasks++;
456
1.62M
            task_runtime_state->set_task_id(cur_task_id);
457
1.62M
            task_runtime_state->set_task_num(pipeline->num_tasks());
458
1.62M
            auto task = std::make_shared<PipelineTask>(
459
1.62M
                    pipeline, cur_task_id, task_runtime_state.get(),
460
1.62M
                    std::dynamic_pointer_cast<PipelineFragmentContext>(shared_from_this()),
461
1.62M
                    pipeline_id_to_profile[pip_idx].get(), get_shared_state(pipeline),
462
1.62M
                    instance_idx);
463
1.62M
            pipeline->incr_created_tasks(instance_idx, task.get());
464
1.62M
            pipeline_id_to_task.insert({pipeline->id(), task.get()});
465
1.62M
            _tasks[instance_idx].emplace_back(
466
1.62M
                    std::pair<std::shared_ptr<PipelineTask>, std::unique_ptr<RuntimeState>> {
467
1.62M
                            std::move(task), std::move(task_runtime_state)});
468
1.62M
        }
469
1.90M
    }
470
471
    /**
472
         * Build DAG for pipeline tasks.
473
         * For example, we have
474
         *
475
         *   ExchangeSink (Pipeline1)     JoinBuildSink (Pipeline2)
476
         *            \                      /
477
         *          JoinProbeOperator1 (Pipeline1)    JoinBuildSink (Pipeline3)
478
         *                 \                          /
479
         *               JoinProbeOperator2 (Pipeline1)
480
         *
481
         * In this fragment, we have three pipelines and pipeline 1 depends on pipeline 2 and pipeline 3.
482
         * To build this DAG, `_dag` manage dependencies between pipelines by pipeline ID and
483
         * `pipeline_id_to_task` is used to find the task by a unique pipeline ID.
484
         *
485
         * Finally, we have two upstream dependencies in Pipeline1 corresponding to JoinProbeOperator1
486
         * and JoinProbeOperator2.
487
         */
488
1.90M
    for (auto& _pipeline : _pipelines) {
489
1.90M
        if (pipeline_id_to_task.contains(_pipeline->id())) {
490
1.62M
            auto* task = pipeline_id_to_task[_pipeline->id()];
491
1.62M
            DCHECK(task != nullptr);
492
493
            // If this task has upstream dependency, then inject it into this task.
494
1.62M
            if (_dag.contains(_pipeline->id())) {
495
1.02M
                auto& deps = _dag[_pipeline->id()];
496
1.55M
                for (auto& dep : deps) {
497
1.55M
                    if (pipeline_id_to_task.contains(dep)) {
498
994k
                        auto ss = pipeline_id_to_task[dep]->get_sink_shared_state();
499
994k
                        if (ss) {
500
486k
                            task->inject_shared_state(ss);
501
507k
                        } else {
502
507k
                            pipeline_id_to_task[dep]->inject_shared_state(
503
507k
                                    task->get_source_shared_state());
504
507k
                        }
505
994k
                    }
506
1.55M
                }
507
1.02M
            }
508
1.62M
        }
509
1.90M
    }
510
2.78M
    for (size_t pip_idx = 0; pip_idx < _pipelines.size(); pip_idx++) {
511
1.90M
        if (pipeline_id_to_task.contains(_pipelines[pip_idx]->id())) {
512
1.62M
            auto* task = pipeline_id_to_task[_pipelines[pip_idx]->id()];
513
1.62M
            DCHECK(pipeline_id_to_profile[pip_idx]);
514
1.62M
            std::vector<TScanRangeParams> scan_ranges;
515
1.62M
            auto node_id = _pipelines[pip_idx]->operators().front()->node_id();
516
1.62M
            if (local_params.per_node_scan_ranges.contains(node_id)) {
517
366k
                scan_ranges = local_params.per_node_scan_ranges.find(node_id)->second;
518
366k
            }
519
1.62M
            RETURN_IF_ERROR_OR_CATCH_EXCEPTION(task->prepare(scan_ranges, local_params.sender_id,
520
1.62M
                                                             _params.fragment.output_sink));
521
1.62M
        }
522
1.90M
    }
523
877k
    {
524
877k
        std::lock_guard<std::mutex> l(_state_map_lock);
525
877k
        _runtime_filter_mgr_map[instance_idx] = std::move(runtime_filter_mgr);
526
877k
    }
527
877k
    return Status::OK();
528
878k
}
529
530
339k
Status PipelineFragmentContext::_build_pipeline_tasks(ThreadPool* thread_pool) {
531
339k
    _total_tasks = 0;
532
339k
    _closed_tasks = 0;
533
339k
    const auto target_size = _params.local_params.size();
534
339k
    _tasks.resize(target_size);
535
339k
    _runtime_filter_mgr_map.resize(target_size);
536
878k
    for (size_t pip_idx = 0; pip_idx < _pipelines.size(); pip_idx++) {
537
538k
        _pip_id_to_pipeline[_pipelines[pip_idx]->id()] = _pipelines[pip_idx].get();
538
538k
    }
539
339k
    auto pipeline_id_to_profile = _runtime_state->build_pipeline_profile(_pipelines.size());
540
541
339k
    if (target_size > 1 &&
542
339k
        (_runtime_state->query_options().__isset.parallel_prepare_threshold &&
543
87.8k
         target_size > _runtime_state->query_options().parallel_prepare_threshold)) {
544
        // If instances parallelism is big enough ( > parallel_prepare_threshold), we will prepare all tasks by multi-threads
545
21.5k
        std::vector<Status> prepare_status(target_size);
546
21.5k
        int submitted_tasks = 0;
547
21.5k
        Status submit_status;
548
21.5k
        CountDownLatch latch((int)target_size);
549
299k
        for (int i = 0; i < target_size; i++) {
550
278k
            submit_status = thread_pool->submit_func([&, i]() {
551
277k
                SCOPED_ATTACH_TASK(_query_ctx.get());
552
277k
                prepare_status[i] = _build_pipeline_tasks_for_instance(i, pipeline_id_to_profile);
553
277k
                latch.count_down();
554
277k
            });
555
278k
            if (LIKELY(submit_status.ok())) {
556
278k
                submitted_tasks++;
557
18.4E
            } else {
558
18.4E
                break;
559
18.4E
            }
560
278k
        }
561
21.5k
        latch.arrive_and_wait(target_size - submitted_tasks);
562
21.5k
        if (UNLIKELY(!submit_status.ok())) {
563
0
            return submit_status;
564
0
        }
565
299k
        for (int i = 0; i < submitted_tasks; i++) {
566
278k
            if (!prepare_status[i].ok()) {
567
0
                return prepare_status[i];
568
0
            }
569
278k
        }
570
318k
    } else {
571
919k
        for (int i = 0; i < target_size; i++) {
572
601k
            RETURN_IF_ERROR(_build_pipeline_tasks_for_instance(i, pipeline_id_to_profile));
573
601k
        }
574
318k
    }
575
339k
    _pipeline_parent_map.clear();
576
339k
    _op_id_to_shared_state.clear();
577
578
339k
    return Status::OK();
579
339k
}
580
581
335k
void PipelineFragmentContext::_init_next_report_time() {
582
335k
    auto interval_s = config::pipeline_status_report_interval;
583
335k
    if (_is_report_success && interval_s > 0 && _timeout > interval_s) {
584
34.1k
        VLOG_FILE << "enable period report: fragment id=" << _fragment_id;
585
34.1k
        uint64_t report_fragment_offset = (uint64_t)(rand() % interval_s) * NANOS_PER_SEC;
586
        // We don't want to wait longer than it takes to run the entire fragment.
587
34.1k
        _previous_report_time =
588
34.1k
                MonotonicNanos() + report_fragment_offset - (uint64_t)(interval_s)*NANOS_PER_SEC;
589
34.1k
        _disable_period_report = false;
590
34.1k
    }
591
335k
}
592
593
4.25k
void PipelineFragmentContext::refresh_next_report_time() {
594
4.25k
    auto disable = _disable_period_report.load(std::memory_order_acquire);
595
4.25k
    DCHECK(disable == true);
596
4.25k
    _previous_report_time.store(MonotonicNanos(), std::memory_order_release);
597
4.25k
    _disable_period_report.compare_exchange_strong(disable, false);
598
4.25k
}
599
600
5.70M
void PipelineFragmentContext::trigger_report_if_necessary() {
601
5.70M
    if (!_is_report_success) {
602
5.11M
        return;
603
5.11M
    }
604
585k
    auto disable = _disable_period_report.load(std::memory_order_acquire);
605
585k
    if (disable) {
606
7.88k
        return;
607
7.88k
    }
608
577k
    int32_t interval_s = config::pipeline_status_report_interval;
609
577k
    if (interval_s <= 0) {
610
0
        LOG(WARNING) << "config::status_report_interval is equal to or less than zero, do not "
611
0
                        "trigger "
612
0
                        "report.";
613
0
    }
614
577k
    uint64_t next_report_time = _previous_report_time.load(std::memory_order_acquire) +
615
577k
                                (uint64_t)(interval_s)*NANOS_PER_SEC;
616
577k
    if (MonotonicNanos() > next_report_time) {
617
4.25k
        if (!_disable_period_report.compare_exchange_strong(disable, true,
618
4.25k
                                                            std::memory_order_acq_rel)) {
619
2
            return;
620
2
        }
621
4.25k
        if (VLOG_FILE_IS_ON) {
622
0
            VLOG_FILE << "Reporting "
623
0
                      << "profile for query_id " << print_id(_query_id)
624
0
                      << ", fragment id: " << _fragment_id;
625
626
0
            std::stringstream ss;
627
0
            _runtime_state->runtime_profile()->compute_time_in_profile();
628
0
            _runtime_state->runtime_profile()->pretty_print(&ss);
629
0
            if (_runtime_state->load_channel_profile()) {
630
0
                _runtime_state->load_channel_profile()->pretty_print(&ss);
631
0
            }
632
633
0
            VLOG_FILE << "Query " << print_id(get_query_id()) << " fragment " << get_fragment_id()
634
0
                      << " profile:\n"
635
0
                      << ss.str();
636
0
        }
637
4.25k
        auto st = send_report(false);
638
4.25k
        if (!st.ok()) {
639
0
            disable = true;
640
0
            _disable_period_report.compare_exchange_strong(disable, false,
641
0
                                                           std::memory_order_acq_rel);
642
0
        }
643
4.25k
    }
644
577k
}
645
646
Status PipelineFragmentContext::_build_pipelines(ObjectPool* pool, const DescriptorTbl& descs,
647
339k
                                                 OperatorPtr* root, PipelinePtr cur_pipe) {
648
339k
    if (_params.fragment.plan.nodes.empty()) {
649
0
        throw Exception(ErrorCode::INTERNAL_ERROR, "Invalid plan which has no plan node!");
650
0
    }
651
652
339k
    int node_idx = 0;
653
654
339k
    RETURN_IF_ERROR(_create_tree_helper(pool, _params.fragment.plan.nodes, descs, nullptr,
655
339k
                                        &node_idx, root, cur_pipe, 0, false, false));
656
657
339k
    if (node_idx + 1 != _params.fragment.plan.nodes.size()) {
658
0
        return Status::InternalError(
659
0
                "Plan tree only partially reconstructed. Not all thrift nodes were used.");
660
0
    }
661
339k
    return Status::OK();
662
339k
}
663
664
Status PipelineFragmentContext::_create_tree_helper(
665
        ObjectPool* pool, const std::vector<TPlanNode>& tnodes, const DescriptorTbl& descs,
666
        OperatorPtr parent, int* node_idx, OperatorPtr* root, PipelinePtr& cur_pipe, int child_idx,
667
542k
        const bool followed_by_shuffled_operator, const bool require_bucket_distribution) {
668
    // propagate error case
669
542k
    if (*node_idx >= tnodes.size()) {
670
0
        return Status::InternalError(
671
0
                "Failed to reconstruct plan tree from thrift. Node id: {}, number of nodes: {}",
672
0
                *node_idx, tnodes.size());
673
0
    }
674
542k
    const TPlanNode& tnode = tnodes[*node_idx];
675
676
542k
    int num_children = tnodes[*node_idx].num_children;
677
542k
    bool current_followed_by_shuffled_operator = followed_by_shuffled_operator;
678
542k
    bool current_require_bucket_distribution = require_bucket_distribution;
679
    // TODO: Create CacheOperator is confused now
680
542k
    OperatorPtr op = nullptr;
681
542k
    OperatorPtr cache_op = nullptr;
682
542k
    RETURN_IF_ERROR(_create_operator(pool, tnodes[*node_idx], descs, op, cur_pipe,
683
542k
                                     parent == nullptr ? -1 : parent->node_id(), child_idx,
684
542k
                                     followed_by_shuffled_operator,
685
542k
                                     current_require_bucket_distribution, cache_op));
686
    // Initialization must be done here. For example, group by expressions in agg will be used to
687
    // decide if a local shuffle should be planed, so it must be initialized here.
688
542k
    RETURN_IF_ERROR(op->init(tnode, _runtime_state.get()));
689
    // assert(parent != nullptr || (node_idx == 0 && root_expr != nullptr));
690
542k
    if (parent != nullptr) {
691
        // add to parent's child(s)
692
203k
        RETURN_IF_ERROR(parent->set_child(cache_op ? cache_op : op));
693
339k
    } else {
694
339k
        *root = op;
695
339k
    }
696
    /**
697
     * `ExchangeType::HASH_SHUFFLE` should be used if an operator is followed by a shuffled operator (shuffled hash join, union operator followed by co-located operators).
698
     *
699
     * For plan:
700
     * LocalExchange(id=0) -> Aggregation(id=1) -> ShuffledHashJoin(id=2)
701
     *                           Exchange(id=3) -> ShuffledHashJoinBuild(id=2)
702
     * We must ensure data distribution of `LocalExchange(id=0)` is same as Exchange(id=3).
703
     *
704
     * If an operator's is followed by a local exchange without shuffle (e.g. passthrough), a
705
     * shuffled local exchanger will be used before join so it is not followed by shuffle join.
706
     */
707
542k
    auto required_data_distribution =
708
542k
            cur_pipe->operators().empty()
709
542k
                    ? cur_pipe->sink()->required_data_distribution(_runtime_state.get())
710
542k
                    : op->required_data_distribution(_runtime_state.get());
711
542k
    current_followed_by_shuffled_operator =
712
542k
            ((followed_by_shuffled_operator ||
713
542k
              (cur_pipe->operators().empty() ? cur_pipe->sink()->is_shuffled_operator()
714
480k
                                             : op->is_shuffled_operator())) &&
715
542k
             Pipeline::is_hash_exchange(required_data_distribution.distribution_type)) ||
716
542k
            (followed_by_shuffled_operator &&
717
425k
             required_data_distribution.distribution_type == ExchangeType::NOOP);
718
719
542k
    current_require_bucket_distribution =
720
542k
            ((require_bucket_distribution ||
721
542k
              (cur_pipe->operators().empty() ? cur_pipe->sink()->is_colocated_operator()
722
484k
                                             : op->is_colocated_operator())) &&
723
542k
             Pipeline::is_hash_exchange(required_data_distribution.distribution_type)) ||
724
542k
            (require_bucket_distribution &&
725
431k
             required_data_distribution.distribution_type == ExchangeType::NOOP);
726
727
542k
    if (num_children == 0) {
728
349k
        _use_serial_source = op->is_serial_operator();
729
349k
    }
730
    // rely on that tnodes is preorder of the plan
731
745k
    for (int i = 0; i < num_children; i++) {
732
203k
        ++*node_idx;
733
203k
        RETURN_IF_ERROR(_create_tree_helper(pool, tnodes, descs, op, node_idx, nullptr, cur_pipe, i,
734
203k
                                            current_followed_by_shuffled_operator,
735
203k
                                            current_require_bucket_distribution));
736
737
        // we are expecting a child, but have used all nodes
738
        // this means we have been given a bad tree and must fail
739
203k
        if (*node_idx >= tnodes.size()) {
740
0
            return Status::InternalError(
741
0
                    "Failed to reconstruct plan tree from thrift. Node id: {}, number of "
742
0
                    "nodes: {}",
743
0
                    *node_idx, tnodes.size());
744
0
        }
745
203k
    }
746
747
542k
    return Status::OK();
748
542k
}
749
750
void PipelineFragmentContext::_inherit_pipeline_properties(
751
        const DataDistribution& data_distribution, PipelinePtr pipe_with_source,
752
75.4k
        PipelinePtr pipe_with_sink) {
753
75.4k
    pipe_with_sink->set_num_tasks(pipe_with_source->num_tasks());
754
75.4k
    pipe_with_source->set_num_tasks(_num_instances);
755
75.4k
    pipe_with_source->set_data_distribution(data_distribution);
756
75.4k
}
757
758
Status PipelineFragmentContext::_add_local_exchange_impl(
759
        int idx, ObjectPool* pool, PipelinePtr cur_pipe, PipelinePtr new_pip,
760
        DataDistribution data_distribution, bool* do_local_exchange, int num_buckets,
761
        const std::map<int, int>& bucket_seq_to_instance_idx,
762
75.4k
        const std::map<int, int>& shuffle_idx_to_instance_idx) {
763
75.4k
    auto& operators = cur_pipe->operators();
764
75.4k
    const auto downstream_pipeline_id = cur_pipe->id();
765
75.4k
    auto local_exchange_id = next_operator_id();
766
    // 1. Create a new pipeline with local exchange sink.
767
75.4k
    DataSinkOperatorPtr sink;
768
75.4k
    auto sink_id = next_sink_operator_id();
769
770
    /**
771
     * `bucket_seq_to_instance_idx` is empty if no scan operator is contained in this fragment.
772
     * So co-located operators(e.g. Agg, Analytic) should use `HASH_SHUFFLE` instead of `BUCKET_HASH_SHUFFLE`.
773
     */
774
75.4k
    const bool followed_by_shuffled_operator =
775
75.4k
            operators.size() > idx ? operators[idx]->followed_by_shuffled_operator()
776
75.4k
                                   : cur_pipe->sink()->followed_by_shuffled_operator();
777
75.4k
    const bool use_global_hash_shuffle = bucket_seq_to_instance_idx.empty() &&
778
75.4k
                                         !shuffle_idx_to_instance_idx.contains(-1) &&
779
75.4k
                                         followed_by_shuffled_operator && !_use_serial_source;
780
75.4k
    sink = std::make_shared<LocalExchangeSinkOperatorX>(
781
75.4k
            sink_id, local_exchange_id, use_global_hash_shuffle ? _total_instances : _num_instances,
782
75.4k
            data_distribution.partition_exprs, bucket_seq_to_instance_idx);
783
75.4k
    if (bucket_seq_to_instance_idx.empty() &&
784
75.4k
        data_distribution.distribution_type == ExchangeType::BUCKET_HASH_SHUFFLE) {
785
3
        data_distribution.distribution_type = ExchangeType::HASH_SHUFFLE;
786
3
    }
787
75.4k
    RETURN_IF_ERROR(new_pip->set_sink(sink));
788
75.4k
    RETURN_IF_ERROR(new_pip->sink()->init(_runtime_state.get(), data_distribution.distribution_type,
789
75.4k
                                          num_buckets, use_global_hash_shuffle,
790
75.4k
                                          shuffle_idx_to_instance_idx));
791
792
    // 2. Create and initialize LocalExchangeSharedState.
793
75.4k
    std::shared_ptr<LocalExchangeSharedState> shared_state =
794
75.4k
            LocalExchangeSharedState::create_shared(_num_instances);
795
75.4k
    switch (data_distribution.distribution_type) {
796
13.0k
    case ExchangeType::HASH_SHUFFLE:
797
13.0k
        shared_state->exchanger = ShuffleExchanger::create_unique(
798
13.0k
                std::max(cur_pipe->num_tasks(), _num_instances), _num_instances,
799
13.0k
                use_global_hash_shuffle ? _total_instances : _num_instances,
800
13.0k
                _runtime_state->query_options().__isset.local_exchange_free_blocks_limit
801
13.0k
                        ? cast_set<int>(
802
13.0k
                                  _runtime_state->query_options().local_exchange_free_blocks_limit)
803
13.0k
                        : 0);
804
13.0k
        break;
805
378
    case ExchangeType::BUCKET_HASH_SHUFFLE:
806
378
        shared_state->exchanger = BucketShuffleExchanger::create_unique(
807
378
                std::max(cur_pipe->num_tasks(), _num_instances), _num_instances, num_buckets,
808
378
                _runtime_state->query_options().__isset.local_exchange_free_blocks_limit
809
378
                        ? cast_set<int>(
810
378
                                  _runtime_state->query_options().local_exchange_free_blocks_limit)
811
378
                        : 0);
812
378
        break;
813
59.1k
    case ExchangeType::PASSTHROUGH:
814
59.1k
        shared_state->exchanger = PassthroughExchanger::create_unique(
815
59.1k
                cur_pipe->num_tasks(), _num_instances,
816
59.1k
                _runtime_state->query_options().__isset.local_exchange_free_blocks_limit
817
59.1k
                        ? cast_set<int>(
818
59.1k
                                  _runtime_state->query_options().local_exchange_free_blocks_limit)
819
59.1k
                        : 0);
820
59.1k
        break;
821
253
    case ExchangeType::BROADCAST:
822
253
        shared_state->exchanger = BroadcastExchanger::create_unique(
823
253
                cur_pipe->num_tasks(), _num_instances,
824
253
                _runtime_state->query_options().__isset.local_exchange_free_blocks_limit
825
253
                        ? cast_set<int>(
826
253
                                  _runtime_state->query_options().local_exchange_free_blocks_limit)
827
253
                        : 0);
828
253
        break;
829
1.91k
    case ExchangeType::PASS_TO_ONE:
830
1.91k
        if (_runtime_state->enable_share_hash_table_for_broadcast_join()) {
831
            // If shared hash table is enabled for BJ, hash table will be built by only one task
832
1.10k
            shared_state->exchanger = PassToOneExchanger::create_unique(
833
1.10k
                    cur_pipe->num_tasks(), _num_instances,
834
1.10k
                    _runtime_state->query_options().__isset.local_exchange_free_blocks_limit
835
1.10k
                            ? cast_set<int>(_runtime_state->query_options()
836
1.10k
                                                    .local_exchange_free_blocks_limit)
837
1.10k
                            : 0);
838
1.10k
        } else {
839
810
            shared_state->exchanger = BroadcastExchanger::create_unique(
840
810
                    cur_pipe->num_tasks(), _num_instances,
841
810
                    _runtime_state->query_options().__isset.local_exchange_free_blocks_limit
842
810
                            ? cast_set<int>(_runtime_state->query_options()
843
810
                                                    .local_exchange_free_blocks_limit)
844
810
                            : 0);
845
810
        }
846
1.91k
        break;
847
656
    case ExchangeType::ADAPTIVE_PASSTHROUGH:
848
656
        shared_state->exchanger = AdaptivePassthroughExchanger::create_unique(
849
656
                std::max(cur_pipe->num_tasks(), _num_instances), _num_instances,
850
656
                _runtime_state->query_options().__isset.local_exchange_free_blocks_limit
851
656
                        ? cast_set<int>(
852
656
                                  _runtime_state->query_options().local_exchange_free_blocks_limit)
853
656
                        : 0);
854
656
        break;
855
0
    default:
856
0
        return Status::InternalError("Unsupported local exchange type : " +
857
0
                                     std::to_string((int)data_distribution.distribution_type));
858
75.4k
    }
859
75.4k
    shared_state->create_source_dependencies(_num_instances, local_exchange_id, local_exchange_id,
860
75.4k
                                             "LOCAL_EXCHANGE_OPERATOR");
861
75.4k
    shared_state->create_sink_dependency(sink_id, local_exchange_id, "LOCAL_EXCHANGE_SINK");
862
75.4k
    _op_id_to_shared_state.insert({local_exchange_id, {shared_state, shared_state->sink_deps}});
863
864
    // 3. Set two pipelines' operator list. For example, split pipeline [Scan - AggSink] to
865
    // pipeline1 [Scan - LocalExchangeSink] and pipeline2 [LocalExchangeSource - AggSink].
866
867
    // 3.1 Initialize new pipeline's operator list.
868
75.4k
    std::copy(operators.begin(), operators.begin() + idx,
869
75.4k
              std::inserter(new_pip->operators(), new_pip->operators().end()));
870
871
    // 3.2 Erase unused operators in previous pipeline.
872
75.4k
    operators.erase(operators.begin(), operators.begin() + idx);
873
874
    // 4. Initialize LocalExchangeSource and insert it into this pipeline.
875
75.4k
    OperatorPtr source_op;
876
75.4k
    source_op = std::make_shared<LocalExchangeSourceOperatorX>(pool, local_exchange_id);
877
75.4k
    RETURN_IF_ERROR(source_op->set_child(new_pip->operators().back()));
878
75.4k
    RETURN_IF_ERROR(source_op->init(data_distribution.distribution_type));
879
75.4k
    if (!operators.empty()) {
880
25.2k
        RETURN_IF_ERROR(operators.front()->set_child(nullptr));
881
25.2k
        RETURN_IF_ERROR(operators.front()->set_child(source_op));
882
25.2k
    }
883
75.4k
    operators.insert(operators.begin(), source_op);
884
885
    // 5. Set children for two pipelines separately.
886
75.4k
    std::vector<std::shared_ptr<Pipeline>> new_children;
887
75.4k
    std::vector<PipelineId> edges_with_source;
888
90.7k
    for (auto child : cur_pipe->children()) {
889
90.7k
        bool found = false;
890
103k
        for (auto op : new_pip->operators()) {
891
103k
            if (child->sink()->node_id() == op->node_id()) {
892
10.9k
                new_pip->set_children(child);
893
10.9k
                found = true;
894
10.9k
            };
895
103k
        }
896
90.7k
        if (!found) {
897
79.8k
            new_children.push_back(child);
898
79.8k
            edges_with_source.push_back(child->id());
899
79.8k
        }
900
90.7k
    }
901
75.4k
    new_children.push_back(new_pip);
902
75.4k
    edges_with_source.push_back(new_pip->id());
903
904
    // 6. Set DAG for new pipelines.
905
75.4k
    if (!new_pip->children().empty()) {
906
6.33k
        std::vector<PipelineId> edges_with_sink;
907
10.9k
        for (auto child : new_pip->children()) {
908
10.9k
            edges_with_sink.push_back(child->id());
909
10.9k
        }
910
6.33k
        _dag.insert({new_pip->id(), edges_with_sink});
911
6.33k
    }
912
75.4k
    cur_pipe->set_children(new_children);
913
75.4k
    _dag[downstream_pipeline_id] = edges_with_source;
914
75.4k
    RETURN_IF_ERROR(new_pip->sink()->set_child(new_pip->operators().back()));
915
75.4k
    RETURN_IF_ERROR(cur_pipe->sink()->set_child(nullptr));
916
75.4k
    RETURN_IF_ERROR(cur_pipe->sink()->set_child(cur_pipe->operators().back()));
917
918
    // 7. Inherit properties from current pipeline.
919
75.4k
    _inherit_pipeline_properties(data_distribution, cur_pipe, new_pip);
920
75.4k
    return Status::OK();
921
75.4k
}
922
923
Status PipelineFragmentContext::_add_local_exchange(
924
        int pip_idx, int idx, int node_id, ObjectPool* pool, PipelinePtr cur_pipe,
925
        DataDistribution data_distribution, bool* do_local_exchange, int num_buckets,
926
        const std::map<int, int>& bucket_seq_to_instance_idx,
927
160k
        const std::map<int, int>& shuffle_idx_to_instance_idx) {
928
160k
    if (_num_instances <= 1 || cur_pipe->num_tasks_of_parent() <= 1) {
929
65.8k
        return Status::OK();
930
65.8k
    }
931
932
94.2k
    if (!cur_pipe->need_to_local_exchange(data_distribution, idx)) {
933
32.3k
        return Status::OK();
934
32.3k
    }
935
61.9k
    *do_local_exchange = true;
936
937
61.9k
    auto& operators = cur_pipe->operators();
938
61.9k
    auto total_op_num = operators.size();
939
61.9k
    auto new_pip = add_pipeline(cur_pipe, pip_idx + 1);
940
61.9k
    RETURN_IF_ERROR(_add_local_exchange_impl(
941
61.9k
            idx, pool, cur_pipe, new_pip, data_distribution, do_local_exchange, num_buckets,
942
61.9k
            bucket_seq_to_instance_idx, shuffle_idx_to_instance_idx));
943
944
18.4E
    CHECK(total_op_num + 1 == cur_pipe->operators().size() + new_pip->operators().size())
945
18.4E
            << "total_op_num: " << total_op_num
946
18.4E
            << " cur_pipe->operators().size(): " << cur_pipe->operators().size()
947
18.4E
            << " new_pip->operators().size(): " << new_pip->operators().size();
948
949
    // There are some local shuffles with relatively heavy operations on the sink.
950
    // If the local sink concurrency is 1 and the local source concurrency is n, the sink becomes a bottleneck.
951
    // Therefore, local passthrough is used to increase the concurrency of the sink.
952
    // op -> local sink(1) -> local source (n)
953
    // op -> local passthrough(1) -> local passthrough(n) ->  local sink(n) -> local source (n)
954
62.3k
    if (cur_pipe->num_tasks() > 1 && new_pip->num_tasks() == 1 &&
955
61.9k
        Pipeline::heavy_operations_on_the_sink(data_distribution.distribution_type)) {
956
13.0k
        RETURN_IF_ERROR(_add_local_exchange_impl(
957
13.0k
                cast_set<int>(new_pip->operators().size()), pool, new_pip,
958
13.0k
                add_pipeline(new_pip, pip_idx + 2), DataDistribution(ExchangeType::PASSTHROUGH),
959
13.0k
                do_local_exchange, num_buckets, bucket_seq_to_instance_idx,
960
13.0k
                shuffle_idx_to_instance_idx));
961
13.0k
    }
962
61.9k
    return Status::OK();
963
61.9k
}
964
965
Status PipelineFragmentContext::_plan_local_exchange(
966
        int num_buckets, const std::map<int, int>& bucket_seq_to_instance_idx,
967
337k
        const std::map<int, int>& shuffle_idx_to_instance_idx) {
968
799k
    for (int pip_idx = cast_set<int>(_pipelines.size()) - 1; pip_idx >= 0; pip_idx--) {
969
461k
        _pipelines[pip_idx]->init_data_distribution(_runtime_state.get());
970
        // Set property if child pipeline is not join operator's child.
971
461k
        if (!_pipelines[pip_idx]->children().empty()) {
972
122k
            for (auto& child : _pipelines[pip_idx]->children()) {
973
122k
                if (child->sink()->node_id() ==
974
122k
                    _pipelines[pip_idx]->operators().front()->node_id()) {
975
113k
                    _pipelines[pip_idx]->set_data_distribution(child->data_distribution());
976
113k
                }
977
122k
            }
978
119k
        }
979
980
        // if 'num_buckets == 0' means the fragment is colocated by exchange node not the
981
        // scan node. so here use `_num_instance` to replace the `num_buckets` to prevent dividing 0
982
        // still keep colocate plan after local shuffle
983
461k
        RETURN_IF_ERROR(_plan_local_exchange(num_buckets, pip_idx, _pipelines[pip_idx],
984
461k
                                             bucket_seq_to_instance_idx,
985
461k
                                             shuffle_idx_to_instance_idx));
986
461k
    }
987
337k
    return Status::OK();
988
337k
}
989
990
Status PipelineFragmentContext::_plan_local_exchange(
991
        int num_buckets, int pip_idx, PipelinePtr pip,
992
        const std::map<int, int>& bucket_seq_to_instance_idx,
993
461k
        const std::map<int, int>& shuffle_idx_to_instance_idx) {
994
461k
    int idx = 1;
995
461k
    bool do_local_exchange = false;
996
486k
    do {
997
486k
        auto& ops = pip->operators();
998
486k
        do_local_exchange = false;
999
        // Plan local exchange for each operator.
1000
572k
        for (; idx < ops.size();) {
1001
111k
            if (ops[idx]->required_data_distribution(_runtime_state.get()).need_local_exchange()) {
1002
100k
                RETURN_IF_ERROR(_add_local_exchange(
1003
100k
                        pip_idx, idx, ops[idx]->node_id(), _runtime_state->obj_pool(), pip,
1004
100k
                        ops[idx]->required_data_distribution(_runtime_state.get()),
1005
100k
                        &do_local_exchange, num_buckets, bucket_seq_to_instance_idx,
1006
100k
                        shuffle_idx_to_instance_idx));
1007
100k
            }
1008
111k
            if (do_local_exchange) {
1009
                // If local exchange is needed for current operator, we will split this pipeline to
1010
                // two pipelines by local exchange sink/source. And then we need to process remaining
1011
                // operators in this pipeline so we set idx to 2 (0 is local exchange source and 1
1012
                // is current operator was already processed) and continue to plan local exchange.
1013
25.3k
                idx = 2;
1014
25.3k
                break;
1015
25.3k
            }
1016
85.8k
            idx++;
1017
85.8k
        }
1018
486k
    } while (do_local_exchange);
1019
461k
    if (pip->sink()->required_data_distribution(_runtime_state.get()).need_local_exchange()) {
1020
60.1k
        RETURN_IF_ERROR(_add_local_exchange(
1021
60.1k
                pip_idx, idx, pip->sink()->node_id(), _runtime_state->obj_pool(), pip,
1022
60.1k
                pip->sink()->required_data_distribution(_runtime_state.get()), &do_local_exchange,
1023
60.1k
                num_buckets, bucket_seq_to_instance_idx, shuffle_idx_to_instance_idx));
1024
60.1k
    }
1025
461k
    return Status::OK();
1026
461k
}
1027
1028
Status PipelineFragmentContext::_create_data_sink(ObjectPool* pool, const TDataSink& thrift_sink,
1029
                                                  const std::vector<TExpr>& output_exprs,
1030
                                                  const TPipelineFragmentParams& params,
1031
                                                  const RowDescriptor& row_desc,
1032
                                                  RuntimeState* state, DescriptorTbl& desc_tbl,
1033
340k
                                                  PipelineId cur_pipeline_id) {
1034
340k
    switch (thrift_sink.type) {
1035
120k
    case TDataSinkType::DATA_STREAM_SINK: {
1036
120k
        if (!thrift_sink.__isset.stream_sink) {
1037
0
            return Status::InternalError("Missing data stream sink.");
1038
0
        }
1039
120k
        _sink = std::make_shared<ExchangeSinkOperatorX>(
1040
120k
                state, row_desc, next_sink_operator_id(), thrift_sink.stream_sink,
1041
120k
                params.destinations, _fragment_instance_ids);
1042
120k
        break;
1043
120k
    }
1044
190k
    case TDataSinkType::RESULT_SINK: {
1045
190k
        if (!thrift_sink.__isset.result_sink) {
1046
0
            return Status::InternalError("Missing data buffer sink.");
1047
0
        }
1048
1049
190k
        _sink = std::make_shared<ResultSinkOperatorX>(next_sink_operator_id(), row_desc,
1050
190k
                                                      output_exprs, thrift_sink.result_sink);
1051
190k
        break;
1052
190k
    }
1053
104
    case TDataSinkType::DICTIONARY_SINK: {
1054
104
        if (!thrift_sink.__isset.dictionary_sink) {
1055
0
            return Status::InternalError("Missing dict sink.");
1056
0
        }
1057
1058
104
        _sink = std::make_shared<DictSinkOperatorX>(next_sink_operator_id(), row_desc, output_exprs,
1059
104
                                                    thrift_sink.dictionary_sink);
1060
104
        break;
1061
104
    }
1062
0
    case TDataSinkType::GROUP_COMMIT_OLAP_TABLE_SINK:
1063
28.3k
    case TDataSinkType::OLAP_TABLE_SINK: {
1064
28.3k
        if (state->query_options().enable_memtable_on_sink_node &&
1065
28.3k
            !_has_inverted_index_v1_or_partial_update(thrift_sink.olap_table_sink) &&
1066
28.3k
            !config::is_cloud_mode()) {
1067
0
            _sink = std::make_shared<OlapTableSinkV2OperatorX>(pool, next_sink_operator_id(),
1068
0
                                                               row_desc, output_exprs);
1069
28.3k
        } else {
1070
28.3k
            _sink = std::make_shared<OlapTableSinkOperatorX>(pool, next_sink_operator_id(),
1071
28.3k
                                                             row_desc, output_exprs);
1072
28.3k
        }
1073
28.3k
        break;
1074
0
    }
1075
165
    case TDataSinkType::GROUP_COMMIT_BLOCK_SINK: {
1076
165
        DCHECK(thrift_sink.__isset.olap_table_sink);
1077
165
        DCHECK(state->get_query_ctx() != nullptr);
1078
165
        state->get_query_ctx()->query_mem_tracker()->is_group_commit_load = true;
1079
165
        _sink = std::make_shared<GroupCommitBlockSinkOperatorX>(next_sink_operator_id(), row_desc,
1080
165
                                                                output_exprs);
1081
165
        break;
1082
0
    }
1083
0
    case TDataSinkType::HIVE_TABLE_SINK: {
1084
0
        if (!thrift_sink.__isset.hive_table_sink) {
1085
0
            return Status::InternalError("Missing hive table sink.");
1086
0
        }
1087
0
        _sink = std::make_shared<HiveTableSinkOperatorX>(pool, next_sink_operator_id(), row_desc,
1088
0
                                                         output_exprs);
1089
0
        break;
1090
0
    }
1091
0
    case TDataSinkType::ICEBERG_TABLE_SINK: {
1092
0
        if (!thrift_sink.__isset.iceberg_table_sink) {
1093
0
            return Status::InternalError("Missing iceberg table sink.");
1094
0
        }
1095
0
        if (thrift_sink.iceberg_table_sink.__isset.sort_info) {
1096
0
            _sink = std::make_shared<SpillIcebergTableSinkOperatorX>(pool, next_sink_operator_id(),
1097
0
                                                                     row_desc, output_exprs);
1098
0
        } else {
1099
0
            _sink = std::make_shared<IcebergTableSinkOperatorX>(pool, next_sink_operator_id(),
1100
0
                                                                row_desc, output_exprs);
1101
0
        }
1102
0
        break;
1103
0
    }
1104
0
    case TDataSinkType::MAXCOMPUTE_TABLE_SINK: {
1105
0
        if (!thrift_sink.__isset.max_compute_table_sink) {
1106
0
            return Status::InternalError("Missing max compute table sink.");
1107
0
        }
1108
0
        _sink = std::make_shared<MCTableSinkOperatorX>(pool, next_sink_operator_id(), row_desc,
1109
0
                                                       output_exprs);
1110
0
        break;
1111
0
    }
1112
0
    case TDataSinkType::JDBC_TABLE_SINK: {
1113
0
        if (!thrift_sink.__isset.jdbc_table_sink) {
1114
0
            return Status::InternalError("Missing data jdbc sink.");
1115
0
        }
1116
0
        if (config::enable_java_support) {
1117
0
            _sink = std::make_shared<JdbcTableSinkOperatorX>(row_desc, next_sink_operator_id(),
1118
0
                                                             output_exprs);
1119
0
        } else {
1120
0
            return Status::InternalError(
1121
0
                    "Jdbc table sink is not enabled, you can change be config "
1122
0
                    "enable_java_support to true and restart be.");
1123
0
        }
1124
0
        break;
1125
0
    }
1126
3
    case TDataSinkType::MEMORY_SCRATCH_SINK: {
1127
3
        if (!thrift_sink.__isset.memory_scratch_sink) {
1128
0
            return Status::InternalError("Missing data buffer sink.");
1129
0
        }
1130
1131
3
        _sink = std::make_shared<MemoryScratchSinkOperatorX>(row_desc, next_sink_operator_id(),
1132
3
                                                             output_exprs);
1133
3
        break;
1134
3
    }
1135
321
    case TDataSinkType::RESULT_FILE_SINK: {
1136
321
        if (!thrift_sink.__isset.result_file_sink) {
1137
0
            return Status::InternalError("Missing result file sink.");
1138
0
        }
1139
1140
        // Result file sink is not the top sink
1141
321
        if (params.__isset.destinations && !params.destinations.empty()) {
1142
0
            _sink = std::make_shared<ResultFileSinkOperatorX>(
1143
0
                    next_sink_operator_id(), row_desc, thrift_sink.result_file_sink,
1144
0
                    params.destinations, output_exprs, desc_tbl);
1145
321
        } else {
1146
321
            _sink = std::make_shared<ResultFileSinkOperatorX>(next_sink_operator_id(), row_desc,
1147
321
                                                              output_exprs);
1148
321
        }
1149
321
        break;
1150
321
    }
1151
513
    case TDataSinkType::MULTI_CAST_DATA_STREAM_SINK: {
1152
513
        DCHECK(thrift_sink.__isset.multi_cast_stream_sink);
1153
513
        DCHECK_GT(thrift_sink.multi_cast_stream_sink.sinks.size(), 0);
1154
513
        auto sink_id = next_sink_operator_id();
1155
513
        const int multi_cast_node_id = sink_id;
1156
513
        auto sender_size = thrift_sink.multi_cast_stream_sink.sinks.size();
1157
        // one sink has multiple sources.
1158
513
        std::vector<int> sources;
1159
1.83k
        for (int i = 0; i < sender_size; ++i) {
1160
1.32k
            auto source_id = next_operator_id();
1161
1.32k
            sources.push_back(source_id);
1162
1.32k
        }
1163
1164
513
        _sink = std::make_shared<MultiCastDataStreamSinkOperatorX>(
1165
513
                sink_id, multi_cast_node_id, sources, pool, thrift_sink.multi_cast_stream_sink);
1166
1.83k
        for (int i = 0; i < sender_size; ++i) {
1167
1.32k
            auto new_pipeline = add_pipeline();
1168
            // use to exchange sink
1169
1.32k
            RowDescriptor* exchange_row_desc = nullptr;
1170
1.32k
            {
1171
1.32k
                const auto& tmp_row_desc =
1172
1.32k
                        !thrift_sink.multi_cast_stream_sink.sinks[i].output_exprs.empty()
1173
1.32k
                                ? RowDescriptor(state->desc_tbl(),
1174
1.32k
                                                {thrift_sink.multi_cast_stream_sink.sinks[i]
1175
1.32k
                                                         .output_tuple_id})
1176
1.32k
                                : row_desc;
1177
1.32k
                exchange_row_desc = pool->add(new RowDescriptor(tmp_row_desc));
1178
1.32k
            }
1179
1.32k
            auto source_id = sources[i];
1180
1.32k
            OperatorPtr source_op;
1181
            // 1. create and set the source operator of multi_cast_data_stream_source for new pipeline
1182
1.32k
            source_op = std::make_shared<MultiCastDataStreamerSourceOperatorX>(
1183
1.32k
                    /*node_id*/ source_id, /*consumer_id*/ i, pool,
1184
1.32k
                    thrift_sink.multi_cast_stream_sink.sinks[i], row_desc,
1185
1.32k
                    /*operator_id=*/source_id);
1186
1.32k
            RETURN_IF_ERROR(new_pipeline->add_operator(
1187
1.32k
                    source_op, params.__isset.parallel_instances ? params.parallel_instances : 0));
1188
            // 2. create and set sink operator of data stream sender for new pipeline
1189
1190
1.32k
            DataSinkOperatorPtr sink_op;
1191
1.32k
            sink_op = std::make_shared<ExchangeSinkOperatorX>(
1192
1.32k
                    state, *exchange_row_desc, next_sink_operator_id(),
1193
1.32k
                    thrift_sink.multi_cast_stream_sink.sinks[i],
1194
1.32k
                    thrift_sink.multi_cast_stream_sink.destinations[i], _fragment_instance_ids);
1195
1196
1.32k
            RETURN_IF_ERROR(new_pipeline->set_sink(sink_op));
1197
1.32k
            {
1198
1.32k
                TDataSink* t = pool->add(new TDataSink());
1199
1.32k
                t->stream_sink = thrift_sink.multi_cast_stream_sink.sinks[i];
1200
1.32k
                RETURN_IF_ERROR(sink_op->init(*t));
1201
1.32k
            }
1202
1203
            // 3. set dependency dag
1204
1.32k
            _dag[new_pipeline->id()].push_back(cur_pipeline_id);
1205
1.32k
        }
1206
513
        if (sources.empty()) {
1207
0
            return Status::InternalError("size of sources must be greater than 0");
1208
0
        }
1209
513
        break;
1210
513
    }
1211
513
    case TDataSinkType::BLACKHOLE_SINK: {
1212
3
        if (!thrift_sink.__isset.blackhole_sink) {
1213
0
            return Status::InternalError("Missing blackhole sink.");
1214
0
        }
1215
1216
3
        _sink.reset(new BlackholeSinkOperatorX(next_sink_operator_id()));
1217
3
        break;
1218
3
    }
1219
0
    case TDataSinkType::TVF_TABLE_SINK: {
1220
0
        if (!thrift_sink.__isset.tvf_table_sink) {
1221
0
            return Status::InternalError("Missing TVF table sink.");
1222
0
        }
1223
0
        _sink = std::make_shared<TVFTableSinkOperatorX>(pool, next_sink_operator_id(), row_desc,
1224
0
                                                        output_exprs);
1225
0
        break;
1226
0
    }
1227
0
    default:
1228
0
        return Status::InternalError("Unsuported sink type in pipeline: {}", thrift_sink.type);
1229
340k
    }
1230
340k
    return Status::OK();
1231
340k
}
1232
1233
// NOLINTBEGIN(readability-function-size)
1234
// NOLINTBEGIN(readability-function-cognitive-complexity)
1235
Status PipelineFragmentContext::_create_operator(ObjectPool* pool, const TPlanNode& tnode,
1236
                                                 const DescriptorTbl& descs, OperatorPtr& op,
1237
                                                 PipelinePtr& cur_pipe, int parent_idx,
1238
                                                 int child_idx,
1239
                                                 const bool followed_by_shuffled_operator,
1240
                                                 const bool require_bucket_distribution,
1241
544k
                                                 OperatorPtr& cache_op) {
1242
544k
    std::vector<DataSinkOperatorPtr> sink_ops;
1243
544k
    Defer defer = Defer([&]() {
1244
543k
        if (op) {
1245
543k
            op->update_operator(tnode, followed_by_shuffled_operator, require_bucket_distribution);
1246
543k
        }
1247
543k
        for (auto& s : sink_ops) {
1248
92.0k
            s->update_operator(tnode, followed_by_shuffled_operator, require_bucket_distribution);
1249
92.0k
        }
1250
543k
    });
1251
    // We directly construct the operator from Thrift because the given array is in the order of preorder traversal.
1252
    // Therefore, here we need to use a stack-like structure.
1253
544k
    _pipeline_parent_map.pop(cur_pipe, parent_idx, child_idx);
1254
544k
    std::stringstream error_msg;
1255
544k
    bool enable_query_cache = _params.fragment.__isset.query_cache_param;
1256
1257
544k
    bool fe_with_old_version = false;
1258
544k
    switch (tnode.node_type) {
1259
168k
    case TPlanNodeType::OLAP_SCAN_NODE: {
1260
168k
        op = std::make_shared<OlapScanOperatorX>(
1261
168k
                pool, tnode, next_operator_id(), descs, _num_instances,
1262
168k
                enable_query_cache ? _params.fragment.query_cache_param : TQueryCacheParam {});
1263
168k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1264
168k
        fe_with_old_version = !tnode.__isset.is_serial_operator;
1265
168k
        break;
1266
168k
    }
1267
79
    case TPlanNodeType::GROUP_COMMIT_SCAN_NODE: {
1268
79
        DCHECK(_query_ctx != nullptr);
1269
79
        _query_ctx->query_mem_tracker()->is_group_commit_load = true;
1270
79
        op = std::make_shared<GroupCommitOperatorX>(pool, tnode, next_operator_id(), descs,
1271
79
                                                    _num_instances);
1272
79
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1273
79
        fe_with_old_version = !tnode.__isset.is_serial_operator;
1274
79
        break;
1275
79
    }
1276
0
    case TPlanNodeType::JDBC_SCAN_NODE: {
1277
0
        if (config::enable_java_support) {
1278
0
            op = std::make_shared<JDBCScanOperatorX>(pool, tnode, next_operator_id(), descs,
1279
0
                                                     _num_instances);
1280
0
            RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1281
0
        } else {
1282
0
            return Status::InternalError(
1283
0
                    "Jdbc scan node is disabled, you can change be config enable_java_support "
1284
0
                    "to true and restart be.");
1285
0
        }
1286
0
        fe_with_old_version = !tnode.__isset.is_serial_operator;
1287
0
        break;
1288
0
    }
1289
2.66k
    case TPlanNodeType::FILE_SCAN_NODE: {
1290
2.66k
        op = std::make_shared<FileScanOperatorX>(pool, tnode, next_operator_id(), descs,
1291
2.66k
                                                 _num_instances);
1292
2.66k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1293
2.66k
        fe_with_old_version = !tnode.__isset.is_serial_operator;
1294
2.66k
        break;
1295
2.66k
    }
1296
0
    case TPlanNodeType::ES_SCAN_NODE:
1297
0
    case TPlanNodeType::ES_HTTP_SCAN_NODE: {
1298
0
        op = std::make_shared<EsScanOperatorX>(pool, tnode, next_operator_id(), descs,
1299
0
                                               _num_instances);
1300
0
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1301
0
        fe_with_old_version = !tnode.__isset.is_serial_operator;
1302
0
        break;
1303
0
    }
1304
119k
    case TPlanNodeType::EXCHANGE_NODE: {
1305
119k
        int num_senders = _params.per_exch_num_senders.contains(tnode.node_id)
1306
119k
                                  ? _params.per_exch_num_senders.find(tnode.node_id)->second
1307
18.4E
                                  : 0;
1308
119k
        DCHECK_GT(num_senders, 0);
1309
119k
        op = std::make_shared<ExchangeSourceOperatorX>(pool, tnode, next_operator_id(), descs,
1310
119k
                                                       num_senders);
1311
119k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1312
119k
        fe_with_old_version = !tnode.__isset.is_serial_operator;
1313
119k
        break;
1314
119k
    }
1315
146k
    case TPlanNodeType::AGGREGATION_NODE: {
1316
146k
        if (tnode.agg_node.grouping_exprs.empty() &&
1317
146k
            descs.get_tuple_descriptor(tnode.agg_node.output_tuple_id)->slots().empty()) {
1318
0
            return Status::InternalError("Illegal aggregate node " + std::to_string(tnode.node_id) +
1319
0
                                         ": group by and output is empty");
1320
0
        }
1321
146k
        bool need_create_cache_op =
1322
146k
                enable_query_cache && tnode.node_id == _params.fragment.query_cache_param.node_id;
1323
146k
        auto create_query_cache_operator = [&](PipelinePtr& new_pipe) {
1324
29.9k
            auto cache_node_id = _params.local_params[0].per_node_scan_ranges.begin()->first;
1325
29.9k
            auto cache_source_id = next_operator_id();
1326
29.9k
            op = std::make_shared<CacheSourceOperatorX>(pool, cache_node_id, cache_source_id,
1327
29.9k
                                                        _params.fragment.query_cache_param);
1328
29.9k
            RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1329
1330
29.9k
            const auto downstream_pipeline_id = cur_pipe->id();
1331
30.0k
            if (!_dag.contains(downstream_pipeline_id)) {
1332
30.0k
                _dag.insert({downstream_pipeline_id, {}});
1333
30.0k
            }
1334
29.9k
            new_pipe = add_pipeline(cur_pipe);
1335
29.9k
            _dag[downstream_pipeline_id].push_back(new_pipe->id());
1336
1337
29.9k
            DataSinkOperatorPtr cache_sink(new CacheSinkOperatorX(
1338
29.9k
                    next_sink_operator_id(), op->node_id(), op->operator_id()));
1339
29.9k
            RETURN_IF_ERROR(new_pipe->set_sink(cache_sink));
1340
29.9k
            return Status::OK();
1341
29.9k
        };
1342
146k
        const bool group_by_limit_opt =
1343
146k
                tnode.agg_node.__isset.agg_sort_info_by_group_key && tnode.limit > 0;
1344
1345
        /// PartitionedAggSourceOperatorX does not support "group by limit opt(#29641)" yet.
1346
        /// If `group_by_limit_opt` is true, then it might not need to spill at all.
1347
146k
        const bool enable_spill = _runtime_state->enable_spill() &&
1348
146k
                                  !tnode.agg_node.grouping_exprs.empty() && !group_by_limit_opt;
1349
146k
        const bool is_streaming_agg = tnode.agg_node.__isset.use_streaming_preaggregation &&
1350
146k
                                      tnode.agg_node.use_streaming_preaggregation &&
1351
146k
                                      !tnode.agg_node.grouping_exprs.empty();
1352
        // TODO: distinct streaming agg does not support spill.
1353
146k
        const bool can_use_distinct_streaming_agg =
1354
146k
                (!enable_spill || is_streaming_agg) && tnode.agg_node.aggregate_functions.empty() &&
1355
146k
                !tnode.agg_node.__isset.agg_sort_info_by_group_key &&
1356
146k
                _params.query_options.__isset.enable_distinct_streaming_aggregation &&
1357
146k
                _params.query_options.enable_distinct_streaming_aggregation;
1358
1359
146k
        if (can_use_distinct_streaming_agg) {
1360
99.0k
            if (need_create_cache_op) {
1361
26.5k
                PipelinePtr new_pipe;
1362
26.5k
                RETURN_IF_ERROR(create_query_cache_operator(new_pipe));
1363
1364
26.5k
                cache_op = op;
1365
26.5k
                op = std::make_shared<DistinctStreamingAggOperatorX>(pool, next_operator_id(),
1366
26.5k
                                                                     tnode, descs);
1367
26.5k
                RETURN_IF_ERROR(new_pipe->add_operator(op, _parallel_instances));
1368
26.5k
                RETURN_IF_ERROR(cur_pipe->operators().front()->set_child(op));
1369
26.5k
                cur_pipe = new_pipe;
1370
72.5k
            } else {
1371
72.5k
                op = std::make_shared<DistinctStreamingAggOperatorX>(pool, next_operator_id(),
1372
72.5k
                                                                     tnode, descs);
1373
72.5k
                RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1374
72.5k
            }
1375
99.0k
        } else if (is_streaming_agg) {
1376
1.03k
            if (need_create_cache_op) {
1377
277
                PipelinePtr new_pipe;
1378
277
                RETURN_IF_ERROR(create_query_cache_operator(new_pipe));
1379
277
                cache_op = op;
1380
277
                op = std::make_shared<StreamingAggOperatorX>(pool, next_operator_id(), tnode,
1381
277
                                                             descs);
1382
277
                RETURN_IF_ERROR(cur_pipe->operators().front()->set_child(op));
1383
277
                RETURN_IF_ERROR(new_pipe->add_operator(op, _parallel_instances));
1384
277
                cur_pipe = new_pipe;
1385
761
            } else {
1386
761
                op = std::make_shared<StreamingAggOperatorX>(pool, next_operator_id(), tnode,
1387
761
                                                             descs);
1388
761
                RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1389
761
            }
1390
46.3k
        } else {
1391
            // create new pipeline to add query cache operator
1392
46.3k
            PipelinePtr new_pipe;
1393
46.3k
            if (need_create_cache_op) {
1394
3.16k
                RETURN_IF_ERROR(create_query_cache_operator(new_pipe));
1395
3.16k
                cache_op = op;
1396
3.16k
            }
1397
1398
46.3k
            if (enable_spill) {
1399
2
                op = std::make_shared<PartitionedAggSourceOperatorX>(pool, tnode,
1400
2
                                                                     next_operator_id(), descs);
1401
46.3k
            } else {
1402
46.3k
                op = std::make_shared<AggSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1403
46.3k
            }
1404
46.3k
            if (need_create_cache_op) {
1405
3.16k
                RETURN_IF_ERROR(cur_pipe->operators().front()->set_child(op));
1406
3.16k
                RETURN_IF_ERROR(new_pipe->add_operator(op, _parallel_instances));
1407
3.16k
                cur_pipe = new_pipe;
1408
43.2k
            } else {
1409
43.2k
                RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1410
43.2k
            }
1411
1412
46.3k
            const auto downstream_pipeline_id = cur_pipe->id();
1413
46.3k
            if (!_dag.contains(downstream_pipeline_id)) {
1414
45.5k
                _dag.insert({downstream_pipeline_id, {}});
1415
45.5k
            }
1416
46.3k
            cur_pipe = add_pipeline(cur_pipe);
1417
46.3k
            _dag[downstream_pipeline_id].push_back(cur_pipe->id());
1418
1419
46.3k
            if (enable_spill) {
1420
2
                sink_ops.push_back(std::make_shared<PartitionedAggSinkOperatorX>(
1421
2
                        pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1422
46.3k
            } else {
1423
46.3k
                sink_ops.push_back(std::make_shared<AggSinkOperatorX>(
1424
46.3k
                        pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1425
46.3k
            }
1426
46.3k
            RETURN_IF_ERROR(cur_pipe->set_sink(sink_ops.back()));
1427
46.3k
            RETURN_IF_ERROR(cur_pipe->sink()->init(tnode, _runtime_state.get()));
1428
46.3k
        }
1429
146k
        break;
1430
146k
    }
1431
146k
    case TPlanNodeType::HASH_JOIN_NODE: {
1432
7.14k
        const auto is_broadcast_join = tnode.hash_join_node.__isset.is_broadcast_join &&
1433
7.14k
                                       tnode.hash_join_node.is_broadcast_join;
1434
7.14k
        const auto enable_spill = _runtime_state->enable_spill();
1435
7.14k
        if (enable_spill && !is_broadcast_join) {
1436
0
            auto tnode_ = tnode;
1437
0
            tnode_.runtime_filters.clear();
1438
0
            auto inner_probe_operator =
1439
0
                    std::make_shared<HashJoinProbeOperatorX>(pool, tnode_, 0, descs);
1440
1441
            // probe side inner sink operator is used to build hash table on probe side when data is spilled.
1442
            // So here use `tnode_` which has no runtime filters.
1443
0
            auto probe_side_inner_sink_operator =
1444
0
                    std::make_shared<HashJoinBuildSinkOperatorX>(pool, 0, 0, tnode_, descs);
1445
1446
0
            RETURN_IF_ERROR(inner_probe_operator->init(tnode_, _runtime_state.get()));
1447
0
            RETURN_IF_ERROR(probe_side_inner_sink_operator->init(tnode_, _runtime_state.get()));
1448
1449
0
            auto probe_operator = std::make_shared<PartitionedHashJoinProbeOperatorX>(
1450
0
                    pool, tnode_, next_operator_id(), descs);
1451
0
            probe_operator->set_inner_operators(probe_side_inner_sink_operator,
1452
0
                                                inner_probe_operator);
1453
0
            op = std::move(probe_operator);
1454
0
            RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1455
1456
0
            const auto downstream_pipeline_id = cur_pipe->id();
1457
0
            if (!_dag.contains(downstream_pipeline_id)) {
1458
0
                _dag.insert({downstream_pipeline_id, {}});
1459
0
            }
1460
0
            PipelinePtr build_side_pipe = add_pipeline(cur_pipe);
1461
0
            _dag[downstream_pipeline_id].push_back(build_side_pipe->id());
1462
1463
0
            auto inner_sink_operator =
1464
0
                    std::make_shared<HashJoinBuildSinkOperatorX>(pool, 0, 0, tnode, descs);
1465
0
            auto sink_operator = std::make_shared<PartitionedHashJoinSinkOperatorX>(
1466
0
                    pool, next_sink_operator_id(), op->operator_id(), tnode_, descs);
1467
0
            RETURN_IF_ERROR(inner_sink_operator->init(tnode, _runtime_state.get()));
1468
1469
0
            sink_operator->set_inner_operators(inner_sink_operator, inner_probe_operator);
1470
0
            sink_ops.push_back(std::move(sink_operator));
1471
0
            RETURN_IF_ERROR(build_side_pipe->set_sink(sink_ops.back()));
1472
0
            RETURN_IF_ERROR(build_side_pipe->sink()->init(tnode_, _runtime_state.get()));
1473
1474
0
            _pipeline_parent_map.push(op->node_id(), cur_pipe);
1475
0
            _pipeline_parent_map.push(op->node_id(), build_side_pipe);
1476
7.14k
        } else {
1477
7.14k
            op = std::make_shared<HashJoinProbeOperatorX>(pool, tnode, next_operator_id(), descs);
1478
7.14k
            RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1479
1480
7.14k
            const auto downstream_pipeline_id = cur_pipe->id();
1481
7.14k
            if (!_dag.contains(downstream_pipeline_id)) {
1482
6.32k
                _dag.insert({downstream_pipeline_id, {}});
1483
6.32k
            }
1484
7.14k
            PipelinePtr build_side_pipe = add_pipeline(cur_pipe);
1485
7.14k
            _dag[downstream_pipeline_id].push_back(build_side_pipe->id());
1486
1487
7.14k
            sink_ops.push_back(std::make_shared<HashJoinBuildSinkOperatorX>(
1488
7.14k
                    pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1489
7.14k
            RETURN_IF_ERROR(build_side_pipe->set_sink(sink_ops.back()));
1490
7.14k
            RETURN_IF_ERROR(build_side_pipe->sink()->init(tnode, _runtime_state.get()));
1491
1492
7.14k
            _pipeline_parent_map.push(op->node_id(), cur_pipe);
1493
7.14k
            _pipeline_parent_map.push(op->node_id(), build_side_pipe);
1494
7.14k
        }
1495
7.14k
        if (is_broadcast_join && _runtime_state->enable_share_hash_table_for_broadcast_join()) {
1496
2.38k
            std::shared_ptr<HashJoinSharedState> shared_state =
1497
2.38k
                    HashJoinSharedState::create_shared(_num_instances);
1498
15.6k
            for (int i = 0; i < _num_instances; i++) {
1499
13.2k
                auto sink_dep = std::make_shared<Dependency>(op->operator_id(), op->node_id(),
1500
13.2k
                                                             "HASH_JOIN_BUILD_DEPENDENCY");
1501
13.2k
                sink_dep->set_shared_state(shared_state.get());
1502
13.2k
                shared_state->sink_deps.push_back(sink_dep);
1503
13.2k
            }
1504
2.38k
            shared_state->create_source_dependencies(_num_instances, op->operator_id(),
1505
2.38k
                                                     op->node_id(), "HASH_JOIN_PROBE");
1506
2.38k
            _op_id_to_shared_state.insert(
1507
2.38k
                    {op->operator_id(), {shared_state, shared_state->sink_deps}});
1508
2.38k
        }
1509
7.14k
        break;
1510
7.14k
    }
1511
1.67k
    case TPlanNodeType::CROSS_JOIN_NODE: {
1512
1.67k
        op = std::make_shared<NestedLoopJoinProbeOperatorX>(pool, tnode, next_operator_id(), descs);
1513
1.67k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1514
1515
1.67k
        const auto downstream_pipeline_id = cur_pipe->id();
1516
1.67k
        if (!_dag.contains(downstream_pipeline_id)) {
1517
1.42k
            _dag.insert({downstream_pipeline_id, {}});
1518
1.42k
        }
1519
1.67k
        PipelinePtr build_side_pipe = add_pipeline(cur_pipe);
1520
1.67k
        _dag[downstream_pipeline_id].push_back(build_side_pipe->id());
1521
1522
1.67k
        sink_ops.push_back(std::make_shared<NestedLoopJoinBuildSinkOperatorX>(
1523
1.67k
                pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1524
1.67k
        RETURN_IF_ERROR(build_side_pipe->set_sink(sink_ops.back()));
1525
1.67k
        RETURN_IF_ERROR(build_side_pipe->sink()->init(tnode, _runtime_state.get()));
1526
1.67k
        _pipeline_parent_map.push(op->node_id(), cur_pipe);
1527
1.67k
        _pipeline_parent_map.push(op->node_id(), build_side_pipe);
1528
1.67k
        break;
1529
1.67k
    }
1530
49.3k
    case TPlanNodeType::UNION_NODE: {
1531
49.3k
        int child_count = tnode.num_children;
1532
49.3k
        op = std::make_shared<UnionSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1533
49.3k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1534
1535
49.3k
        const auto downstream_pipeline_id = cur_pipe->id();
1536
49.3k
        if (!_dag.contains(downstream_pipeline_id)) {
1537
49.1k
            _dag.insert({downstream_pipeline_id, {}});
1538
49.1k
        }
1539
50.4k
        for (int i = 0; i < child_count; i++) {
1540
1.12k
            PipelinePtr build_side_pipe = add_pipeline(cur_pipe);
1541
1.12k
            _dag[downstream_pipeline_id].push_back(build_side_pipe->id());
1542
1.12k
            sink_ops.push_back(std::make_shared<UnionSinkOperatorX>(
1543
1.12k
                    i, next_sink_operator_id(), op->operator_id(), pool, tnode, descs));
1544
1.12k
            RETURN_IF_ERROR(build_side_pipe->set_sink(sink_ops.back()));
1545
1.12k
            RETURN_IF_ERROR(build_side_pipe->sink()->init(tnode, _runtime_state.get()));
1546
            // preset children pipelines. if any pipeline found this as its father, will use the prepared pipeline to build.
1547
1.12k
            _pipeline_parent_map.push(op->node_id(), build_side_pipe);
1548
1.12k
        }
1549
49.3k
        break;
1550
49.3k
    }
1551
49.3k
    case TPlanNodeType::SORT_NODE: {
1552
33.6k
        const auto should_spill = _runtime_state->enable_spill() &&
1553
33.6k
                                  tnode.sort_node.algorithm == TSortAlgorithm::FULL_SORT;
1554
33.6k
        const bool use_local_merge =
1555
33.6k
                tnode.sort_node.__isset.use_local_merge && tnode.sort_node.use_local_merge;
1556
33.6k
        if (should_spill) {
1557
7
            op = std::make_shared<SpillSortSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1558
33.5k
        } else if (use_local_merge) {
1559
28.9k
            op = std::make_shared<LocalMergeSortSourceOperatorX>(pool, tnode, next_operator_id(),
1560
28.9k
                                                                 descs);
1561
28.9k
        } else {
1562
4.66k
            op = std::make_shared<SortSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1563
4.66k
        }
1564
33.6k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1565
1566
33.6k
        const auto downstream_pipeline_id = cur_pipe->id();
1567
33.6k
        if (!_dag.contains(downstream_pipeline_id)) {
1568
33.5k
            _dag.insert({downstream_pipeline_id, {}});
1569
33.5k
        }
1570
33.6k
        cur_pipe = add_pipeline(cur_pipe);
1571
33.6k
        _dag[downstream_pipeline_id].push_back(cur_pipe->id());
1572
1573
33.6k
        if (should_spill) {
1574
7
            sink_ops.push_back(std::make_shared<SpillSortSinkOperatorX>(
1575
7
                    pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1576
33.5k
        } else {
1577
33.5k
            sink_ops.push_back(std::make_shared<SortSinkOperatorX>(
1578
33.5k
                    pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1579
33.5k
        }
1580
33.6k
        RETURN_IF_ERROR(cur_pipe->set_sink(sink_ops.back()));
1581
33.6k
        RETURN_IF_ERROR(cur_pipe->sink()->init(tnode, _runtime_state.get()));
1582
33.6k
        break;
1583
33.6k
    }
1584
33.6k
    case TPlanNodeType::PARTITION_SORT_NODE: {
1585
65
        op = std::make_shared<PartitionSortSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1586
65
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1587
1588
65
        const auto downstream_pipeline_id = cur_pipe->id();
1589
65
        if (!_dag.contains(downstream_pipeline_id)) {
1590
65
            _dag.insert({downstream_pipeline_id, {}});
1591
65
        }
1592
65
        cur_pipe = add_pipeline(cur_pipe);
1593
65
        _dag[downstream_pipeline_id].push_back(cur_pipe->id());
1594
1595
65
        sink_ops.push_back(std::make_shared<PartitionSortSinkOperatorX>(
1596
65
                pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1597
65
        RETURN_IF_ERROR(cur_pipe->set_sink(sink_ops.back()));
1598
65
        RETURN_IF_ERROR(cur_pipe->sink()->init(tnode, _runtime_state.get()));
1599
65
        break;
1600
65
    }
1601
1.76k
    case TPlanNodeType::ANALYTIC_EVAL_NODE: {
1602
1.76k
        op = std::make_shared<AnalyticSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1603
1.76k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1604
1605
1.76k
        const auto downstream_pipeline_id = cur_pipe->id();
1606
1.76k
        if (!_dag.contains(downstream_pipeline_id)) {
1607
1.75k
            _dag.insert({downstream_pipeline_id, {}});
1608
1.75k
        }
1609
1.76k
        cur_pipe = add_pipeline(cur_pipe);
1610
1.76k
        _dag[downstream_pipeline_id].push_back(cur_pipe->id());
1611
1612
1.76k
        sink_ops.push_back(std::make_shared<AnalyticSinkOperatorX>(
1613
1.76k
                pool, next_sink_operator_id(), op->operator_id(), tnode, descs));
1614
1.76k
        RETURN_IF_ERROR(cur_pipe->set_sink(sink_ops.back()));
1615
1.76k
        RETURN_IF_ERROR(cur_pipe->sink()->init(tnode, _runtime_state.get()));
1616
1.76k
        break;
1617
1.76k
    }
1618
1.76k
    case TPlanNodeType::MATERIALIZATION_NODE: {
1619
669
        op = std::make_shared<MaterializationOperator>(pool, tnode, next_operator_id(), descs);
1620
669
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1621
669
        break;
1622
669
    }
1623
669
    case TPlanNodeType::INTERSECT_NODE: {
1624
119
        RETURN_IF_ERROR(_build_operators_for_set_operation_node<true>(pool, tnode, descs, op,
1625
119
                                                                      cur_pipe, sink_ops));
1626
119
        break;
1627
119
    }
1628
129
    case TPlanNodeType::EXCEPT_NODE: {
1629
129
        RETURN_IF_ERROR(_build_operators_for_set_operation_node<false>(pool, tnode, descs, op,
1630
129
                                                                       cur_pipe, sink_ops));
1631
129
        break;
1632
129
    }
1633
329
    case TPlanNodeType::REPEAT_NODE: {
1634
329
        op = std::make_shared<RepeatOperatorX>(pool, tnode, next_operator_id(), descs);
1635
329
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1636
329
        break;
1637
329
    }
1638
867
    case TPlanNodeType::TABLE_FUNCTION_NODE: {
1639
867
        op = std::make_shared<TableFunctionOperatorX>(pool, tnode, next_operator_id(), descs);
1640
867
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1641
867
        break;
1642
867
    }
1643
867
    case TPlanNodeType::ASSERT_NUM_ROWS_NODE: {
1644
18
        op = std::make_shared<AssertNumRowsOperatorX>(pool, tnode, next_operator_id(), descs);
1645
18
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1646
18
        break;
1647
18
    }
1648
1.55k
    case TPlanNodeType::EMPTY_SET_NODE: {
1649
1.55k
        op = std::make_shared<EmptySetSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1650
1.55k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1651
1.55k
        break;
1652
1.55k
    }
1653
1.55k
    case TPlanNodeType::DATA_GEN_SCAN_NODE: {
1654
265
        op = std::make_shared<DataGenSourceOperatorX>(pool, tnode, next_operator_id(), descs);
1655
265
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1656
265
        fe_with_old_version = !tnode.__isset.is_serial_operator;
1657
265
        break;
1658
265
    }
1659
1.53k
    case TPlanNodeType::SCHEMA_SCAN_NODE: {
1660
1.53k
        op = std::make_shared<SchemaScanOperatorX>(pool, tnode, next_operator_id(), descs);
1661
1.53k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1662
1.53k
        break;
1663
1.53k
    }
1664
5.36k
    case TPlanNodeType::META_SCAN_NODE: {
1665
5.36k
        op = std::make_shared<MetaScanOperatorX>(pool, tnode, next_operator_id(), descs);
1666
5.36k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1667
5.36k
        break;
1668
5.36k
    }
1669
5.36k
    case TPlanNodeType::SELECT_NODE: {
1670
267
        op = std::make_shared<SelectOperatorX>(pool, tnode, next_operator_id(), descs);
1671
267
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1672
267
        break;
1673
267
    }
1674
267
    case TPlanNodeType::REC_CTE_NODE: {
1675
150
        op = std::make_shared<RecCTESourceOperatorX>(pool, tnode, next_operator_id(), descs);
1676
150
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1677
1678
150
        const auto downstream_pipeline_id = cur_pipe->id();
1679
150
        if (!_dag.contains(downstream_pipeline_id)) {
1680
147
            _dag.insert({downstream_pipeline_id, {}});
1681
147
        }
1682
1683
150
        PipelinePtr anchor_side_pipe = add_pipeline(cur_pipe);
1684
150
        _dag[downstream_pipeline_id].push_back(anchor_side_pipe->id());
1685
1686
150
        DataSinkOperatorPtr anchor_sink;
1687
150
        anchor_sink = std::make_shared<RecCTEAnchorSinkOperatorX>(next_sink_operator_id(),
1688
150
                                                                  op->operator_id(), tnode, descs);
1689
150
        RETURN_IF_ERROR(anchor_side_pipe->set_sink(anchor_sink));
1690
150
        RETURN_IF_ERROR(anchor_side_pipe->sink()->init(tnode, _runtime_state.get()));
1691
150
        _pipeline_parent_map.push(op->node_id(), anchor_side_pipe);
1692
1693
150
        PipelinePtr rec_side_pipe = add_pipeline(cur_pipe);
1694
150
        _dag[downstream_pipeline_id].push_back(rec_side_pipe->id());
1695
1696
150
        DataSinkOperatorPtr rec_sink;
1697
150
        rec_sink = std::make_shared<RecCTESinkOperatorX>(next_sink_operator_id(), op->operator_id(),
1698
150
                                                         tnode, descs);
1699
150
        RETURN_IF_ERROR(rec_side_pipe->set_sink(rec_sink));
1700
150
        RETURN_IF_ERROR(rec_side_pipe->sink()->init(tnode, _runtime_state.get()));
1701
150
        _pipeline_parent_map.push(op->node_id(), rec_side_pipe);
1702
1703
150
        break;
1704
150
    }
1705
1.85k
    case TPlanNodeType::REC_CTE_SCAN_NODE: {
1706
1.85k
        op = std::make_shared<RecCTEScanOperatorX>(pool, tnode, next_operator_id(), descs);
1707
1.85k
        RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1708
1.85k
        break;
1709
1.85k
    }
1710
1.85k
    default:
1711
0
        return Status::InternalError("Unsupported exec type in pipeline: {}",
1712
0
                                     print_plan_node_type(tnode.node_type));
1713
544k
    }
1714
542k
    if (_params.__isset.parallel_instances && fe_with_old_version) {
1715
0
        cur_pipe->set_num_tasks(_params.parallel_instances);
1716
0
        op->set_serial_operator();
1717
0
    }
1718
1719
542k
    return Status::OK();
1720
544k
}
1721
// NOLINTEND(readability-function-cognitive-complexity)
1722
// NOLINTEND(readability-function-size)
1723
1724
template <bool is_intersect>
1725
Status PipelineFragmentContext::_build_operators_for_set_operation_node(
1726
        ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs, OperatorPtr& op,
1727
248
        PipelinePtr& cur_pipe, std::vector<DataSinkOperatorPtr>& sink_ops) {
1728
248
    op.reset(new SetSourceOperatorX<is_intersect>(pool, tnode, next_operator_id(), descs));
1729
248
    RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1730
1731
248
    const auto downstream_pipeline_id = cur_pipe->id();
1732
248
    if (!_dag.contains(downstream_pipeline_id)) {
1733
231
        _dag.insert({downstream_pipeline_id, {}});
1734
231
    }
1735
1736
837
    for (int child_id = 0; child_id < tnode.num_children; child_id++) {
1737
589
        PipelinePtr probe_side_pipe = add_pipeline(cur_pipe);
1738
589
        _dag[downstream_pipeline_id].push_back(probe_side_pipe->id());
1739
1740
589
        if (child_id == 0) {
1741
248
            sink_ops.push_back(std::make_shared<SetSinkOperatorX<is_intersect>>(
1742
248
                    child_id, next_sink_operator_id(), op->operator_id(), pool, tnode, descs));
1743
341
        } else {
1744
341
            sink_ops.push_back(std::make_shared<SetProbeSinkOperatorX<is_intersect>>(
1745
341
                    child_id, next_sink_operator_id(), op->operator_id(), pool, tnode, descs));
1746
341
        }
1747
589
        RETURN_IF_ERROR(probe_side_pipe->set_sink(sink_ops.back()));
1748
589
        RETURN_IF_ERROR(probe_side_pipe->sink()->init(tnode, _runtime_state.get()));
1749
        // prepare children pipelines. if any pipeline found this as its father, will use the prepared pipeline to build.
1750
589
        _pipeline_parent_map.push(op->node_id(), probe_side_pipe);
1751
589
    }
1752
1753
248
    return Status::OK();
1754
248
}
_ZN5doris23PipelineFragmentContext39_build_operators_for_set_operation_nodeILb1EEENS_6StatusEPNS_10ObjectPoolERKNS_9TPlanNodeERKNS_13DescriptorTblERSt10shared_ptrINS_13OperatorXBaseEERSB_INS_8PipelineEERSt6vectorISB_INS_21DataSinkOperatorXBaseEESaISK_EE
Line
Count
Source
1727
119
        PipelinePtr& cur_pipe, std::vector<DataSinkOperatorPtr>& sink_ops) {
1728
119
    op.reset(new SetSourceOperatorX<is_intersect>(pool, tnode, next_operator_id(), descs));
1729
119
    RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1730
1731
119
    const auto downstream_pipeline_id = cur_pipe->id();
1732
119
    if (!_dag.contains(downstream_pipeline_id)) {
1733
110
        _dag.insert({downstream_pipeline_id, {}});
1734
110
    }
1735
1736
435
    for (int child_id = 0; child_id < tnode.num_children; child_id++) {
1737
316
        PipelinePtr probe_side_pipe = add_pipeline(cur_pipe);
1738
316
        _dag[downstream_pipeline_id].push_back(probe_side_pipe->id());
1739
1740
316
        if (child_id == 0) {
1741
119
            sink_ops.push_back(std::make_shared<SetSinkOperatorX<is_intersect>>(
1742
119
                    child_id, next_sink_operator_id(), op->operator_id(), pool, tnode, descs));
1743
197
        } else {
1744
197
            sink_ops.push_back(std::make_shared<SetProbeSinkOperatorX<is_intersect>>(
1745
197
                    child_id, next_sink_operator_id(), op->operator_id(), pool, tnode, descs));
1746
197
        }
1747
316
        RETURN_IF_ERROR(probe_side_pipe->set_sink(sink_ops.back()));
1748
316
        RETURN_IF_ERROR(probe_side_pipe->sink()->init(tnode, _runtime_state.get()));
1749
        // prepare children pipelines. if any pipeline found this as its father, will use the prepared pipeline to build.
1750
316
        _pipeline_parent_map.push(op->node_id(), probe_side_pipe);
1751
316
    }
1752
1753
119
    return Status::OK();
1754
119
}
_ZN5doris23PipelineFragmentContext39_build_operators_for_set_operation_nodeILb0EEENS_6StatusEPNS_10ObjectPoolERKNS_9TPlanNodeERKNS_13DescriptorTblERSt10shared_ptrINS_13OperatorXBaseEERSB_INS_8PipelineEERSt6vectorISB_INS_21DataSinkOperatorXBaseEESaISK_EE
Line
Count
Source
1727
129
        PipelinePtr& cur_pipe, std::vector<DataSinkOperatorPtr>& sink_ops) {
1728
129
    op.reset(new SetSourceOperatorX<is_intersect>(pool, tnode, next_operator_id(), descs));
1729
129
    RETURN_IF_ERROR(cur_pipe->add_operator(op, _parallel_instances));
1730
1731
129
    const auto downstream_pipeline_id = cur_pipe->id();
1732
129
    if (!_dag.contains(downstream_pipeline_id)) {
1733
121
        _dag.insert({downstream_pipeline_id, {}});
1734
121
    }
1735
1736
402
    for (int child_id = 0; child_id < tnode.num_children; child_id++) {
1737
273
        PipelinePtr probe_side_pipe = add_pipeline(cur_pipe);
1738
273
        _dag[downstream_pipeline_id].push_back(probe_side_pipe->id());
1739
1740
273
        if (child_id == 0) {
1741
129
            sink_ops.push_back(std::make_shared<SetSinkOperatorX<is_intersect>>(
1742
129
                    child_id, next_sink_operator_id(), op->operator_id(), pool, tnode, descs));
1743
144
        } else {
1744
144
            sink_ops.push_back(std::make_shared<SetProbeSinkOperatorX<is_intersect>>(
1745
144
                    child_id, next_sink_operator_id(), op->operator_id(), pool, tnode, descs));
1746
144
        }
1747
273
        RETURN_IF_ERROR(probe_side_pipe->set_sink(sink_ops.back()));
1748
273
        RETURN_IF_ERROR(probe_side_pipe->sink()->init(tnode, _runtime_state.get()));
1749
        // prepare children pipelines. if any pipeline found this as its father, will use the prepared pipeline to build.
1750
273
        _pipeline_parent_map.push(op->node_id(), probe_side_pipe);
1751
273
    }
1752
1753
129
    return Status::OK();
1754
129
}
1755
1756
338k
Status PipelineFragmentContext::submit() {
1757
338k
    if (_submitted) {
1758
0
        return Status::InternalError("submitted");
1759
0
    }
1760
338k
    _submitted = true;
1761
1762
338k
    int submit_tasks = 0;
1763
338k
    Status st;
1764
338k
    auto* scheduler = _query_ctx->get_pipe_exec_scheduler();
1765
878k
    for (auto& task : _tasks) {
1766
1.63M
        for (auto& t : task) {
1767
1.63M
            st = scheduler->submit(t.first);
1768
1.63M
            DBUG_EXECUTE_IF("PipelineFragmentContext.submit.failed",
1769
1.63M
                            { st = Status::Aborted("PipelineFragmentContext.submit.failed"); });
1770
1.63M
            if (!st) {
1771
0
                cancel(Status::InternalError("submit context to executor fail"));
1772
0
                std::lock_guard<std::mutex> l(_task_mutex);
1773
0
                _total_tasks = submit_tasks;
1774
0
                break;
1775
0
            }
1776
1.63M
            submit_tasks++;
1777
1.63M
        }
1778
878k
    }
1779
338k
    if (!st.ok()) {
1780
0
        std::lock_guard<std::mutex> l(_task_mutex);
1781
0
        if (_closed_tasks >= _total_tasks) {
1782
0
            _close_fragment_instance();
1783
0
        }
1784
0
        return Status::InternalError("Submit pipeline failed. err = {}, BE: {}", st.to_string(),
1785
0
                                     BackendOptions::get_localhost());
1786
338k
    } else {
1787
338k
        return st;
1788
338k
    }
1789
338k
}
1790
1791
0
void PipelineFragmentContext::print_profile(const std::string& extra_info) {
1792
0
    if (_runtime_state->enable_profile()) {
1793
0
        std::stringstream ss;
1794
0
        for (auto runtime_profile_ptr : _runtime_state->pipeline_id_to_profile()) {
1795
0
            runtime_profile_ptr->pretty_print(&ss);
1796
0
        }
1797
1798
0
        if (_runtime_state->load_channel_profile()) {
1799
0
            _runtime_state->load_channel_profile()->pretty_print(&ss);
1800
0
        }
1801
1802
0
        auto profile_str =
1803
0
                fmt::format("Query {} fragment {} {}, profile, {}", print_id(this->_query_id),
1804
0
                            this->_fragment_id, extra_info, ss.str());
1805
0
        LOG_LONG_STRING(INFO, profile_str);
1806
0
    }
1807
0
}
1808
// If all pipeline tasks binded to the fragment instance are finished, then we could
1809
// close the fragment instance.
1810
339k
void PipelineFragmentContext::_close_fragment_instance() {
1811
339k
    if (_is_fragment_instance_closed) {
1812
0
        return;
1813
0
    }
1814
339k
    Defer defer_op {[&]() {
1815
339k
        _is_fragment_instance_closed = true;
1816
339k
        _notify_cv.notify_all();
1817
339k
    }};
1818
339k
    _fragment_level_profile->total_time_counter()->update(_fragment_watcher.elapsed_time());
1819
339k
    if (!_need_notify_close) {
1820
336k
        auto st = send_report(true);
1821
336k
        if (!st) {
1822
299k
            LOG(WARNING) << fmt::format("Failed to send report for query {}, fragment {}: {}",
1823
299k
                                        print_id(_query_id), _fragment_id, st.to_string());
1824
299k
        }
1825
336k
    }
1826
    // Print profile content in info log is a tempoeray solution for stream load and external_connector.
1827
    // Since stream load does not have someting like coordinator on FE, so
1828
    // backend can not report profile to FE, ant its profile can not be shown
1829
    // in the same way with other query. So we print the profile content to info log.
1830
1831
339k
    if (_runtime_state->enable_profile() &&
1832
339k
        (_query_ctx->get_query_source() == QuerySource::STREAM_LOAD ||
1833
2.28k
         _query_ctx->get_query_source() == QuerySource::EXTERNAL_CONNECTOR ||
1834
2.28k
         _query_ctx->get_query_source() == QuerySource::GROUP_COMMIT_LOAD)) {
1835
0
        std::stringstream ss;
1836
        // Compute the _local_time_percent before pretty_print the runtime_profile
1837
        // Before add this operation, the print out like that:
1838
        // UNION_NODE (id=0):(Active: 56.720us, non-child: 00.00%)
1839
        // After add the operation, the print out like that:
1840
        // UNION_NODE (id=0):(Active: 56.720us, non-child: 82.53%)
1841
        // We can easily know the exec node execute time without child time consumed.
1842
0
        for (auto runtime_profile_ptr : _runtime_state->pipeline_id_to_profile()) {
1843
0
            runtime_profile_ptr->pretty_print(&ss);
1844
0
        }
1845
1846
0
        if (_runtime_state->load_channel_profile()) {
1847
0
            _runtime_state->load_channel_profile()->pretty_print(&ss);
1848
0
        }
1849
1850
0
        LOG_INFO("Query {} fragment {} profile:\n {}", print_id(_query_id), _fragment_id, ss.str());
1851
0
    }
1852
1853
339k
    if (_query_ctx->enable_profile()) {
1854
2.28k
        _query_ctx->add_fragment_profile(_fragment_id, collect_realtime_profile(),
1855
2.28k
                                         collect_realtime_load_channel_profile());
1856
2.28k
    }
1857
1858
339k
    if (!_need_notify_close) {
1859
        // all submitted tasks done
1860
336k
        _exec_env->fragment_mgr()->remove_pipeline_context({_query_id, _fragment_id});
1861
336k
    }
1862
339k
}
1863
1864
1.62M
void PipelineFragmentContext::decrement_running_task(PipelineId pipeline_id) {
1865
    // If all tasks of this pipeline has been closed, upstream tasks is never needed, and we just make those runnable here
1866
1.62M
    DCHECK(_pip_id_to_pipeline.contains(pipeline_id));
1867
1.62M
    if (_pip_id_to_pipeline[pipeline_id]->close_task()) {
1868
537k
        if (_dag.contains(pipeline_id)) {
1869
273k
            for (auto dep : _dag[pipeline_id]) {
1870
273k
                _pip_id_to_pipeline[dep]->make_all_runnable(pipeline_id);
1871
273k
            }
1872
240k
        }
1873
537k
    }
1874
1.62M
    std::lock_guard<std::mutex> l(_task_mutex);
1875
1.62M
    ++_closed_tasks;
1876
1.62M
    if (_closed_tasks >= _total_tasks) {
1877
339k
        _close_fragment_instance();
1878
339k
    }
1879
1.62M
}
1880
1881
47.4k
std::string PipelineFragmentContext::get_load_error_url() {
1882
47.4k
    if (const auto& str = _runtime_state->get_error_log_file_path(); !str.empty()) {
1883
0
        return to_load_error_http_path(str);
1884
0
    }
1885
140k
    for (auto& tasks : _tasks) {
1886
243k
        for (auto& task : tasks) {
1887
243k
            if (const auto& str = task.second->get_error_log_file_path(); !str.empty()) {
1888
153
                return to_load_error_http_path(str);
1889
153
            }
1890
243k
        }
1891
140k
    }
1892
47.2k
    return "";
1893
47.4k
}
1894
1895
47.4k
std::string PipelineFragmentContext::get_first_error_msg() {
1896
47.4k
    if (const auto& str = _runtime_state->get_first_error_msg(); !str.empty()) {
1897
0
        return str;
1898
0
    }
1899
140k
    for (auto& tasks : _tasks) {
1900
243k
        for (auto& task : tasks) {
1901
243k
            if (const auto& str = task.second->get_first_error_msg(); !str.empty()) {
1902
153
                return str;
1903
153
            }
1904
243k
        }
1905
140k
    }
1906
47.2k
    return "";
1907
47.4k
}
1908
1909
340k
Status PipelineFragmentContext::send_report(bool done) {
1910
340k
    Status exec_status = _query_ctx->exec_status();
1911
    // If plan is done successfully, but _is_report_success is false,
1912
    // no need to send report.
1913
    // Load will set _is_report_success to true because load wants to know
1914
    // the process.
1915
340k
    if (!_is_report_success && done && exec_status.ok()) {
1916
300k
        return Status::NeedSendAgain("");
1917
300k
    }
1918
1919
    // If both _is_report_success and _is_report_on_cancel are false,
1920
    // which means no matter query is success or failed, no report is needed.
1921
    // This may happen when the query limit reached and
1922
    // a internal cancellation being processed
1923
    // When limit is reached the fragment is also cancelled, but _is_report_on_cancel will
1924
    // be set to false, to avoid sending fault report to FE.
1925
40.5k
    if (!_is_report_success && !_is_report_on_cancel) {
1926
56
        return Status::NeedSendAgain("");
1927
56
    }
1928
1929
40.5k
    std::vector<RuntimeState*> runtime_states;
1930
1931
118k
    for (auto& tasks : _tasks) {
1932
199k
        for (auto& task : tasks) {
1933
199k
            runtime_states.push_back(task.second.get());
1934
199k
        }
1935
118k
    }
1936
1937
40.5k
    std::string load_eror_url = _query_ctx->get_load_error_url().empty()
1938
40.5k
                                        ? get_load_error_url()
1939
18.4E
                                        : _query_ctx->get_load_error_url();
1940
40.5k
    std::string first_error_msg = _query_ctx->get_first_error_msg().empty()
1941
40.5k
                                          ? get_first_error_msg()
1942
18.4E
                                          : _query_ctx->get_first_error_msg();
1943
1944
40.5k
    ReportStatusRequest req {.status = exec_status,
1945
40.5k
                             .runtime_states = runtime_states,
1946
40.5k
                             .done = done || !exec_status.ok(),
1947
40.5k
                             .coord_addr = _query_ctx->coord_addr,
1948
40.5k
                             .query_id = _query_id,
1949
40.5k
                             .fragment_id = _fragment_id,
1950
40.5k
                             .fragment_instance_id = TUniqueId(),
1951
40.5k
                             .backend_num = -1,
1952
40.5k
                             .runtime_state = _runtime_state.get(),
1953
40.5k
                             .load_error_url = load_eror_url,
1954
40.5k
                             .first_error_msg = first_error_msg,
1955
40.5k
                             .cancel_fn = [this](const Status& reason) { cancel(reason); }};
1956
1957
40.5k
    return _report_status_cb(
1958
40.5k
            req, std::dynamic_pointer_cast<PipelineFragmentContext>(shared_from_this()));
1959
40.5k
}
1960
1961
0
size_t PipelineFragmentContext::get_revocable_size(bool* has_running_task) const {
1962
0
    size_t res = 0;
1963
    // _tasks will be cleared during ~PipelineFragmentContext, so that it's safe
1964
    // here to traverse the vector.
1965
0
    for (const auto& task_instances : _tasks) {
1966
0
        for (const auto& task : task_instances) {
1967
0
            if (task.first->is_running()) {
1968
0
                LOG_EVERY_N(INFO, 50) << "Query: " << print_id(_query_id)
1969
0
                                      << " is running, task: " << (void*)task.first.get()
1970
0
                                      << ", is_running: " << task.first->is_running();
1971
0
                *has_running_task = true;
1972
0
                return 0;
1973
0
            }
1974
1975
0
            size_t revocable_size = task.first->get_revocable_size();
1976
0
            if (revocable_size >= SpillFile::MIN_SPILL_WRITE_BATCH_MEM) {
1977
0
                res += revocable_size;
1978
0
            }
1979
0
        }
1980
0
    }
1981
0
    return res;
1982
0
}
1983
1984
0
std::vector<PipelineTask*> PipelineFragmentContext::get_revocable_tasks() const {
1985
0
    std::vector<PipelineTask*> revocable_tasks;
1986
0
    for (const auto& task_instances : _tasks) {
1987
0
        for (const auto& task : task_instances) {
1988
0
            size_t revocable_size_ = task.first->get_revocable_size();
1989
1990
0
            if (revocable_size_ >= SpillFile::MIN_SPILL_WRITE_BATCH_MEM) {
1991
0
                revocable_tasks.emplace_back(task.first.get());
1992
0
            }
1993
0
        }
1994
0
    }
1995
0
    return revocable_tasks;
1996
0
}
1997
1998
1.46k
std::string PipelineFragmentContext::debug_string() {
1999
1.46k
    std::lock_guard<std::mutex> l(_task_mutex);
2000
1.46k
    fmt::memory_buffer debug_string_buffer;
2001
1.46k
    fmt::format_to(debug_string_buffer,
2002
1.46k
                   "PipelineFragmentContext Info: _closed_tasks={}, _total_tasks={}, "
2003
1.46k
                   "need_notify_close={}, has_task_execution_ctx_ref_count={}\n",
2004
1.46k
                   _closed_tasks, _total_tasks, _need_notify_close,
2005
1.46k
                   _has_task_execution_ctx_ref_count);
2006
3.61k
    for (size_t j = 0; j < _tasks.size(); j++) {
2007
2.14k
        fmt::format_to(debug_string_buffer, "Tasks in instance {}:\n", j);
2008
5.04k
        for (size_t i = 0; i < _tasks[j].size(); i++) {
2009
2.89k
            fmt::format_to(debug_string_buffer, "Task {}: {}\n", i,
2010
2.89k
                           _tasks[j][i].first->debug_string());
2011
2.89k
        }
2012
2.14k
    }
2013
2014
1.46k
    return fmt::to_string(debug_string_buffer);
2015
1.46k
}
2016
2017
std::vector<std::shared_ptr<TRuntimeProfileTree>>
2018
2.28k
PipelineFragmentContext::collect_realtime_profile() const {
2019
2.28k
    std::vector<std::shared_ptr<TRuntimeProfileTree>> res;
2020
2021
    // we do not have mutex to protect pipeline_id_to_profile
2022
    // so we need to make sure this funciton is invoked after fragment context
2023
    // has already been prepared.
2024
2.28k
    if (!_prepared) {
2025
0
        std::string msg =
2026
0
                "Query " + print_id(_query_id) + " collecting profile, but its not prepared";
2027
0
        DCHECK(false) << msg;
2028
0
        LOG_ERROR(msg);
2029
0
        return res;
2030
0
    }
2031
2032
    // Make sure first profile is fragment level profile
2033
2.28k
    auto fragment_profile = std::make_shared<TRuntimeProfileTree>();
2034
2.28k
    _fragment_level_profile->to_thrift(fragment_profile.get(), _runtime_state->profile_level());
2035
2.28k
    res.push_back(fragment_profile);
2036
2037
    // pipeline_id_to_profile is initialized in prepare stage
2038
4.24k
    for (auto pipeline_profile : _runtime_state->pipeline_id_to_profile()) {
2039
4.24k
        auto profile_ptr = std::make_shared<TRuntimeProfileTree>();
2040
4.24k
        pipeline_profile->to_thrift(profile_ptr.get(), _runtime_state->profile_level());
2041
4.24k
        res.push_back(profile_ptr);
2042
4.24k
    }
2043
2044
2.28k
    return res;
2045
2.28k
}
2046
2047
std::shared_ptr<TRuntimeProfileTree>
2048
2.28k
PipelineFragmentContext::collect_realtime_load_channel_profile() const {
2049
    // we do not have mutex to protect pipeline_id_to_profile
2050
    // so we need to make sure this funciton is invoked after fragment context
2051
    // has already been prepared.
2052
2.28k
    if (!_prepared) {
2053
0
        std::string msg =
2054
0
                "Query " + print_id(_query_id) + " collecting profile, but its not prepared";
2055
0
        DCHECK(false) << msg;
2056
0
        LOG_ERROR(msg);
2057
0
        return nullptr;
2058
0
    }
2059
2060
6.67k
    for (const auto& tasks : _tasks) {
2061
13.3k
        for (const auto& task : tasks) {
2062
13.3k
            if (task.second->load_channel_profile() == nullptr) {
2063
0
                continue;
2064
0
            }
2065
2066
13.3k
            auto tmp_load_channel_profile = std::make_shared<TRuntimeProfileTree>();
2067
2068
13.3k
            task.second->load_channel_profile()->to_thrift(tmp_load_channel_profile.get(),
2069
13.3k
                                                           _runtime_state->profile_level());
2070
13.3k
            _runtime_state->load_channel_profile()->update(*tmp_load_channel_profile);
2071
13.3k
        }
2072
6.67k
    }
2073
2074
2.28k
    auto load_channel_profile = std::make_shared<TRuntimeProfileTree>();
2075
2.28k
    _runtime_state->load_channel_profile()->to_thrift(load_channel_profile.get(),
2076
2.28k
                                                      _runtime_state->profile_level());
2077
2.28k
    return load_channel_profile;
2078
2.28k
}
2079
2080
3.16k
Status PipelineFragmentContext::wait_close(bool close) {
2081
3.16k
    if (_exec_env->new_load_stream_mgr()->get(_query_id) != nullptr) {
2082
0
        return Status::InternalError("stream load do not support reset");
2083
0
    }
2084
3.16k
    if (!_need_notify_close) {
2085
0
        return Status::InternalError("_need_notify_close is false, do not support reset");
2086
0
    }
2087
2088
3.16k
    {
2089
3.16k
        std::unique_lock<std::mutex> lock(_task_mutex);
2090
3.26k
        while (!(_is_fragment_instance_closed.load() && !_has_task_execution_ctx_ref_count)) {
2091
100
            if (_query_ctx->is_cancelled()) {
2092
0
                return Status::Cancelled("Query has been cancelled");
2093
0
            }
2094
100
            _notify_cv.wait_for(lock, std::chrono::seconds(1));
2095
100
        }
2096
3.16k
    }
2097
2098
3.16k
    if (close) {
2099
176
        auto st = send_report(true);
2100
176
        if (!st) {
2101
139
            LOG(WARNING) << fmt::format("Failed to send report for query {}, fragment {}: {}",
2102
139
                                        print_id(_query_id), _fragment_id, st.to_string());
2103
139
        }
2104
176
        _exec_env->fragment_mgr()->remove_pipeline_context({_query_id, _fragment_id});
2105
176
    }
2106
3.16k
    return Status::OK();
2107
3.16k
}
2108
2109
2.98k
Status PipelineFragmentContext::set_to_rerun() {
2110
2.98k
    {
2111
2.98k
        std::lock_guard<std::mutex> l(_task_mutex);
2112
2.98k
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_query_ctx->query_mem_tracker());
2113
5.88k
        for (auto& tasks : _tasks) {
2114
10.3k
            for (const auto& task : tasks) {
2115
10.3k
                task.first->runtime_state()->reset_to_rerun();
2116
10.3k
            }
2117
5.88k
        }
2118
2.98k
    }
2119
2.98k
    _release_resource();
2120
2.98k
    _runtime_state->reset_to_rerun();
2121
2.98k
    return Status::OK();
2122
2.98k
}
2123
2124
2.98k
Status PipelineFragmentContext::rebuild(ThreadPool* thread_pool) {
2125
2.98k
    _submitted = false;
2126
2.98k
    _is_fragment_instance_closed = false;
2127
2.98k
    return _build_and_prepare_full_pipeline(thread_pool);
2128
2.98k
}
2129
2130
341k
void PipelineFragmentContext::_release_resource() {
2131
341k
    std::lock_guard<std::mutex> l(_task_mutex);
2132
    // The memory released by the query end is recorded in the query mem tracker.
2133
341k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_query_ctx->query_mem_tracker());
2134
341k
    auto st = _query_ctx->exec_status();
2135
880k
    for (auto& _task : _tasks) {
2136
880k
        if (!_task.empty()) {
2137
880k
            _call_back(_task.front().first->runtime_state(), &st);
2138
880k
        }
2139
880k
    }
2140
341k
    _tasks.clear();
2141
341k
    _dag.clear();
2142
341k
    _pip_id_to_pipeline.clear();
2143
341k
    _pipelines.clear();
2144
341k
    _sink.reset();
2145
341k
    _root_op.reset();
2146
341k
    _runtime_filter_mgr_map.clear();
2147
341k
    _op_id_to_shared_state.clear();
2148
341k
}
2149
2150
#include "common/compile_check_end.h"
2151
} // namespace doris