Coverage Report

Created: 2025-04-24 00:04

/root/doris/be/src/pipeline/pipeline_task.cpp
Line
Count
Source (jump to first uncovered line)
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 "pipeline_task.h"
19
20
#include <fmt/core.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/Metrics_types.h>
23
#include <glog/logging.h>
24
25
#include <ostream>
26
#include <vector>
27
28
#include "common/logging.h"
29
#include "common/status.h"
30
#include "pipeline/dependency.h"
31
#include "pipeline/exec/operator.h"
32
#include "pipeline/exec/scan_operator.h"
33
#include "pipeline/pipeline.h"
34
#include "pipeline/pipeline_fragment_context.h"
35
#include "pipeline/task_queue.h"
36
#include "pipeline/task_scheduler.h"
37
#include "runtime/descriptors.h"
38
#include "runtime/exec_env.h"
39
#include "runtime/query_context.h"
40
#include "runtime/thread_context.h"
41
#include "runtime/workload_group/workload_group_manager.h"
42
#include "util/container_util.hpp"
43
#include "util/defer_op.h"
44
#include "util/mem_info.h"
45
#include "util/runtime_profile.h"
46
#include "util/uid_util.h"
47
#include "vec/core/block.h"
48
#include "vec/spill/spill_stream.h"
49
50
namespace doris {
51
class RuntimeState;
52
} // namespace doris
53
54
namespace doris::pipeline {
55
56
PipelineTask::PipelineTask(PipelinePtr& pipeline, uint32_t task_id, RuntimeState* state,
57
                           std::shared_ptr<PipelineFragmentContext> fragment_context,
58
                           RuntimeProfile* parent_profile,
59
                           std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
60
                                                   std::vector<std::shared_ptr<Dependency>>>>
61
                                   shared_state_map,
62
                           int task_idx)
63
        :
64
#ifdef BE_TEST
65
          _query_id(fragment_context ? fragment_context->get_query_id() : TUniqueId()),
66
#else
67
          _query_id(fragment_context->get_query_id()),
68
#endif
69
          _index(task_id),
70
          _pipeline(pipeline),
71
          _opened(false),
72
          _state(state),
73
          _fragment_context(fragment_context),
74
          _parent_profile(parent_profile),
75
          _operators(pipeline->operators()),
76
          _source(_operators.front().get()),
77
          _root(_operators.back().get()),
78
          _sink(pipeline->sink_shared_pointer()),
79
          _shared_state_map(std::move(shared_state_map)),
80
          _task_idx(task_idx),
81
          _execution_dep(state->get_query_ctx()->get_execution_dependency()),
82
          _memory_sufficient_dependency(state->get_query_ctx()->get_memory_sufficient_dependency()),
83
78.1k
          _pipeline_name(_pipeline->name()) {
84
78.1k
    if (!_shared_state_map.contains(_sink->dests_id().front())) {
85
78.1k
        auto shared_state = _sink->create_shared_state();
86
78.1k
        if (shared_state) {
87
29
            _sink_shared_state = shared_state;
88
29
        }
89
78.1k
    }
90
78.1k
}
91
92
Status PipelineTask::prepare(const std::vector<TScanRangeParams>& scan_range, const int sender_id,
93
15
                             const TDataSink& tsink) {
94
15
    DCHECK(_sink);
95
15
    _init_profile();
96
15
    SCOPED_TIMER(_task_profile->total_time_counter());
97
15
    SCOPED_CPU_TIMER(_task_cpu_timer);
98
15
    SCOPED_TIMER(_prepare_timer);
99
15
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::prepare", {
100
15
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task prepare failed");
101
15
        return status;
102
15
    });
103
15
    {
104
        // set sink local state
105
15
        LocalSinkStateInfo info {_task_idx,         _task_profile.get(),
106
15
                                 sender_id,         get_sink_shared_state().get(),
107
15
                                 _shared_state_map, tsink};
108
15
        RETURN_IF_ERROR(_sink->setup_local_state(_state, info));
109
15
    }
110
111
15
    _scan_ranges = scan_range;
112
15
    auto* parent_profile = _state->get_sink_local_state()->profile();
113
114
32
    for (int op_idx = _operators.size() - 1; op_idx >= 0; op_idx--) {
115
17
        auto& op = _operators[op_idx];
116
17
        LocalStateInfo info {parent_profile, _scan_ranges, get_op_shared_state(op->operator_id()),
117
17
                             _shared_state_map, _task_idx};
118
17
        RETURN_IF_ERROR(op->setup_local_state(_state, info));
119
17
        parent_profile = _state->get_local_state(op->operator_id())->profile();
120
17
    }
121
15
    {
122
15
        std::vector<Dependency*> filter_dependencies;
123
15
        const auto& deps = _state->get_local_state(_source->operator_id())->filter_dependencies();
124
15
        std::copy(deps.begin(), deps.end(),
125
15
                  std::inserter(filter_dependencies, filter_dependencies.end()));
126
127
15
        std::unique_lock<std::mutex> lc(_dependency_lock);
128
15
        filter_dependencies.swap(_filter_dependencies);
129
15
    }
