Coverage Report

Created: 2026-05-27 18:10

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
31
            _sink_shared_state = shared_state;
94
31
        }
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
17
                             const TDataSink& tsink) {
124
17
    DCHECK(_sink);
125
17
    _init_profile();
126
17
    SCOPED_TIMER(_task_profile->total_time_counter());
127
17
    SCOPED_CPU_TIMER(_task_cpu_timer);
128
17
    SCOPED_TIMER(_prepare_timer);
129
17
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::prepare", {
130
17
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task prepare failed");
131
17
        return status;
132
17
    });
133
17
    {
134
        // set sink local state
135
17
        LocalSinkStateInfo info {_task_idx,         _task_profile.get(),
136
17
                                 sender_id,         get_sink_shared_state().get(),
137
17
                                 _shared_state_map, tsink};
138
17
        RETURN_IF_ERROR(_sink->setup_local_state(_state, info));
139
17
    }
140
141
17
    _scan_ranges = scan_range;
142
17
    auto* parent_profile = _state->get_sink_local_state()->operator_profile();
143
144
36
    for (int op_idx = cast_set<int>(_operators.size() - 1); op_idx >= 0; op_idx--) {
145
19
        auto& op = _operators[op_idx];
146
19
        LocalStateInfo info {parent_profile, _scan_ranges, get_op_shared_state(op->operator_id()),
147
19
                             _shared_state_map, _task_idx};
148
19
        RETURN_IF_ERROR(op->setup_local_state(_state, info));
149
19
        parent_profile = _state->get_local_state(op->operator_id())->operator_profile();
150
19
    }
151
17
    {
152
17
        const auto& deps =
153
17
                _state->get_local_state(_source->operator_id())->execution_dependencies();
154
17
        std::unique_lock<std::mutex> lc(_dependency_lock);
155
17
        std::copy(deps.begin(), deps.end(),
156
17
                  std::inserter(_execution_dependencies, _execution_dependencies.end()));
157
17
    }
158
17
    if (auto fragment = _fragment_context.lock()) {
159
16
        if (fragment->get_query_ctx()->is_cancelled()) {
160
0
            terminate();
161
0
            return fragment->get_query_ctx()->exec_status();
162
0
        }
163
16
    } else {
164
1
        return Status::InternalError("Fragment already finished! Query: {}", print_id(_query_id));
165
1
    }
166
16
    _block = doris::vectorized::Block::create_unique();
167
16
    return _state_transition(State::RUNNABLE);
168
17
}
169
170
15
Status PipelineTask::_extract_dependencies() {
171
15
    std::vector<std::vector<Dependency*>> read_dependencies;
172
15
    std::vector<Dependency*> write_dependencies;
173
15
    std::vector<Dependency*> finish_dependencies;
174
15
    read_dependencies.resize(_operators.size());
175
15
    size_t i = 0;
176
17
    for (auto& op : _operators) {
177
17
        auto result = _state->get_local_state_result(op->operator_id());
178
17
        if (!result) {
179
1
            return result.error();
180
1
        }
181
16
        auto* local_state = result.value();
182
16
        read_dependencies[i] = local_state->dependencies();
183
16
        auto* fin_dep = local_state->finishdependency();
184
16
        if (fin_dep) {
185
9
            finish_dependencies.push_back(fin_dep);
186
9
        }
187
16
        i++;
188
16
    }
189
14
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::_extract_dependencies", {
190
14
        Status status = Status::Error<INTERNAL_ERROR>(
191
14
                "fault_inject pipeline_task _extract_dependencies failed");
192
14
        return status;
193
14
    });
194
14
    {
195
14
        auto* local_state = _state->get_sink_local_state();
196
14
        write_dependencies = local_state->dependencies();
197
14
        auto* fin_dep = local_state->finishdependency();
198
14
        if (fin_dep) {
199
14
            finish_dependencies.push_back(fin_dep);
200
14
        }
201
14
    }
202
14
    {
203
14
        std::unique_lock<std::mutex> lc(_dependency_lock);
204
14
        read_dependencies.swap(_read_dependencies);
205
14
        write_dependencies.swap(_write_dependencies);
206
14
        finish_dependencies.swap(_finish_dependencies);
207
14
    }
208
14
    return Status::OK();
