Coverage Report

Created: 2026-03-20 10:42

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