130
15
    if (auto fragment = _fragment_context.lock()) {
131
14
        if (fragment->get_query_ctx()->is_cancelled()) {
132
0
            terminate();
133
0
            return fragment->get_query_ctx()->exec_status();
134
0
        }
135
14
    } else {
136
1
        return Status::InternalError("Fragment already finished! Query: {}", print_id(_query_id));
137
1
    }
138
14
    _block = doris::vectorized::Block::create_unique();
139
14
    return _state_transition(State::RUNNABLE);
140
15
}
141
142
13
Status PipelineTask::_extract_dependencies() {
143
13
    std::vector<std::vector<Dependency*>> read_dependencies;
144
13
    std::vector<Dependency*> write_dependencies;
145
13
    std::vector<Dependency*> finish_dependencies;
146
13
    std::vector<Dependency*> spill_dependencies;
147
13
    read_dependencies.resize(_operators.size());
148
13
    size_t i = 0;
149
15
    for (auto& op : _operators) {
150
15
        auto result = _state->get_local_state_result(op->operator_id());
151
15
        if (!result) {
152
1
            return result.error();
153
1
        }
154
14
        auto* local_state = result.value();
155
14
        read_dependencies[i] = local_state->dependencies();
156
14
        auto* fin_dep = local_state->finishdependency();
157
14
        if (fin_dep) {
158
7
            finish_dependencies.push_back(fin_dep);
159
7
        }
160
14
        if (auto* spill_dependency = local_state->spill_dependency()) {
161
7
            spill_dependencies.push_back(spill_dependency);
162
7
        }
163
14
        i++;
164
14
    }
165
12
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::_extract_dependencies", {
166
12
        Status status = Status::Error<INTERNAL_ERROR>(
167
12
                "fault_inject pipeline_task _extract_dependencies failed");
168
12
        return status;
169
12
    });
170
12
    {
171
12
        auto* local_state = _state->get_sink_local_state();
172
12
        write_dependencies = local_state->dependencies();
173
12
        auto* fin_dep = local_state->finishdependency();
174
12
        if (fin_dep) {
175
12
            finish_dependencies.push_back(fin_dep);
176
12
        }
177
12
        if (auto* spill_dependency = local_state->spill_dependency()) {
178
7
            spill_dependencies.push_back(spill_dependency);
179
7
        }
180
12
    }
181
12
    {
182
12
        std::unique_lock<std::mutex> lc(_dependency_lock);
183
12
        read_dependencies.swap(_read_dependencies);
184
12
        write_dependencies.swap(_write_dependencies);
185
12
        finish_dependencies.swap(_finish_dependencies);
186
12
        spill_dependencies.swap(_spill_dependencies);
187
12
    }
188
12
    return Status::OK();
189
12
}
190
191
6
bool PipelineTask::inject_shared_state(std::shared_ptr<BasicSharedState> shared_state) {
192
6
    if (!shared_state) {
193
1
        return false;
194
1
    }
195
    // Shared state is created by upstream task's sink operator and shared by source operator of
196
    // this task.
197
7
    for (auto& op : _operators) {
198
7
        if (shared_state->related_op_ids.contains(op->operator_id())) {
199
3
            _op_shared_states.insert({op->operator_id(), shared_state});
200
3
            return true;
201
3
        }
202
7
    }
203
    // Shared state is created by the first sink operator and shared by sink operator of this task.
204
    // For example, Set operations.
205
2
    if (shared_state->related_op_ids.contains(_sink->dests_id().front())) {
206
1
        DCHECK_EQ(_sink_shared_state, nullptr)
207
0
                << " Sink: " << _sink->get_name() << " dest id: " << _sink->dests_id().front();
208
1
        _sink_shared_state = shared_state;
209
1
        return true;
210
1
    }
211
1
    return false;
212
2
}
213
214
15
void PipelineTask::_init_profile() {
215
15
    _task_profile =
216
15
            std::make_unique<RuntimeProfile>(fmt::format("PipelineTask (index={})", _index));
217
15
    _parent_profile->add_child(_task_profile.get(), true, nullptr);
218
15
    _task_cpu_timer = ADD_TIMER(_task_profile, "TaskCpuTime");
219
220
15
    static const char* exec_time = "ExecuteTime";
221
15
    _exec_timer = ADD_TIMER(_task_profile, exec_time);
222
15
    _prepare_timer = ADD_CHILD_TIMER(_task_profile, "PrepareTime", exec_time);
223
15
    _open_timer = ADD_CHILD_TIMER(_task_profile, "OpenTime", exec_time);
224
15
    _get_block_timer = ADD_CHILD_TIMER(_task_profile, "GetBlockTime", exec_time);
225
15
    _get_block_counter = ADD_COUNTER(_task_profile, "GetBlockCounter", TUnit::UNIT);
226
15
    _sink_timer = ADD_CHILD_TIMER(_task_profile, "SinkTime", exec_time);
227
15
    _close_timer = ADD_CHILD_TIMER(_task_profile, "CloseTime", exec_time);
228
229
15
    _wait_worker_timer = ADD_TIMER_WITH_LEVEL(_task_profile, "WaitWorkerTime", 1);
230
231
15
    _schedule_counts = ADD_COUNTER(_task_profile, "NumScheduleTimes", TUnit::UNIT);
232
15
    _yield_counts = ADD_COUNTER(_task_profile, "NumYieldTimes", TUnit::UNIT);
233
15
    _core_change_times = ADD_COUNTER(_task_profile, "CoreChangeTimes", TUnit::UNIT);
234
15
    _memory_reserve_times = ADD_COUNTER(_task_profile, "MemoryReserveTimes", TUnit::UNIT);
235
15
    _memory_reserve_failed_times =
236
15
            ADD_COUNTER(_task_profile, "MemoryReserveFailedTimes", TUnit::UNIT);
237
15
}
238
239
6
void PipelineTask::_fresh_profile_counter() {
240
6
    COUNTER_SET(_schedule_counts, (int64_t)_schedule_time);
241
6
    COUNTER_SET(_wait_worker_timer, (int64_t)_wait_worker_watcher.elapsed_time());
242
6
}
243
244
12
Status PipelineTask::_open() {
245
12
    SCOPED_TIMER(_task_profile->total_time_counter());
246
12
    SCOPED_CPU_TIMER(_task_cpu_timer);
247
12
    SCOPED_TIMER(_open_timer);
248
12
    _dry_run = _sink->should_dry_run(_state);
249
14
    for (auto& o : _operators) {
250
14
        RETURN_IF_ERROR(_state->get_local_state(o->operator_id())->open(_state));
251
14
    }
252
12
    RETURN_IF_ERROR(_state->get_sink_local_state()->open(_state));
253
12
    RETURN_IF_ERROR(_extract_dependencies());
254
12
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::open", {
255
12
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task open failed");
256
12
        return status;
257
12
    });