209
14
}
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
17
void PipelineTask::_init_profile() {
235
17
    _task_profile = std::make_unique<RuntimeProfile>(fmt::format("PipelineTask(index={})", _index));
236
17
    _parent_profile->add_child(_task_profile.get(), true, nullptr);
237
17
    _task_cpu_timer = ADD_TIMER(_task_profile, "TaskCpuTime");
238
239
17
    static const char* exec_time = "ExecuteTime";
240
17
    _exec_timer = ADD_TIMER(_task_profile, exec_time);
241
17
    _prepare_timer = ADD_CHILD_TIMER(_task_profile, "PrepareTime", exec_time);
242
17
    _open_timer = ADD_CHILD_TIMER(_task_profile, "OpenTime", exec_time);
243
17
    _get_block_timer = ADD_CHILD_TIMER(_task_profile, "GetBlockTime", exec_time);
244
17
    _get_block_counter = ADD_COUNTER(_task_profile, "GetBlockCounter", TUnit::UNIT);
245
17
    _sink_timer = ADD_CHILD_TIMER(_task_profile, "SinkTime", exec_time);
246
17
    _close_timer = ADD_CHILD_TIMER(_task_profile, "CloseTime", exec_time);
247
248
17
    _wait_worker_timer = ADD_TIMER_WITH_LEVEL(_task_profile, "WaitWorkerTime", 1);
249
250
17
    _schedule_counts = ADD_COUNTER(_task_profile, "NumScheduleTimes", TUnit::UNIT);
251
17
    _yield_counts = ADD_COUNTER(_task_profile, "NumYieldTimes", TUnit::UNIT);
252
17
    _core_change_times = ADD_COUNTER(_task_profile, "CoreChangeTimes", TUnit::UNIT);
253
17
    _memory_reserve_times = ADD_COUNTER(_task_profile, "MemoryReserveTimes", TUnit::UNIT);
254
17
    _memory_reserve_failed_times =
255
17
            ADD_COUNTER(_task_profile, "MemoryReserveFailedTimes", TUnit::UNIT);
256
17
}
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
14
Status PipelineTask::_open() {
264
14
    SCOPED_TIMER(_task_profile->total_time_counter());
265
14
    SCOPED_CPU_TIMER(_task_cpu_timer);
266
14
    SCOPED_TIMER(_open_timer);
267
14
    _dry_run = _sink->should_dry_run(_state);
268
16
    for (auto& o : _operators) {
269
16
        RETURN_IF_ERROR(_state->get_local_state(o->operator_id())->open(_state));
270
16
    }
271
14
    RETURN_IF_ERROR(_state->get_sink_local_state()->open(_state));
272
14
    RETURN_IF_ERROR(_extract_dependencies());
273
14
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::open", {
274
14
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task open failed");
275
14
        return status;
276
14
    });
277
14
    _opened = true;
278
14
    return Status::OK();
279
14
}
280
281
68
Status PipelineTask::_prepare() {
282
68
    SCOPED_TIMER(_task_profile->total_time_counter());
283
68
    SCOPED_CPU_TIMER(_task_cpu_timer);
284
80
    for (auto& o : _operators) {
285
80
        RETURN_IF_ERROR(_state->get_local_state(o->operator_id())->prepare(_state));
286
80
    }
287
68
    RETURN_IF_ERROR(_state->get_sink_local_state()->prepare(_state));
288
68
    return Status::OK();
289
68
}
290
291
45
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
45
    return std::any_of(
297
45
            _execution_dependencies.begin(), _execution_dependencies.end(),
298
62
            [&](Dependency* dep) -> bool { return dep->is_blocked_by(shared_from_this()); });
299
45
}
300
301
18
bool PipelineTask::_is_pending_finish() {
302
    // Spilling may be in progress if eos is true.
303
25
    return std::ranges::any_of(_finish_dependencies, [&](Dependency* dep) -> bool {
304
25
        return dep->is_blocked_by(shared_from_this());
305
25
    });
306
18
}
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
531k
bool PipelineTask::_is_blocked() {
326
    // `_dry_run = true` means we do not need data from source operator.
327
531k
    if (!_dry_run) {
328
1.06M
        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
531k
            for (auto* dep : _read_dependencies[i]) {
331
531k
                if (dep->is_blocked_by(shared_from_this())) {
332
15
                    return true;
333
15
                }
334
531k
            }
335
            // If all dependencies are ready for this operator, we can execute this task if no datum is needed from upstream operators.
336
531k
            if (!_operators[i]->need_more_input_data(_state)) {
337
2
                break;
338
2
            }
339
531k
        }
340
531k
    }
341
531k
    return _memory_sufficient_dependency->is_blocked_by(shared_from_this()) ||
342
531k
           std::ranges::any_of(_write_dependencies, [&](Dependency* dep) -> bool {
343
531k
               return dep->is_blocked_by(shared_from_this());
344
531k
           });
