Coverage Report

Created: 2026-03-17 12:19

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