258
12
    _opened = true;
259
12
    return Status::OK();
260
12
}
261
262
41
bool PipelineTask::_wait_to_start() {
263
    // Before task starting, we should make sure
264
    // 1. Execution dependency is ready (which is controlled by FE 2-phase commit)
265
    // 2. Runtime filter dependencies are ready
266
41
    return _execution_dep->is_blocked_by(shared_from_this()) ||
267
41
           std::any_of(
268
35
                   _filter_dependencies.begin(), _filter_dependencies.end(),
269
35
                   [&](Dependency* dep) -> bool { return dep->is_blocked_by(shared_from_this()); });
270
41
}
271
272
16
bool PipelineTask::_is_pending_finish() {
273
    // Spilling may be in progress if eos is true.
274
16
    return std::any_of(_spill_dependencies.begin(), _spill_dependencies.end(),
275
16
                       [&](Dependency* dep) -> bool {
276
11
                           return dep->is_blocked_by(shared_from_this());
277
11
                       }) ||
278
16
           std::any_of(
279
15
                   _finish_dependencies.begin(), _finish_dependencies.end(),
280
19
                   [&](Dependency* dep) -> bool { return dep->is_blocked_by(shared_from_this()); });
281
16
}
282
283
2
bool PipelineTask::is_revoking() const {
284
    // Spilling may be in progress if eos is true.
285
2
    return std::any_of(_spill_dependencies.begin(), _spill_dependencies.end(),
286
3
                       [&](Dependency* dep) -> bool { return dep->is_blocked_by(); });
287
2
}
288
289
368k
bool PipelineTask::_is_blocked() {
290
    // `_dry_run = true` means we do not need data from source operator.
291
368k
    if (!_dry_run) {
292
736k
        for (int i = _read_dependencies.size() - 1; i >= 0; i--) {
293
            // `_read_dependencies` is organized according to operators. For each operator, running condition is met iff all dependencies are ready.
294
368k
            for (auto* dep : _read_dependencies[i]) {
295
368k
                if (dep->is_blocked_by(shared_from_this())) {
296
14
                    return true;
297
14
                }
298
368k
            }
299
            // If all dependencies are ready for this operator, we can execute this task if no datum is needed from upstream operators.
300
368k
            if (!_operators[i]->need_more_input_data(_state)) {
301
2
                break;
302
2
            }
303
368k
        }
304
368k
    }
305
368k
    return std::any_of(_spill_dependencies.begin(), _spill_dependencies.end(),
306
736k
                       [&](Dependency* dep) -> bool {
307
736k
                           return dep->is_blocked_by(shared_from_this());
308
736k
                       }) ||
309
368k
           _memory_sufficient_dependency->is_blocked_by(shared_from_this()) ||
310
368k
           std::any_of(
311
368k
                   _write_dependencies.begin(), _write_dependencies.end(),
312
368k
                   [&](Dependency* dep) -> bool { return dep->is_blocked_by(shared_from_this()); });
313
368k
}
314
315
4
void PipelineTask::terminate() {
316
    // We use a lock to assure all dependencies are not deconstructed here.
317
4
    std::unique_lock<std::mutex> lc(_dependency_lock);
318
4
    auto fragment = _fragment_context.lock();
319
4
    if (!is_finalized() && fragment) {
320
4
        DCHECK(_wake_up_early || fragment->is_canceled());
321
4
        std::for_each(_spill_dependencies.begin(), _spill_dependencies.end(),
322
8
                      [&](Dependency* dep) { dep->set_always_ready(); });
323
4
        std::for_each(_filter_dependencies.begin(), _filter_dependencies.end(),
324
4
                      [&](Dependency* dep) { dep->set_always_ready(); });
325
4
        std::for_each(_write_dependencies.begin(), _write_dependencies.end(),
326
4
                      [&](Dependency* dep) { dep->set_always_ready(); });
327
4
        std::for_each(_finish_dependencies.begin(), _finish_dependencies.end(),
328
8
                      [&](Dependency* dep) { dep->set_always_ready(); });
329
4
        std::for_each(_read_dependencies.begin(), _read_dependencies.end(),
330
4
                      [&](std::vector<Dependency*>& deps) {
331
4
                          std::for_each(deps.begin(), deps.end(),
332
4
                                        [&](Dependency* dep) { dep->set_always_ready(); });
333
4
                      });
334
4
        _execution_dep->set_ready();
335
4
        _memory_sufficient_dependency->set_ready();
336
4
    }
337
4
}
338
339
/**
340
 * `_eos` indicates whether the execution phase is done. `done` indicates whether we could close
341
 * this task.
342
 *
343
 * For example,
344
 * 1. if `_eos` is false which means we should continue to get next block so we cannot close (e.g.
345
 *    `done` is false)
346
 * 2. if `_eos` is true which means all blocks from source are exhausted but `_is_pending_finish()`
347
 *    is true which means we should wait for a pending dependency ready (maybe a running rpc), so we
348
 *    cannot close (e.g. `done` is false)
349
 * 3. if `_eos` is true which means all blocks from source are exhausted and `_is_pending_finish()`
350
 *    is false which means we can close immediately (e.g. `done` is true)
351
 * @param done
352
 * @return
353
 */