345
531k
}
346
347
7
void PipelineTask::terminate() {
348
    // We use a lock to assure all dependencies are not deconstructed here.
349
7
    std::unique_lock<std::mutex> lc(_dependency_lock);
350
7
    auto fragment = _fragment_context.lock();
351
7
    if (!is_finalized() && fragment) {
352
7
        try {
353
7
            DCHECK(_wake_up_early || fragment->is_canceled());
354
7
            std::ranges::for_each(_write_dependencies,
355
7
                                  [&](Dependency* dep) { dep->set_always_ready(); });
356
7
            std::ranges::for_each(_finish_dependencies,
357
14
                                  [&](Dependency* dep) { dep->set_always_ready(); });
358
7
            std::ranges::for_each(_read_dependencies, [&](std::vector<Dependency*>& deps) {
359
7
                std::ranges::for_each(deps, [&](Dependency* dep) { dep->set_always_ready(); });
360
7
            });
361
            // All `_execution_deps` will never be set blocking from ready. So we just set ready here.
362
7
            std::ranges::for_each(_execution_dependencies,
363
14
                                  [&](Dependency* dep) { dep->set_ready(); });
364
7
            _memory_sufficient_dependency->set_ready();
365
7
        } catch (const doris::Exception& e) {
366
0
            LOG(WARNING) << "Terminate failed: " << e.code() << ", " << e.to_string();
367
0
        }
368
7
    }
369
7
}
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
39
Status PipelineTask::execute(bool* done) {
387
39
    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
38
    auto fragment_context = _fragment_context.lock();
397
38
    if (!fragment_context) {
398
0
        return Status::InternalError("Fragment already finished! Query: {}", print_id(_query_id));
399
0
    }
400
38
    int64_t time_spent = 0;
401
38
    ThreadCpuStopWatch cpu_time_stop_watch;
402
38
    cpu_time_stop_watch.start();
403
38
    SCOPED_ATTACH_TASK(_state);
404
38
    Defer running_defer {[&]() {
405
38
        int64_t delta_cpu_time = cpu_time_stop_watch.elapsed_time();
406
38
        _task_cpu_timer->update(delta_cpu_time);
407
38
        fragment_context->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(
408
38
                delta_cpu_time);
409
410
        // If task is woke up early, we should terminate all operators, and this task could be closed immediately.
411
38
        if (_wake_up_early) {
412
3
            _eos = true;
413
3
            *done = true;
414
35
        } else if (_eos && !_spilling &&
415
35
                   (fragment_context->is_canceled() || !_is_pending_finish())) {
416
            // Debug point for testing the race condition fix: inject set_wake_up_early() +
417
            // terminate() here to simulate Thread B writing A then B between Thread A's two
418
            // reads of _wake_up_early.
419
11
            DBUG_EXECUTE_IF("PipelineTask::execute.wake_up_early_in_else_if", {
420
11
                set_wake_up_early();
421
11
                terminate();
422
11
            });
423
11
            *done = true;
424
11
        }
425
426
        // NOTE: The terminate() call is intentionally placed AFTER the _is_pending_finish() check
427
        // above, not before. This ordering is critical to avoid a race condition:
428
        //
429
        // Pipeline::make_all_runnable() writes in this order:
430
        //   (A) set_wake_up_early()  ->  (B) terminate() [sets finish_dep._always_ready]
431
        //
432
        // If we checked _wake_up_early (A) before _is_pending_finish() (B), there would be a
433
        // window where Thread A reads _wake_up_early=false, then Thread B writes both A and B,
434
        // then Thread A reads _is_pending_finish()=false (due to _always_ready). Thread A would
435
        // then set *done=true without ever calling operator terminate(), causing close() to run
436
        // on operators that were never properly terminated (e.g. RuntimeFilterProducer still in
437
        // WAITING_FOR_SYNCED_SIZE state when insert() is called).
438
        //
439
        // By reading _is_pending_finish() (B) before the second read of _wake_up_early (A),
440
        // if Thread A observes B's effect (_always_ready=true), it is guaranteed to also observe
441
        // A's effect (_wake_up_early=true) on this second read, ensuring terminate() is called.
442
38
        if (_wake_up_early) {
443
4
            terminate();
444
4
            THROW_IF_ERROR(_root->terminate(_state));
445
4
            THROW_IF_ERROR(_sink->terminate(_state));
446
4
        }
447
38
    }};
448
38
    const auto query_id = _state->query_id();
449
    // If this task is already EOS and block is empty (which means we already output all blocks),
450
    // just return here.
451
38
    if (_eos && !_spilling) {
452
3
        return Status::OK();
453
3
    }
454
    // If this task is blocked by a spilling request and waken up immediately, the spilling
455
    // dependency will not block this task and we should just run here.
456
35
    if (!_block->empty()) {
457
0
        LOG(INFO) << "Query: " << print_id(query_id) << " has pending block, size: "
458
0
                  << PrettyPrinter::print_bytes(_block->allocated_bytes());
459
0
        DCHECK(_spilling);
460
0
    }
461
462
35
    SCOPED_TIMER(_task_profile->total_time_counter());
463
35
    SCOPED_TIMER(_exec_timer);
464
465
35
    if (!_wake_up_early) {
466
35
        RETURN_IF_ERROR(_prepare());
467
35
    }
468
35
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::execute", {
469
35
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task execute failed");
470
35
        return status;
471
35
    });
472
    // `_wake_up_early` must be after `_wait_to_start()`
