Coverage Report

Created: 2025-12-30 16:22

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