354
33
Status PipelineTask::execute(bool* done) {
355
33
    if (_exec_state != State::RUNNABLE || _blocked_dep != nullptr) [[unlikely]] {
356
1
        return Status::InternalError("Pipeline task is not runnable! Task info: {}",
357
1
                                     debug_string());
358
1
    }
359
32
    auto fragment_context = _fragment_context.lock();
360
32
    DCHECK(fragment_context);
361
32
    int64_t time_spent = 0;
362
32
    ThreadCpuStopWatch cpu_time_stop_watch;
363
32
    cpu_time_stop_watch.start();
364
32
    SCOPED_ATTACH_TASK(_state);
365
32
    Defer running_defer {[&]() {
366
32
        if (_task_queue) {
367
32
            _task_queue->update_statistics(this, time_spent);
368
32
        }
369
32
        int64_t delta_cpu_time = cpu_time_stop_watch.elapsed_time();
370
32
        _task_cpu_timer->update(delta_cpu_time);
371
32
        fragment_context->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(
372
32
                delta_cpu_time);
373
374
        // If task is woke up early, we should terminate all operators, and this task could be closed immediately.
375
32
        if (_wake_up_early) {
376
3
            terminate();
377
3
            THROW_IF_ERROR(_root->terminate(_state));
378
3
            THROW_IF_ERROR(_sink->terminate(_state));
379
3
            _eos = true;
380
3
            *done = true;
381
29
        } else if (_eos && !_spilling &&
382
29
                   (fragment_context->is_canceled() || !_is_pending_finish())) {
383
8
            *done = true;
384
8
        }
385
32
    }};
386
32
    const auto query_id = _state->query_id();
387
    // If this task is already EOS and block is empty (which means we already output all blocks),
388
    // just return here.
389
32
    if (_eos && !_spilling) {
390
1
        return Status::OK();
391
1
    }
392
    // If this task is blocked by a spilling request and waken up immediately, the spilling
393
    // dependency will not block this task and we should just run here.
394
31
    if (!_block->empty()) {
395
0
        LOG(INFO) << "Query: " << print_id(query_id) << " has pending block, size: "
396
0
                  << PrettyPrinter::print_bytes(_block->allocated_bytes());
397
0
        DCHECK(_spilling);
398
0
    }
399
400
31
    SCOPED_TIMER(_task_profile->total_time_counter());
401
31
    SCOPED_TIMER(_exec_timer);
402
403
31
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::execute", {
404
31
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task execute failed");
405
31
        return status;
406
31
    });
407
    // `_wake_up_early` must be after `_wait_to_start()`
408
31
    if (_wait_to_start() || _wake_up_early) {
409
2
        if (config::enable_prefetch_tablet) {
410
2
            RETURN_IF_ERROR(_source->hold_tablets(_state));
411
2
        }
412
2
        return Status::OK();
413
2
    }
414
415
    // The status must be runnable
416
29
    if (!_opened && !fragment_context->is_canceled()) {
417
11
        DBUG_EXECUTE_IF("PipelineTask::execute.open_sleep", {
418
11
            auto required_pipeline_id =
419
11
                    DebugPoints::instance()->get_debug_param_or_default<int32_t>(
420
11
                            "PipelineTask::execute.open_sleep", "pipeline_id", -1);
421
11
            auto required_task_id = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
422
11
                    "PipelineTask::execute.open_sleep", "task_id", -1);
423
11
            if (required_pipeline_id == pipeline_id() && required_task_id == task_id()) {
424
11
                LOG(WARNING) << "PipelineTask::execute.open_sleep sleep 5s";
425
11
                sleep(5);
426
11
            }
427
11
        });
