Coverage Report

Created: 2025-07-24 22:14

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