473
35
    if (_wait_to_start() || _wake_up_early) {
474
2
        return Status::OK();
475
2
    }
476
33
    RETURN_IF_ERROR(_prepare());
477
478
    // The status must be runnable
479
33
    if (!_opened && !fragment_context->is_canceled()) {
480
13
        DBUG_EXECUTE_IF("PipelineTask::execute.open_sleep", {
481
13
            auto required_pipeline_id =
482
13
                    DebugPoints::instance()->get_debug_param_or_default<int32_t>(
483
13
                            "PipelineTask::execute.open_sleep", "pipeline_id", -1);
484
13
            auto required_task_id = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
485
13
                    "PipelineTask::execute.open_sleep", "task_id", -1);
486
13
            if (required_pipeline_id == pipeline_id() && required_task_id == task_id()) {
487
13
                LOG(WARNING) << "PipelineTask::execute.open_sleep sleep 5s";
488
13
                sleep(5);
489
13
            }
490
13
        });
491
492
13
        SCOPED_RAW_TIMER(&time_spent);
493
13
        RETURN_IF_ERROR(_open());
494
13
    }
495
496
531k
    while (!fragment_context->is_canceled()) {
497
531k
        SCOPED_RAW_TIMER(&time_spent);
498
531k
        Defer defer {[&]() {
499
            // If this run is pended by a spilling request, the block will be output in next run.
500
531k
            if (!_spilling) {
501
529k
                _block->clear_column_data(_root->row_desc().num_materialized_slots());
502
529k
            }
503
531k
        }};
504
        // `_wake_up_early` must be after `_is_blocked()`
505
531k
        if (_is_blocked() || _wake_up_early) {
506
17
            return Status::OK();
507
17
        }
508
509
        /// When a task is cancelled,
510
        /// its blocking state will be cleared and it will transition to a ready state (though it is not truly ready).
511
        /// Here, checking whether it is cancelled to prevent tasks in a blocking state from being re-executed.
512
531k
        if (fragment_context->is_canceled()) {
513
0
            break;
514
0
        }
515
516
531k
        if (time_spent > _exec_time_slice) {
517
4
            COUNTER_UPDATE(_yield_counts, 1);
518
4
            break;
519
4
        }
520
531k
        auto* block = _block.get();
521
522
531k
        DBUG_EXECUTE_IF("fault_inject::PipelineXTask::executing", {
523
531k
            Status status =
524
531k
                    Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task executing failed");
525
531k
            return status;
526
531k
        });
527
528
        // `_sink->is_finished(_state)` means sink operator should be finished
529
531k
        if (_sink->is_finished(_state)) {
530
1
            set_wake_up_early();
531
1
            return Status::OK();
532
1
        }
533
534
        // `_dry_run` means sink operator need no more data
535
531k
        _eos = _dry_run || _eos;
536
531k
        _spilling = false;
537
531k
        auto workload_group = _state->workload_group();
538
        // If last run is pended by a spilling request, `_block` is produced with some rows in last
539
        // run, so we will resume execution using the block.
540
531k
        if (!_eos && _block->empty()) {
541
530k
            SCOPED_TIMER(_get_block_timer);
542
530k
            if (_state->low_memory_mode()) {
543
0
                _sink->set_low_memory_mode(_state);
544
0
                _root->set_low_memory_mode(_state);
545
0
            }
546
530k
            DEFER_RELEASE_RESERVED();
547
530k
            _get_block_counter->update(1);
548
530k
            const auto reserve_size = _root->get_reserve_mem_size(_state);
549
530k
            _root->reset_reserve_mem_size(_state);
550
551
530k
            if (workload_group &&
552
530k
                _state->get_query_ctx()
553
52.9k
                        ->resource_ctx()
554
52.9k
                        ->task_controller()
555
52.9k
                        ->is_enable_reserve_memory() &&
556
530k
                reserve_size > 0) {
557
1.05k
                if (!_try_to_reserve_memory(reserve_size, _root)) {
558
1.05k
                    continue;
559
1.05k
                }
560
1.05k
            }
561
562
529k
            bool eos = false;
563
529k
            RETURN_IF_ERROR(_root->get_block_after_projects(_state, block, &eos));
564
529k
            RETURN_IF_ERROR(block->check_type_and_column());
565
529k
            _eos = eos;
566
529k
        }
567
568
530k
        if (!_block->empty() || _eos) {
569
925
            SCOPED_TIMER(_sink_timer);
570
925
            Status status = Status::OK();
571
925
            DEFER_RELEASE_RESERVED();
572
925
            if (_state->get_query_ctx()
573
925
                        ->resource_ctx()
574
925
                        ->task_controller()
575
925
                        ->is_enable_reserve_memory() &&
576
925
                workload_group && !(_wake_up_early || _dry_run)) {
577
909
                const auto sink_reserve_size = _sink->get_reserve_mem_size(_state, _eos);
578
909
                if (sink_reserve_size > 0 &&
579
909
                    !_try_to_reserve_memory(sink_reserve_size, _sink.get())) {
580
908
                    continue;
581
908
                }
582
909
            }
583
584
17
            if (_eos) {
585
11
                RETURN_IF_ERROR(close(Status::OK(), false));
586
11
            }
587
588
17
            DBUG_EXECUTE_IF("PipelineTask::execute.sink_eos_sleep", {
589
17
                auto required_pipeline_id =
590
17
                        DebugPoints::instance()->get_debug_param_or_default<int32_t>(
591
17
                                "PipelineTask::execute.sink_eos_sleep", "pipeline_id", -1);
592
17
                auto required_task_id =
593
17
                        DebugPoints::instance()->get_debug_param_or_default<int32_t>(
594
17
                                "PipelineTask::execute.sink_eos_sleep", "task_id", -1);
595
17
                if (required_pipeline_id == pipeline_id() && required_task_id == task_id()) {
596
17
                    LOG(WARNING) << "PipelineTask::execute.sink_eos_sleep sleep 10s";
597
17
                    sleep(10);
598
17
                }
599
17
            });
600
601
17
            DBUG_EXECUTE_IF("PipelineTask::execute.terminate", {
602
17
                if (_eos) {
603
17
                    auto required_pipeline_id =
604
17
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
605
17
                                    "PipelineTask::execute.terminate", "pipeline_id", -1);
606
17
                    auto required_task_id =
607
17
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
608
17
                                    "PipelineTask::execute.terminate", "task_id", -1);
609
17
                    auto required_fragment_id =
610
17
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
611
17
                                    "PipelineTask::execute.terminate", "fragment_id", -1);
612
17
                    if (required_pipeline_id == pipeline_id() && required_task_id == task_id() &&
613
17
                        fragment_context->get_fragment_id() == required_fragment_id) {
614
17
                        _wake_up_early = true;
615
17
                        terminate();
616
17
                    } else if (required_pipeline_id == pipeline_id() &&
617
17
                               fragment_context->get_fragment_id() == required_fragment_id) {
618
17
                        LOG(WARNING) << "PipelineTask::execute.terminate sleep 5s";
619
17
                        sleep(5);
620
17
                    }
621
17
                }
622
17
            });