428
429
11
        SCOPED_RAW_TIMER(&time_spent);
430
11
        RETURN_IF_ERROR(_open());
431
11
    }
432
433
368k
    while (!fragment_context->is_canceled()) {
434
368k
        SCOPED_RAW_TIMER(&time_spent);
435
368k
        Defer defer {[&]() {
436
            // If this run is pended by a spilling request, the block will be output in next run.
437
368k
            if (!_spilling) {
438
366k
                _block->clear_column_data(_root->row_desc().num_materialized_slots());
439
366k
            }
440
368k
        }};
441
        // `_wake_up_early` must be after `_is_blocked()`
442
368k
        if (_is_blocked() || _wake_up_early) {
443
16
            return Status::OK();
444
16
        }
445
446
        /// When a task is cancelled,
447
        /// its blocking state will be cleared and it will transition to a ready state (though it is not truly ready).
448
        /// Here, checking whether it is cancelled to prevent tasks in a blocking state from being re-executed.
449
368k
        if (fragment_context->is_canceled()) {
450
0
            break;
451
0
        }
452
453
368k
        if (time_spent > _exec_time_slice) {
454
3
            COUNTER_UPDATE(_yield_counts, 1);
455
3
            break;
456
3
        }
457
368k
        auto* block = _block.get();
458
459
368k
        DBUG_EXECUTE_IF("fault_inject::PipelineXTask::executing", {
460
368k
            Status status =
461
368k
                    Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task executing failed");
462
368k
            return status;
463
368k
        });
464
465
        // `_sink->is_finished(_state)` means sink operator should be finished
466
368k
        if (_sink->is_finished(_state)) {
467
1
            set_wake_up_early();
468
1
            return Status::OK();
469
1
        }
470
471
        // `_dry_run` means sink operator need no more data
472
368k
        _eos = _dry_run || _eos;
473
368k
        _spilling = false;
474
368k
        auto workload_group = _state->workload_group();
475
        // If last run is pended by a spilling request, `_block` is produced with some rows in last
476
        // run, so we will resume execution using the block.
477
368k
        if (!_eos && _block->empty()) {
478
367k
            SCOPED_TIMER(_get_block_timer);
479
367k
            if (_state->low_memory_mode()) {
480
1.43k
                _sink->set_low_memory_mode(_state);
481
1.43k
                _root->set_low_memory_mode(_state);
482
1.43k
            }
483
367k
            DEFER_RELEASE_RESERVED();
484
367k
            _get_block_counter->update(1);
485
367k
            const auto reserve_size = _root->get_reserve_mem_size(_state);
486
367k
            _root->reset_reserve_mem_size(_state);
487
488
367k
            if (workload_group &&
489
367k
                _state->get_query_ctx()
490
2.39k
                        ->resource_ctx()
491
2.39k
                        ->task_controller()
492
2.39k
                        ->is_enable_reserve_memory() &&
493
367k
                reserve_size > 0) {
494
2.39k
                if (!_try_to_reserve_memory(reserve_size, _root)) {
495
951
                    continue;
496
951
                }
497
2.39k
            }
498
499
366k
            bool eos = false;
500
366k
            RETURN_IF_ERROR(_root->get_block_after_projects(_state, block, &eos));
501
366k
            _eos = eos;
502
366k
        }
503
504
367k
        if (!_block->empty() || _eos) {
505
986
            SCOPED_TIMER(_sink_timer);
506
986
            Status status = Status::OK();
507
986
            DEFER_RELEASE_RESERVED();
508
986
            COUNTER_UPDATE(_memory_reserve_times, 1);
509
986
            if (_state->get_query_ctx()
510
986
                        ->resource_ctx()
511
986
                        ->task_controller()
512
986
                        ->is_enable_reserve_memory() &&
513
986
                workload_group && !(_wake_up_early || _dry_run)) {
514
973
                const auto sink_reserve_size = _sink->get_reserve_mem_size(_state, _eos);
515
973
                if (sink_reserve_size > 0 &&
516
973
                    !_try_to_reserve_memory(sink_reserve_size, _sink.get())) {
517
971
                    continue;
518
971
                }
519
973
            }
520
521
15
            if (_eos) {
522
9
                RETURN_IF_ERROR(close(Status::OK(), false));
523
9
            }
524
525
15
            DBUG_EXECUTE_IF("PipelineTask::execute.sink_eos_sleep", {
526
15
                auto required_pipeline_id =
527
15
                        DebugPoints::instance()->get_debug_param_or_default<int32_t>(
528
15
                                "PipelineTask::execute.sink_eos_sleep", "pipeline_id", -1);
529
15
                auto required_task_id =
530
15
                        DebugPoints::instance()->get_debug_param_or_default<int32_t>(
531
15
                                "PipelineTask::execute.sink_eos_sleep", "task_id", -1);
532
15
                if (required_pipeline_id == pipeline_id() && required_task_id == task_id()) {
533
15
                    LOG(WARNING) << "PipelineTask::execute.sink_eos_sleep sleep 10s";
534
15
                    sleep(10);
535
15
                }
536
15
            });
537
538
15
            DBUG_EXECUTE_IF("PipelineTask::execute.terminate", {
539
15
                if (_eos) {
540
15
                    auto required_pipeline_id =
541
15
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
542
15
                                    "PipelineTask::execute.terminate", "pipeline_id", -1);
543
15
                    auto required_task_id =
544
15
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
545
15
                                    "PipelineTask::execute.terminate", "task_id", -1);
546
15
                    auto required_fragment_id =
547
15
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
548
15
                                    "PipelineTask::execute.terminate", "fragment_id", -1);
549
15
                    if (required_pipeline_id == pipeline_id() && required_task_id == task_id() &&
550
15
                        fragment_context->get_fragment_id() == required_fragment_id) {
551
15
                        _wake_up_early = true;
552
15
                        terminate();
553
15
                    } else if (required_pipeline_id == pipeline_id() &&
554
15
                               fragment_context->get_fragment_id() == required_fragment_id) {
555
15
                        LOG(WARNING) << "PipelineTask::execute.terminate sleep 5s";
556
15
                        sleep(5);
557
15
                    }
558
15
                }
559
15
            });
