Coverage Report

Created: 2026-03-13 05:13

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