623
17
            RETURN_IF_ERROR(block->check_type_and_column());
624
17
            status = _sink->sink(_state, block, _eos);
625
626
17
            if (status.is<ErrorCode::END_OF_FILE>()) {
627
1
                set_wake_up_early();
628
1
                return Status::OK();
629
16
            } else if (!status) {
630
0
                return status;
631
0
            }
632
633
16
            if (_eos) { // just return, the scheduler will do finish work
634
10
                return Status::OK();
635
10
            }
636
16
        }
637
530k
    }
638
639
4
    RETURN_IF_ERROR(_state->get_query_ctx()->get_pipe_exec_scheduler()->submit(shared_from_this()));
640
4
    return Status::OK();
641
4
}
642
643
0
Status PipelineTask::do_revoke_memory(const std::shared_ptr<SpillContext>& spill_context) {
644
0
    auto fragment_context = _fragment_context.lock();
645
0
    if (!fragment_context) {
646
0
        return Status::InternalError("Fragment already finished! Query: {}", print_id(_query_id));
647
0
    }
648
649
0
    SCOPED_ATTACH_TASK(_state);
650
0
    ThreadCpuStopWatch cpu_time_stop_watch;
651
0
    cpu_time_stop_watch.start();
652
0
    Defer running_defer {[&]() {
653
0
        int64_t delta_cpu_time = cpu_time_stop_watch.elapsed_time();
654
0
        _task_cpu_timer->update(delta_cpu_time);
655
0
        fragment_context->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(
656
0
                delta_cpu_time);
657
658
        // If task is woke up early, we should terminate all operators, and this task could be closed immediately.
659
0
        if (_wake_up_early) {
660
0
            terminate();
661
0
            THROW_IF_ERROR(_root->terminate(_state));
662
0
            THROW_IF_ERROR(_sink->terminate(_state));
663
0
            _eos = true;
664
0
        }
665
0
    }};
666
667
0
    return _sink->revoke_memory(_state, spill_context);
668
0
}
669
670
1.96k
bool PipelineTask::_try_to_reserve_memory(const size_t reserve_size, OperatorBase* op) {
671
1.96k
    auto st = thread_context()->thread_mem_tracker_mgr->try_reserve(reserve_size);
672
    // If reserve memory failed and the query is not enable spill, just disable reserve memory(this will enable
673
    // memory hard limit check, and will cancel the query if allocate memory failed) and let it run.
674
1.96k
    if (!st.ok() && !_state->enable_spill()) {
675
2
        LOG(INFO) << print_id(_query_id) << " reserve memory failed due to " << st
676
2
                  << ", and it is not enable spill, disable reserve memory and let it run";
677
2
        _state->get_query_ctx()->resource_ctx()->task_controller()->disable_reserve_memory();
678
2
        return true;
679
2
    }
680
1.96k
    COUNTER_UPDATE(_memory_reserve_times, 1);
681
1.96k
    auto sink_revocable_mem_size = _sink->revocable_mem_size(_state);
682
1.96k
    if (st.ok() && _state->enable_force_spill() && _sink->is_spillable() &&
683
1.96k
        sink_revocable_mem_size >= vectorized::SpillStream::MIN_SPILL_WRITE_BATCH_MEM) {
684
0
        st = Status(ErrorCode::QUERY_MEMORY_EXCEEDED, "Force Spill");
685
0
    }
686
1.96k
    if (!st.ok()) {
687
1.96k
        COUNTER_UPDATE(_memory_reserve_failed_times, 1);
688
1.96k
        auto debug_msg = fmt::format(
689
1.96k
                "Query: {} , try to reserve: {}, operator name: {}, operator "
690
1.96k
                "id: {}, task id: {}, root revocable mem size: {}, sink revocable mem"
691
1.96k
                "size: {}, failed: {}",
692
1.96k
                print_id(_query_id), PrettyPrinter::print_bytes(reserve_size), op->get_name(),
693
1.96k
                op->node_id(), _state->task_id(),
694
1.96k
                PrettyPrinter::print_bytes(op->revocable_mem_size(_state)),
695
1.96k
                PrettyPrinter::print_bytes(sink_revocable_mem_size), st.to_string());
696
        // PROCESS_MEMORY_EXCEEDED error msg already contains process_mem_log_str
697
1.96k
        if (!st.is<ErrorCode::PROCESS_MEMORY_EXCEEDED>()) {
698
1.96k
            debug_msg +=
699
1.96k
                    fmt::format(", debug info: {}", GlobalMemoryArbitrator::process_mem_log_str());
700
1.96k
        }
701
        // If sink has enough revocable memory, trigger revoke memory
702
1.96k
        LOG(INFO) << fmt::format(
703
1.96k
                "Query: {} sink: {}, node id: {}, task id: "
704
1.96k
                "{}, revocable mem size: {}",
705
1.96k
                print_id(_query_id), _sink->get_name(), _sink->node_id(), _state->task_id(),
706
1.96k
                PrettyPrinter::print_bytes(sink_revocable_mem_size));
707
1.96k
        ExecEnv::GetInstance()->workload_group_mgr()->add_paused_query(
708
1.96k
                _state->get_query_ctx()->resource_ctx()->shared_from_this(), reserve_size, st);
709
1.96k
        _spilling = true;
710
1.96k
        return false;
711
        // !!! Attention:
712
        // In the past, if reserve failed, not add this query to paused list, because it is very small, will not
713
        // consume a lot of memory. But need set low memory mode to indicate that the system should
714
        // not use too much memory.
715
        // But if we only set _state->get_query_ctx()->set_low_memory_mode() here, and return true, the query will
716
        // continue to run and not blocked, and this reserve maybe the last block of join sink opertorator, and it will
717
        // build hash table directly and will consume a lot of memory. So that should return false directly.
718
        // TODO: we should using a global system buffer management logic to deal with low memory mode.
719
        /**
720
        if (sink_revocable_mem_size >= vectorized::SpillStream::MIN_SPILL_WRITE_BATCH_MEM) {
721
            LOG(INFO) << fmt::format(
722
                    "Query: {} sink: {}, node id: {}, task id: "
723
                    "{}, revocable mem size: {}",
724
                    print_id(_query_id), _sink->get_name(), _sink->node_id(), _state->task_id(),
725
                    PrettyPrinter::print_bytes(sink_revocable_mem_size));
726
            ExecEnv::GetInstance()->workload_group_mgr()->add_paused_query(
727
                    _state->get_query_ctx()->resource_ctx()->shared_from_this(), reserve_size, st);
728
            _spilling = true;
729
            return false;
730
        } else {
731
            _state->get_query_ctx()->set_low_memory_mode();
732
        } */
733
1.96k
    }
734
0
    return true;
735
1.96k
}
736
737
248k
void PipelineTask::stop_if_finished() {
738
248k
    auto fragment = _fragment_context.lock();
739
248k
    if (!fragment) {
740
0
        return;
741
0
    }
742
248k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(fragment->get_query_ctx()->query_mem_tracker());
743
248k
    if (auto sink = _sink) {
744
248k
        if (sink->is_finished(_state)) {
745
1
            set_wake_up_early();
746
1
            terminate();
747
1
        }
748
248k
    }
749
248k
}
750
751
1
Status PipelineTask::finalize() {
752
1
    auto fragment = _fragment_context.lock();
753
1
    if (!fragment) {
754
0
        return Status::OK();
755
0
    }
756
1
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(fragment->get_query_ctx()->query_mem_tracker());
757
1
    RETURN_IF_ERROR(_state_transition(State::FINALIZED));
758
1
    std::unique_lock<std::mutex> lc(_dependency_lock);
759
1
    _sink_shared_state.reset();
760
1
    _op_shared_states.clear();
761
1
    _shared_state_map.clear();
762
1
    _block.reset();
763
1
    _operators.clear();
764
1
    _sink.reset();
765
1
    _pipeline.reset();
766
1
    return Status::OK();
767
1
}
768
769
17
Status PipelineTask::close(Status exec_status, bool close_sink) {
770
17
    int64_t close_ns = 0;
771
17
    Status s;
772
17
    {
773
17
        SCOPED_RAW_TIMER(&close_ns);
774
17
        if (close_sink) {
775
6
            s = _sink->close(_state, exec_status);
776
6
        }
777
21
        for (auto& op : _operators) {
778
21
            auto tem = op->close(_state);
779
21
            if (!tem.ok() && s.ok()) {
780
0
                s = tem;
781
0
            }
782
21
        }
783
17
    }
784
17
    if (_opened) {
785
17
        COUNTER_UPDATE(_close_timer, close_ns);
786
17
        COUNTER_UPDATE(_task_profile->total_time_counter(), close_ns);
787
17
    }
788
789
17
    if (close_sink && _opened) {
790
6
        _task_profile->add_info_string("WakeUpEarly", std::to_string(_wake_up_early.load()));
791
6
        _fresh_profile_counter();
792
6
    }
793
794
17
    if (close_sink) {
795
6
        RETURN_IF_ERROR(_state_transition(State::FINISHED));
796
6
    }
797
17
    return s;
798
17
}
799
800
33.9k
std::string PipelineTask::debug_string() {
801
33.9k
    fmt::memory_buffer debug_string_buffer;
802
803
33.9k
    fmt::format_to(debug_string_buffer, "QueryId: {}\n", print_id(_query_id));
804
33.9k
    fmt::format_to(debug_string_buffer, "InstanceId: {}\n",
805
33.9k
                   print_id(_state->fragment_instance_id()));
806
807
33.9k
    fmt::format_to(debug_string_buffer,
808
33.9k
                   "PipelineTask[id = {}, open = {}, eos = {}, state = {}, dry run = "
809
33.9k
                   "{}, _wake_up_early = {}, _wake_up_by = {}, time elapsed since last state "
810
33.9k
                   "changing = {}s, spilling = {}, is running = {}]",
811
33.9k
                   _index, _opened, _eos, _to_string(_exec_state), _dry_run, _wake_up_early.load(),
812
33.9k
                   _wake_by, _state_change_watcher.elapsed_time() / NANOS_PER_SEC, _spilling,
813
33.9k
                   is_running());
814
33.9k
    std::unique_lock<std::mutex> lc(_dependency_lock);
815
33.9k
    auto* cur_blocked_dep = _blocked_dep;
816
33.9k
    auto fragment = _fragment_context.lock();
817
33.9k
    if (is_finalized() || !fragment) {
818
5
        fmt::format_to(debug_string_buffer, " pipeline name = {}", _pipeline_name);
819
5
        return fmt::to_string(debug_string_buffer);
820
5
    }
821
33.9k
    auto elapsed = fragment->elapsed_time() / NANOS_PER_SEC;
822
33.9k
    fmt::format_to(debug_string_buffer, " elapse time = {}s, block dependency = [{}]\n", elapsed,
823
33.9k
                   cur_blocked_dep && !is_finalized() ? cur_blocked_dep->debug_string() : "NULL");
824
825
33.9k
    if (_state && _state->local_runtime_filter_mgr()) {
826
0
        fmt::format_to(debug_string_buffer, "local_runtime_filter_mgr: [{}]\n",
827
0
                       _state->local_runtime_filter_mgr()->debug_string());
828
0
    }
829
830
33.9k
    fmt::format_to(debug_string_buffer, "operators: ");
831
67.8k
    for (size_t i = 0; i < _operators.size(); i++) {
832
33.9k
        fmt::format_to(debug_string_buffer, "\n{}",
833
33.9k
                       _opened && !is_finalized()
834
33.9k
                               ? _operators[i]->debug_string(_state, cast_set<int>(i))
835
33.9k
                               : _operators[i]->debug_string(cast_set<int>(i)));
836
33.9k
    }
837
33.9k
    fmt::format_to(debug_string_buffer, "\n{}\n",
838
33.9k
                   _opened && !is_finalized()
839
33.9k
                           ? _sink->debug_string(_state, cast_set<int>(_operators.size()))
840
33.9k
                           : _sink->debug_string(cast_set<int>(_operators.size())));
841
842
33.9k
    fmt::format_to(debug_string_buffer, "\nRead Dependency Information: \n");
843
844
33.9k
    size_t i = 0;
845
67.7k
    for (; i < _read_dependencies.size(); i++) {
846
67.7k
        for (size_t j = 0; j < _read_dependencies[i].size(); j++) {
847
33.8k
            fmt::format_to(debug_string_buffer, "{}. {}\n", i,
848
33.8k
                           _read_dependencies[i][j]->debug_string(cast_set<int>(i) + 1));
849
33.8k
        }
850
33.8k
    }
851
852
33.9k
    fmt::format_to(debug_string_buffer, "{}. {}\n", i,
853
33.9k
                   _memory_sufficient_dependency->debug_string(cast_set<int>(i++)));
854
855
33.9k
    fmt::format_to(debug_string_buffer, "\nWrite Dependency Information: \n");
856
67.7k
    for (size_t j = 0; j < _write_dependencies.size(); j++, i++) {
857
33.8k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
858
33.8k
                       _write_dependencies[j]->debug_string(cast_set<int>(j) + 1));
859
33.8k
    }