560
15
            status = _sink->sink(_state, block, _eos);
561
562
15
            if (status.is<ErrorCode::END_OF_FILE>()) {
563
1
                set_wake_up_early();
564
1
                return Status::OK();
565
14
            } else if (!status) {
566
0
                return status;
567
0
            }
568
569
14
            if (_eos) { // just return, the scheduler will do finish work
570
8
                return Status::OK();
571
8
            }
572
14
        }
573
367k
    }
574
575
3
    RETURN_IF_ERROR(get_task_queue()->push_back(shared_from_this()));
576
3
    return Status::OK();
577
3
}
578
579
3.36k
bool PipelineTask::_try_to_reserve_memory(const size_t reserve_size, OperatorBase* op) {
580
3.36k
    auto st = thread_context()->thread_mem_tracker_mgr->try_reserve(reserve_size);
581
3.36k
    COUNTER_UPDATE(_memory_reserve_times, 1);
582
3.36k
    auto sink_revocable_mem_size = _sink->revocable_mem_size(_state);
583
3.36k
    if (st.ok() && _state->enable_force_spill() && _sink->is_spillable() &&
584
3.36k
        sink_revocable_mem_size >= vectorized::SpillStream::MIN_SPILL_WRITE_BATCH_MEM) {
585
0
        st = Status(ErrorCode::QUERY_MEMORY_EXCEEDED, "Force Spill");
586
0
    }
587
3.36k
    if (!st.ok()) {
588
3.36k
        COUNTER_UPDATE(_memory_reserve_failed_times, 1);
589
3.36k
        auto debug_msg = fmt::format(
590
3.36k
                "Query: {} , try to reserve: {}, operator name: {}, operator "
591
3.36k
                "id: {}, task id: {}, root revocable mem size: {}, sink revocable mem"
592
3.36k
                "size: {}, failed: {}",
593
3.36k
                print_id(_query_id), PrettyPrinter::print_bytes(reserve_size), op->get_name(),
594
3.36k
                op->node_id(), _state->task_id(),
595
3.36k
                PrettyPrinter::print_bytes(op->revocable_mem_size(_state)),
596
3.36k
                PrettyPrinter::print_bytes(sink_revocable_mem_size), st.to_string());
597
        // PROCESS_MEMORY_EXCEEDED error msg alread contains process_mem_log_str
598
3.36k
        if (!st.is<ErrorCode::PROCESS_MEMORY_EXCEEDED>()) {
599
3.36k
            debug_msg +=
600
3.36k
                    fmt::format(", debug info: {}", GlobalMemoryArbitrator::process_mem_log_str());
601
3.36k
        }
602
3.36k
        LOG_EVERY_N(INFO, 100) << debug_msg;
603
        // If sink has enough revocable memory, trigger revoke memory
604
3.36k
        if (sink_revocable_mem_size >= vectorized::SpillStream::MIN_SPILL_WRITE_BATCH_MEM) {
605
1.92k
            LOG(INFO) << fmt::format(
606
1.92k
                    "Query: {} sink: {}, node id: {}, task id: "
607
1.92k
                    "{}, revocable mem size: {}",
608
1.92k
                    print_id(_query_id), _sink->get_name(), _sink->node_id(), _state->task_id(),
609
1.92k
                    PrettyPrinter::print_bytes(sink_revocable_mem_size));
610
1.92k
            ExecEnv::GetInstance()->workload_group_mgr()->add_paused_query(
611
1.92k
                    _state->get_query_ctx()->resource_ctx()->shared_from_this(), reserve_size, st);
612
1.92k
            _spilling = true;
613
1.92k
            return false;
614
1.92k
        } else {
615
            // If reserve failed, not add this query to paused list, because it is very small, will not
616
            // consume a lot of memory. But need set low memory mode to indicate that the system should
617
            // not use too much memory.
618
1.44k
            _state->get_query_ctx()->set_low_memory_mode();
619
1.44k
        }
620
3.36k
    }
621
1.44k
    return true;
622
3.36k
}
623
624
247k
void PipelineTask::stop_if_finished() {
625
247k
    auto fragment = _fragment_context.lock();
626
247k
    if (!fragment) {
627
0
        return;
628
0
    }
629
247k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(fragment->get_query_ctx()->query_mem_tracker());
630
247k
    if (auto sink = _sink) {
631
247k
        if (sink->is_finished(_state)) {
632
0
            set_wake_up_early();
633
0
            terminate();
634
0
        }
635
247k
    }
636
247k
}
637
638
1
Status PipelineTask::finalize() {
639
1
    auto fragment = _fragment_context.lock();
640
1
    if (!fragment) {
641
0
        return Status::OK();
642
0
    }
643
1
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(fragment->get_query_ctx()->query_mem_tracker());
644
1
    std::unique_lock<std::mutex> lc(_dependency_lock);
645
1
    RETURN_IF_ERROR(_state_transition(State::FINALIZED));
646
1
    _sink_shared_state.reset();
647
1
    _op_shared_states.clear();
648
1
    _shared_state_map.clear();
649
1
    _block.reset();
650
1
    _operators.clear();
651
1
    _sink.reset();
652
1
    _pipeline.reset();
653
1
    return Status::OK();
654
1
}
655
656
15
Status PipelineTask::close(Status exec_status, bool close_sink) {
657
15
    int64_t close_ns = 0;
658
15
    Status s;
659
15
    {
660
15
        SCOPED_RAW_TIMER(&close_ns);
661
15
        if (close_sink) {
662
6
            s = _sink->close(_state, exec_status);
663
6
        }
664
19
        for (auto& op : _operators) {
665
19
            auto tem = op->close(_state);
666
19
            if (!tem.ok() && s.ok()) {
667
0
                s = tem;
668
0
            }
669
19
        }
670
15
    }
671
15
    if (_opened) {
672
15
        COUNTER_UPDATE(_close_timer, close_ns);
673
15
        COUNTER_UPDATE(_task_profile->total_time_counter(), close_ns);
674
15
    }
675
676
15
    if (close_sink && _opened) {
677
6
        _task_profile->add_info_string("WakeUpEarly", std::to_string(_wake_up_early.load()));
678
6
        _fresh_profile_counter();
679
6
    }
680
681
15
    if (_task_queue) {
682
15
        _task_queue->update_statistics(this, close_ns);
683
15
    }
684
15
    if (close_sink) {
685
6
        RETURN_IF_ERROR(_state_transition(State::FINISHED));
686
6
    }
687
15
    return s;
688
15
}
689
690
11.2k
std::string PipelineTask::debug_string() {
691
11.2k
    fmt::memory_buffer debug_string_buffer;
692
693
11.2k
    fmt::format_to(debug_string_buffer, "QueryId: {}\n", print_id(_query_id));
694
11.2k
    fmt::format_to(debug_string_buffer, "InstanceId: {}\n",
695
11.2k
                   print_id(_state->fragment_instance_id()));
696
697
11.2k
    fmt::format_to(debug_string_buffer,
698
11.2k
                   "PipelineTask[id = {}, open = {}, eos = {}, state = {}, dry run = "
699
11.2k
                   "{}, _wake_up_early = {}, time elapsed since last state changing = {}s, spilling"
700
11.2k
                   " = {}, is running = {}]",
701
11.2k
                   _index, _opened, _eos, _to_string(_exec_state), _dry_run, _wake_up_early.load(),
702
11.2k
                   _state_change_watcher.elapsed_time() / NANOS_PER_SEC, _spilling, is_running());
703
11.2k
    std::unique_lock<std::mutex> lc(_dependency_lock);
704
11.2k
    auto* cur_blocked_dep = _blocked_dep;
705
11.2k
    auto fragment = _fragment_context.lock();
706
11.2k
    if (is_finalized() || !fragment) {
707
5
        fmt::format_to(debug_string_buffer, " pipeline name = {}", _pipeline_name);
708
5
        return fmt::to_string(debug_string_buffer);
709
5
    }
710
11.2k
    auto elapsed = fragment->elapsed_time() / NANOS_PER_SEC;
711
11.2k
    fmt::format_to(debug_string_buffer,
712
11.2k
                   " elapse time = {}s, block dependency = [{}]\noperators: ", elapsed,
713
11.2k
                   cur_blocked_dep && !is_finalized() ? cur_blocked_dep->debug_string() : "NULL");
714
715
22.5k
    for (size_t i = 0; i < _operators.size(); i++) {
716
11.2k
        fmt::format_to(debug_string_buffer, "\n{}",
717
11.2k
                       _opened && !is_finalized() ? _operators[i]->debug_string(_state, i)
718
11.2k
                                                  : _operators[i]->debug_string(i));
719
11.2k
    }
720
11.2k
    fmt::format_to(debug_string_buffer, "\n{}\n",
721
11.2k
                   _opened && !is_finalized() ? _sink->debug_string(_state, _operators.size())
722
11.2k
                                              : _sink->debug_string(_operators.size()));
723
724
11.2k
    fmt::format_to(debug_string_buffer, "\nRead Dependency Information: \n");
725
726
11.2k
    size_t i = 0;
727
22.5k
    for (; i < _read_dependencies.size(); i++) {
728
22.5k
        for (size_t j = 0; j < _read_dependencies[i].size(); j++) {
729
11.2k
            fmt::format_to(debug_string_buffer, "{}. {}\n", i,
730
11.2k
                           _read_dependencies[i][j]->debug_string(i + 1));
731
11.2k
        }
732
11.2k
    }
733
734
11.2k
    fmt::format_to(debug_string_buffer, "{}. {}\n", i,
735
11.2k
                   _memory_sufficient_dependency->debug_string(i++));
736
737
11.2k
    fmt::format_to(debug_string_buffer, "\nWrite Dependency Information: \n");
738
22.5k
    for (size_t j = 0; j < _write_dependencies.size(); j++, i++) {
739
11.2k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
740
11.2k
                       _write_dependencies[j]->debug_string(i + 1));
741
11.2k
    }
