Coverage Report

Created: 2025-09-11 18:52

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