860
861
33.9k
    fmt::format_to(debug_string_buffer, "\nExecution Dependency Information: \n");
862
101k
    for (size_t j = 0; j < _execution_dependencies.size(); j++, i++) {
863
67.8k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
864
67.8k
                       _execution_dependencies[j]->debug_string(cast_set<int>(i) + 1));
865
67.8k
    }
866
867
33.9k
    fmt::format_to(debug_string_buffer, "Finish Dependency Information: \n");
868
101k
    for (size_t j = 0; j < _finish_dependencies.size(); j++, i++) {
869
67.7k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
870
67.7k
                       _finish_dependencies[j]->debug_string(cast_set<int>(i) + 1));
871
67.7k
    }
872
33.9k
    return fmt::to_string(debug_string_buffer);
873
33.9k
}
874
875
0
size_t PipelineTask::get_revocable_size() const {
876
0
    if (!_opened || is_finalized() || _running || (_eos && !_spilling)) {
877
0
        return 0;
878
0
    }
879
880
0
    return _sink->revocable_mem_size(_state);
881
0
}
882
883
0
Status PipelineTask::revoke_memory(const std::shared_ptr<SpillContext>& spill_context) {
884
0
    DCHECK(spill_context);
885
0
    if (is_finalized()) {
886
0
        spill_context->on_task_finished();
887
0
        VLOG_DEBUG << "Query: " << print_id(_state->query_id()) << ", task: " << ((void*)this)
888
0
                   << " finalized";
889
0
        return Status::OK();
890
0
    }
891
892
0
    const auto revocable_size = _sink->revocable_mem_size(_state);
893
0
    if (revocable_size >= vectorized::SpillStream::MIN_SPILL_WRITE_BATCH_MEM) {
894
0
        auto revokable_task = std::make_shared<RevokableTask>(shared_from_this(), spill_context);
895
0
        RETURN_IF_ERROR(_state->get_query_ctx()->get_pipe_exec_scheduler()->submit(revokable_task));
896
0
    } else {
897
0
        spill_context->on_task_finished();
898
0
        LOG(INFO) << "Query: " << print_id(_state->query_id()) << ", task: " << ((void*)this)
899
0
                  << " has not enough data to revoke: " << revocable_size;
900
0
    }
901
0
    return Status::OK();
902
0
}
903
904
25
Status PipelineTask::wake_up(Dependency* dep) {
905
    // call by dependency
906
25
    DCHECK_EQ(_blocked_dep, dep) << "dep : " << dep->debug_string(0) << "task: " << debug_string();
907
25
    _blocked_dep = nullptr;
908
25
    auto holder = std::dynamic_pointer_cast<PipelineTask>(shared_from_this());
909
25
    RETURN_IF_ERROR(_state_transition(PipelineTask::State::RUNNABLE));
910
25
    RETURN_IF_ERROR(_state->get_query_ctx()->get_pipe_exec_scheduler()->submit(holder));
911
25
    return Status::OK();
912
25
}
913
914
98
Status PipelineTask::_state_transition(State new_state) {
915
98
    if (_exec_state != new_state) {
916
93
        _state_change_watcher.reset();
917
93
        _state_change_watcher.start();
918
93
    }
919
98
    _task_profile->add_info_string("TaskState", _to_string(new_state));
920
98
    _task_profile->add_info_string("BlockedByDependency", _blocked_dep ? _blocked_dep->name() : "");
921
98
    if (!LEGAL_STATE_TRANSITION[(int)new_state].contains(_exec_state)) {
922
17
        return Status::InternalError(
923
17
                "Task state transition from {} to {} is not allowed! Task info: {}",
924
17
                _to_string(_exec_state), _to_string(new_state), debug_string());
925
17
    }
926
81
    _exec_state = new_state;
927
81
    return Status::OK();
928
98
}
929
930
#include "common/compile_check_end.h"
931
} // namespace doris::pipeline