Coverage Report

Created: 2026-03-20 04:39

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