742
743
11.2k
    fmt::format_to(debug_string_buffer, "\nRuntime Filter Dependency Information: \n");
744
22.5k
    for (size_t j = 0; j < _filter_dependencies.size(); j++, i++) {
745
11.2k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
746
11.2k
                       _filter_dependencies[j]->debug_string(i + 1));
747
11.2k
    }
748
749
11.2k
    fmt::format_to(debug_string_buffer, "\nSpill Dependency Information: \n");
750
33.8k
    for (size_t j = 0; j < _spill_dependencies.size(); j++, i++) {
751
22.5k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
752
22.5k
                       _spill_dependencies[j]->debug_string(i + 1));
753
22.5k
    }
754
755
11.2k
    fmt::format_to(debug_string_buffer, "Finish Dependency Information: \n");
756
33.8k
    for (size_t j = 0; j < _finish_dependencies.size(); j++, i++) {
757
22.5k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
758
22.5k
                       _finish_dependencies[j]->debug_string(j + 1));
759
22.5k
    }
760
11.2k
    return fmt::to_string(debug_string_buffer);
761
11.2k
}
762
763
0
size_t PipelineTask::get_revocable_size() const {
764
0
    if (is_finalized() || _running || (_eos && !_spilling)) {
765
0
        return 0;
766
0
    }
767
768
0
    return _sink->revocable_mem_size(_state);
769
0
}
770
771
0
Status PipelineTask::revoke_memory(const std::shared_ptr<SpillContext>& spill_context) {
772
0
    if (is_finalized()) {
773
0
        if (spill_context) {
774
0
            spill_context->on_task_finished();
775
0
            VLOG_DEBUG << "Query: " << print_id(_state->query_id()) << ", task: " << ((void*)this)
776
0
                       << " finalized";
777
0
        }
778
0
        return Status::OK();
779
0
    }
780
781
0
    const auto revocable_size = _sink->revocable_mem_size(_state);
782
0
    if (revocable_size >= vectorized::SpillStream::MIN_SPILL_WRITE_BATCH_MEM) {
783
0
        RETURN_IF_ERROR(_sink->revoke_memory(_state, spill_context));
784
0
    } else if (spill_context) {
785
0
        spill_context->on_task_finished();
786
0
        LOG(INFO) << "Query: " << print_id(_state->query_id()) << ", task: " << ((void*)this)
787
0
                  << " has not enough data to revoke: " << revocable_size;
788
0
    }
789
0
    return Status::OK();
790
0
}
791
792
25
Status PipelineTask::wake_up(Dependency* dep) {
793
    // call by dependency
794
25
    DCHECK_EQ(_blocked_dep, dep) << "dep : " << dep->debug_string(0) << "task: " << debug_string();
795
25
    _blocked_dep = nullptr;
796
25
    auto holder = std::dynamic_pointer_cast<PipelineTask>(shared_from_this());
797
25
    RETURN_IF_ERROR(_state_transition(PipelineTask::State::RUNNABLE));
798
25
    RETURN_IF_ERROR(get_task_queue()->push_back(holder));
799
25
    return Status::OK();
800
25
}
801
802
96
Status PipelineTask::_state_transition(State new_state) {
803
96
    if (_exec_state != new_state) {
804
91
        _state_change_watcher.reset();
805
91
        _state_change_watcher.start();
806
91
    }
807
96
    _task_profile->add_info_string("TaskState", _to_string(new_state));
808
96
    _task_profile->add_info_string("BlockedByDependency", _blocked_dep ? _blocked_dep->name() : "");
809
96
    if (!LEGAL_STATE_TRANSITION[(int)new_state].contains(_exec_state)) {
810
17
        return Status::InternalError(
811
17
                "Task state transition from {} to {} is not allowed! Task info: {}",
812
17
                _to_string(_exec_state), _to_string(new_state), debug_string());
813
17
    }
814
79
    _exec_state = new_state;
815
79
    return Status::OK();
816
96
}
817
818
} // namespace doris::pipeline