Coverage Report

Created: 2025-12-30 17:16

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