Coverage Report

Created: 2026-03-27 23:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/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 "exec/pipeline/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 "core/block/block.h"
33
#include "exec/operator/exchange_source_operator.h"
34
#include "exec/operator/operator.h"
35
#include "exec/operator/rec_cte_source_operator.h"
36
#include "exec/operator/scan_operator.h"
37
#include "exec/pipeline/dependency.h"
38
#include "exec/pipeline/pipeline.h"
39
#include "exec/pipeline/pipeline_fragment_context.h"
40
#include "exec/pipeline/revokable_task.h"
41
#include "exec/pipeline/task_queue.h"
42
#include "exec/pipeline/task_scheduler.h"
43
#include "exec/spill/spill_file.h"
44
#include "runtime/descriptors.h"
45
#include "runtime/exec_env.h"
46
#include "runtime/query_context.h"
47
#include "runtime/runtime_profile.h"
48
#include "runtime/runtime_profile_counter_names.h"
49
#include "runtime/thread_context.h"
50
#include "runtime/workload_group/workload_group_manager.h"
51
#include "util/defer_op.h"
52
#include "util/mem_info.h"
53
#include "util/uid_util.h"
54
55
namespace doris {
56
class RuntimeState;
57
} // namespace doris
58
59
namespace doris {
60
#include "common/compile_check_begin.h"
61
62
PipelineTask::PipelineTask(PipelinePtr& pipeline, uint32_t task_id, RuntimeState* state,
63
                           std::shared_ptr<PipelineFragmentContext> fragment_context,
64
                           RuntimeProfile* parent_profile,
65
                           std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
66
                                                   std::vector<std::shared_ptr<Dependency>>>>
67
                                   shared_state_map,
68
                           int task_idx)
69
        :
70
#ifdef BE_TEST
71
72.1k
          _query_id(fragment_context ? fragment_context->get_query_id() : TUniqueId()),
72
#else
73
          _query_id(fragment_context->get_query_id()),
74
#endif
75
72.1k
          _index(task_id),
76
72.1k
          _pipeline(pipeline),
77
72.1k
          _opened(false),
78
72.1k
          _state(state),
79
72.1k
          _fragment_context(fragment_context),
80
72.1k
          _parent_profile(parent_profile),
81
72.1k
          _operators(pipeline->operators()),
82
72.1k
          _source(_operators.front().get()),
83
72.1k
          _root(_operators.back().get()),
84
72.1k
          _sink(pipeline->sink_shared_pointer()),
85
72.1k
          _shared_state_map(std::move(shared_state_map)),
86
72.1k
          _task_idx(task_idx),
87
72.1k
          _memory_sufficient_dependency(state->get_query_ctx()->get_memory_sufficient_dependency()),
88
72.1k
          _pipeline_name(_pipeline->name()) {
89
#ifndef BE_TEST
90
    _query_mem_tracker = fragment_context->get_query_ctx()->query_mem_tracker();
91
#endif
92
72.1k
    _execution_dependencies.push_back(state->get_query_ctx()->get_execution_dependency());
93
72.1k
    if (!_shared_state_map.contains(_sink->dests_id().front())) {
94
72.1k
        auto shared_state = _sink->create_shared_state();
95
72.1k
        if (shared_state) {
96
35
            _sink_shared_state = shared_state;
97
35
        }
98
72.1k
    }
99
72.1k
}
100
101
72.1k
PipelineTask::~PipelineTask() {
102
72.1k
    auto reset_member = [&]() {
103
72.1k
        _shared_state_map.clear();
104
72.1k
        _sink_shared_state.reset();
105
72.1k
        _op_shared_states.clear();
106
72.1k
        _sink.reset();
107
72.1k
        _operators.clear();
108
72.1k
        _block.reset();
109
72.1k
        _pipeline.reset();
110
72.1k
    };
111
// PipelineTask is also hold by task queue( https://github.com/apache/doris/pull/49753),
112
// so that it maybe the last one to be destructed.
113
// But pipeline task hold some objects, like operators, shared state, etc. So that should release
114
// memory manually.
115
#ifndef BE_TEST
116
    if (_query_mem_tracker) {
117
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_query_mem_tracker);
118
        reset_member();
119
        return;
120
    }
121
#endif
122
72.1k
    reset_member();
123
72.1k
}
124
125
Status PipelineTask::prepare(const std::vector<TScanRangeParams>& scan_range, const int sender_id,
126
21
                             const TDataSink& tsink) {
127
21
    DCHECK(_sink);
128
21
    _init_profile();
129
21
    SCOPED_TIMER(_task_profile->total_time_counter());
130
21
    SCOPED_CPU_TIMER(_task_cpu_timer);
131
21
    SCOPED_TIMER(_prepare_timer);
132
21
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::prepare", {
133
21
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task prepare failed");
134
21
        return status;
135
21
    });
136
21
    {
137
        // set sink local state
138
21
        LocalSinkStateInfo info {_task_idx,         _task_profile.get(),
139
21
                                 sender_id,         get_sink_shared_state().get(),
140
21
                                 _shared_state_map, tsink};
141
21
        RETURN_IF_ERROR(_sink->setup_local_state(_state, info));
142
21
    }
143
144
21
    _scan_ranges = scan_range;
145
21
    auto* parent_profile = _state->get_sink_local_state()->operator_profile();
146
147
44
    for (int op_idx = cast_set<int>(_operators.size() - 1); op_idx >= 0; op_idx--) {
148
23
        auto& op = _operators[op_idx];
149
23
        LocalStateInfo info {parent_profile, _scan_ranges, get_op_shared_state(op->operator_id()),
150
23
                             _shared_state_map, _task_idx};
151
23
        RETURN_IF_ERROR(op->setup_local_state(_state, info));
152
23
        parent_profile = _state->get_local_state(op->operator_id())->operator_profile();
153
23
    }
154
21
    {
155
21
        const auto& deps =
156
21
                _state->get_local_state(_source->operator_id())->execution_dependencies();
157
21
        std::unique_lock<std::mutex> lc(_dependency_lock);
158
21
        std::copy(deps.begin(), deps.end(),
159
21
                  std::inserter(_execution_dependencies, _execution_dependencies.end()));
160
21
    }
161
21
    if (auto fragment = _fragment_context.lock()) {
162
20
        if (fragment->get_query_ctx()->is_cancelled()) {
163
0
            terminate();
164
0
            return fragment->get_query_ctx()->exec_status();
165
0
        }
166
20
    } else {
167
1
        return Status::InternalError("Fragment already finished! Query: {}", print_id(_query_id));
168
1
    }
169
20
    _block = doris::Block::create_unique();
170
20
    return _state_transition(State::RUNNABLE);
171
21
}
172
173
14
Status PipelineTask::_extract_dependencies() {
174
14
    std::vector<std::vector<Dependency*>> read_dependencies;
175
14
    std::vector<Dependency*> write_dependencies;
176
14
    std::vector<Dependency*> finish_dependencies;
177
14
    read_dependencies.resize(_operators.size());
178
14
    size_t i = 0;
179
16
    for (auto& op : _operators) {
180
16
        auto* local_state = _state->get_local_state(op->operator_id());
181
16
        DCHECK(local_state);
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
21
void PipelineTask::_init_profile() {
235
21
    _task_profile = std::make_unique<RuntimeProfile>(fmt::format("PipelineTask(index={})", _index));
236
21
    _parent_profile->add_child(_task_profile.get(), true, nullptr);
237
21
    _task_cpu_timer = ADD_TIMER(_task_profile, profile::TASK_CPU_TIME);
238
239
21
    static const char* exec_time = profile::EXECUTE_TIME;
240
21
    _exec_timer = ADD_TIMER(_task_profile, exec_time);
241
21
    _prepare_timer = ADD_CHILD_TIMER(_task_profile, profile::PREPARE_TIME, exec_time);
242
21
    _open_timer = ADD_CHILD_TIMER(_task_profile, profile::OPEN_TIME, exec_time);
243
21
    _get_block_timer = ADD_CHILD_TIMER(_task_profile, profile::GET_BLOCK_TIME, exec_time);
244
21
    _get_block_counter = ADD_COUNTER(_task_profile, profile::GET_BLOCK_COUNTER, TUnit::UNIT);
245
21
    _sink_timer = ADD_CHILD_TIMER(_task_profile, profile::SINK_TIME, exec_time);
246
21
    _close_timer = ADD_CHILD_TIMER(_task_profile, profile::CLOSE_TIME, exec_time);
247
248
21
    _wait_worker_timer = ADD_TIMER_WITH_LEVEL(_task_profile, profile::WAIT_WORKER_TIME, 1);
249
250
21
    _schedule_counts = ADD_COUNTER(_task_profile, profile::NUM_SCHEDULE_TIMES, TUnit::UNIT);
251
21
    _yield_counts = ADD_COUNTER(_task_profile, profile::NUM_YIELD_TIMES, TUnit::UNIT);
252
21
    _core_change_times = ADD_COUNTER(_task_profile, profile::CORE_CHANGE_TIMES, TUnit::UNIT);
253
21
    _memory_reserve_times = ADD_COUNTER(_task_profile, profile::MEMORY_RESERVE_TIMES, TUnit::UNIT);
254
21
    _memory_reserve_failed_times =
255
21
            ADD_COUNTER(_task_profile, profile::MEMORY_RESERVE_FAILED_TIMES, TUnit::UNIT);
256
21
}
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
861k
bool PipelineTask::_is_blocked() {
326
    // `_dry_run = true` means we do not need data from source operator.
327
861k
    if (!_dry_run) {
328
1.72M
        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
861k
            for (auto* dep : _read_dependencies[i]) {
331
861k
                if (dep->is_blocked_by(shared_from_this())) {
332
15
                    return true;
333
15
                }
334
861k
            }
335
            // If all dependencies are ready for this operator, we can execute this task if no datum is needed from upstream operators.
336
861k
            if (!_operators[i]->need_more_input_data(_state)) {
337
2
                break;
338
2
            }
339
861k
        }
340
861k
    }
341
861k
    return _memory_sufficient_dependency->is_blocked_by(shared_from_this()) ||
342
861k
           std::ranges::any_of(_write_dependencies, [&](Dependency* dep) -> bool {
343
861k
               return dep->is_blocked_by(shared_from_this());
344
861k
           });
345
861k
}
346
347
8
void PipelineTask::terminate() {
348
    // We use a lock to assure all dependencies are not deconstructed here.
349
8
    std::unique_lock<std::mutex> lc(_dependency_lock);
350
8
    auto fragment = _fragment_context.lock();
351
8
    if (!is_finalized() && fragment) {
352
8
        try {
353
8
            DCHECK(_wake_up_early || fragment->is_canceled());
354
8
            std::ranges::for_each(_write_dependencies,
355
8
                                  [&](Dependency* dep) { dep->set_always_ready(); });
356
8
            std::ranges::for_each(_finish_dependencies,
357
14
                                  [&](Dependency* dep) { dep->set_always_ready(); });
358
8
            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
8
            std::ranges::for_each(_execution_dependencies,
363
16
                                  [&](Dependency* dep) { dep->set_ready(); });
364
8
            _memory_sufficient_dependency->set_ready();
365
8
        } catch (const doris::Exception& e) {
366
0
            LOG(WARNING) << "Terminate failed: " << e.code() << ", " << e.to_string();
367
0
        }
368
8
    }
369
8
}
370
371
// When current memory pressure is low, memory usage may increase significantly in the next
372
// operator run, while there is no revocable memory available for spilling.
373
// Trigger memory revoking when pressure is high and revocable memory is significant.
374
// Memory pressure is evaluated using two signals:
375
// 1. Query memory usage exceeds a threshold ratio of the query memory limit.
376
// 2. Workload group memory usage reaches the workload group low-watermark threshold.
377
1.54k
bool PipelineTask::_should_trigger_revoking(const size_t reserve_size) const {
378
1.54k
    if (!_state->enable_spill()) {
379
3
        return false;
380
3
    }
381
382
1.54k
    auto query_mem_tracker = _state->get_query_ctx()->query_mem_tracker();
383
1.54k
    auto wg = _state->get_query_ctx()->workload_group();
384
1.54k
    if (!query_mem_tracker || !wg) {
385
1.53k
        return false;
386
1.53k
    }
387
388
8
    const auto parallelism = std::max(1, _pipeline->num_tasks());
389
8
    const auto query_water_mark = 90; // 90%
390
8
    const auto group_mem_limit = wg->memory_limit();
391
8
    auto query_limit = query_mem_tracker->limit();
392
8
    if (query_limit <= 0) {
393
1
        query_limit = group_mem_limit;
394
7
    } else if (query_limit > group_mem_limit && group_mem_limit > 0) {
395
1
        query_limit = group_mem_limit;
396
1
    }
397
398
8
    if (query_limit <= 0) {
399
1
        return false;
400
1
    }
401
402
7
    if ((reserve_size * parallelism) <= (query_limit / 5)) {
403
1
        return false;
404
1
    }
405
406
6
    bool is_high_memory_pressure = false;
407
6
    const auto used_mem = query_mem_tracker->consumption() + reserve_size * parallelism;
408
6
    if (used_mem >= int64_t((double(query_limit) * query_water_mark / 100))) {
409
2
        is_high_memory_pressure = true;
410
2
    }
411
412
6
    if (!is_high_memory_pressure) {
413
4
        bool is_low_watermark;
414
4
        bool is_high_watermark;
415
4
        wg->check_mem_used(&is_low_watermark, &is_high_watermark);
416
4
        is_high_memory_pressure = is_low_watermark || is_high_watermark;
417
4
    }
418
419
6
    if (is_high_memory_pressure) {
420
4
        const auto revocable_size = [&]() {
421
4
            size_t total = _sink->revocable_mem_size(_state);
422
4
            for (const auto& op : _operators) {
423
4
                total += op->revocable_mem_size(_state);
424
4
            }
425
4
            return total;
426
4
        }();
427
428
4
        const auto total_estimated_revocable = revocable_size * parallelism;
429
4
        return total_estimated_revocable >= int64_t(double(query_limit) * 0.2);
430
4
    }
431
432
2
    return false;
433
6
}
434
435
/**
436
 * `_eos` indicates whether the execution phase is done. `done` indicates whether we could close
437
 * this task.
438
 *
439
 * For example,
440
 * 1. if `_eos` is false which means we should continue to get next block so we cannot close (e.g.
441
 *    `done` is false)
442
 * 2. if `_eos` is true which means all blocks from source are exhausted but `_is_pending_finish()`
443
 *    is true which means we should wait for a pending dependency ready (maybe a running rpc), so we
444
 *    cannot close (e.g. `done` is false)
445
 * 3. if `_eos` is true which means all blocks from source are exhausted and `_is_pending_finish()`
446
 *    is false which means we can close immediately (e.g. `done` is true)
447
 * @param done
448
 * @return
449
 */
450
39
Status PipelineTask::execute(bool* done) {
451
39
    if (_exec_state != State::RUNNABLE || _blocked_dep != nullptr) [[unlikely]] {
452
1
#ifdef BE_TEST
453
1
        return Status::InternalError("Pipeline task is not runnable! Task info: {}",
454
1
                                     debug_string());
455
#else
456
        return Status::FatalError("Pipeline task is not runnable! Task info: {}", debug_string());
457
#endif
458
1
    }
459
460
38
    auto fragment_context = _fragment_context.lock();
461
38
    if (!fragment_context) {
462
0
        return Status::InternalError("Fragment already finished! Query: {}", print_id(_query_id));
463
0
    }
464
38
    int64_t time_spent = 0;
465
38
    ThreadCpuStopWatch cpu_time_stop_watch;
466
38
    cpu_time_stop_watch.start();
467
38
    SCOPED_ATTACH_TASK(_state);
468
38
    Defer running_defer {[&]() {
469
38
        int64_t delta_cpu_time = cpu_time_stop_watch.elapsed_time();
470
38
        _task_cpu_timer->update(delta_cpu_time);
471
38
        fragment_context->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(
472
38
                delta_cpu_time);
473
474
        // If task is woke up early, we should terminate all operators, and this task could be closed immediately.
475
38
        if (_wake_up_early) {
476
3
            _eos = true;
477
3
            *done = true;
478
35
        } else if (_eos && !_spilling &&
479
35
                   (fragment_context->is_canceled() || !_is_pending_finish())) {
480
            // Debug point for testing the race condition fix: inject set_wake_up_early() +
481
            // terminate() here to simulate Thread B writing A then B between Thread A's two
482
            // reads of _wake_up_early.
483
11
            DBUG_EXECUTE_IF("PipelineTask::execute.wake_up_early_in_else_if", {
484
11
                set_wake_up_early();
485
11
                terminate();
486
11
            });
487
11
            *done = true;
488
11
        }
489
490
        // NOTE: The terminate() call is intentionally placed AFTER the _is_pending_finish() check
491
        // above, not before. This ordering is critical to avoid a race condition:
492
        //
493
        // Pipeline::make_all_runnable() writes in this order:
494
        //   (A) set_wake_up_early()  ->  (B) terminate() [sets finish_dep._always_ready]
495
        //
496
        // If we checked _wake_up_early (A) before _is_pending_finish() (B), there would be a
497
        // window where Thread A reads _wake_up_early=false, then Thread B writes both A and B,
498
        // then Thread A reads _is_pending_finish()=false (due to _always_ready). Thread A would
499
        // then set *done=true without ever calling operator terminate(), causing close() to run
500
        // on operators that were never properly terminated (e.g. RuntimeFilterProducer still in
501
        // WAITING_FOR_SYNCED_SIZE state when insert() is called).
502
        //
503
        // By reading _is_pending_finish() (B) before the second read of _wake_up_early (A),
504
        // if Thread A observes B's effect (_always_ready=true), it is guaranteed to also observe
505
        // A's effect (_wake_up_early=true) on this second read, ensuring terminate() is called.
506
38
        if (_wake_up_early) {
507
4
            terminate();
508
4
            THROW_IF_ERROR(_root->terminate(_state));
509
4
            THROW_IF_ERROR(_sink->terminate(_state));
510
4
        }
511
38
    }};
512
38
    const auto query_id = _state->query_id();
513
    // If this task is already EOS and block is empty (which means we already output all blocks),
514
    // just return here.
515
38
    if (_eos && !_spilling) {
516
3
        return Status::OK();
517
3
    }
518
    // If this task is blocked by a spilling request and waken up immediately, the spilling
519
    // dependency will not block this task and we should just run here.
520
35
    if (!_block->empty()) {
521
0
        LOG(INFO) << "Query: " << print_id(query_id) << " has pending block, size: "
522
0
                  << PrettyPrinter::print_bytes(_block->allocated_bytes());
523
0
        DCHECK(_spilling);
524
0
    }
525
526
35
    SCOPED_TIMER(_task_profile->total_time_counter());
527
35
    SCOPED_TIMER(_exec_timer);
528
529
35
    if (!_wake_up_early) {
530
35
        RETURN_IF_ERROR(_prepare());
531
35
    }
532
35
    DBUG_EXECUTE_IF("fault_inject::PipelineXTask::execute", {
533
35
        Status status = Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task execute failed");
534
35
        return status;
535
35
    });
536
    // `_wake_up_early` must be after `_wait_to_start()`
537
35
    if (_wait_to_start() || _wake_up_early) {
538
2
        return Status::OK();
539
2
    }
540
33
    RETURN_IF_ERROR(_prepare());
541
542
    // The status must be runnable
543
33
    if (!_opened && !fragment_context->is_canceled()) {
544
13
        DBUG_EXECUTE_IF("PipelineTask::execute.open_sleep", {
545
13
            auto required_pipeline_id =
546
13
                    DebugPoints::instance()->get_debug_param_or_default<int32_t>(
547
13
                            "PipelineTask::execute.open_sleep", "pipeline_id", -1);
548
13
            auto required_task_id = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
549
13
                    "PipelineTask::execute.open_sleep", "task_id", -1);
550
13
            if (required_pipeline_id == pipeline_id() && required_task_id == task_id()) {
551
13
                LOG(WARNING) << "PipelineTask::execute.open_sleep sleep 5s";
552
13
                sleep(5);
553
13
            }
554
13
        });
555
556
13
        SCOPED_RAW_TIMER(&time_spent);
557
13
        RETURN_IF_ERROR(_open());
558
13
    }
559
560
861k
    while (!fragment_context->is_canceled()) {
561
861k
        SCOPED_RAW_TIMER(&time_spent);
562
861k
        Defer defer {[&]() {
563
            // If this run is pended by a spilling request, the block will be output in next run.
564
861k
            if (!_spilling) {
565
859k
                _block->clear_column_data(_root->row_desc().num_materialized_slots());
566
859k
            }
567
861k
        }};
568
        // `_wake_up_early` must be after `_is_blocked()`
569
861k
        if (_is_blocked() || _wake_up_early) {
570
18
            return Status::OK();
571
18
        }
572
573
        /// When a task is cancelled,
574
        /// its blocking state will be cleared and it will transition to a ready state (though it is not truly ready).
575
        /// Here, checking whether it is cancelled to prevent tasks in a blocking state from being re-executed.
576
861k
        if (fragment_context->is_canceled()) {
577
0
            break;
578
0
        }
579
580
861k
        if (time_spent > _exec_time_slice) {
581
4
            COUNTER_UPDATE(_yield_counts, 1);
582
4
            break;
583
4
        }
584
861k
        auto* block = _block.get();
585
586
861k
        DBUG_EXECUTE_IF("fault_inject::PipelineXTask::executing", {
587
861k
            Status status =
588
861k
                    Status::Error<INTERNAL_ERROR>("fault_inject pipeline_task executing failed");
589
861k
            return status;
590
861k
        });
591
592
        // `_sink->is_finished(_state)` means sink operator should be finished
593
861k
        if (_sink->is_finished(_state)) {
594
0
            set_wake_up_early();
595
0
            return Status::OK();
596
0
        }
597
598
        // `_dry_run` means sink operator need no more data
599
861k
        _eos = _dry_run || _eos;
600
861k
        _spilling = false;
601
861k
        auto workload_group = _state->workload_group();
602
        // If last run is pended by a spilling request, `_block` is produced with some rows in last
603
        // run, so we will resume execution using the block.
604
861k
        if (!_eos && _block->empty()) {
605
860k
            SCOPED_TIMER(_get_block_timer);
606
860k
            if (_state->low_memory_mode()) {
607
0
                _sink->set_low_memory_mode(_state);
608
0
                for (auto& op : _operators) {
609
0
                    op->set_low_memory_mode(_state);
610
0
                }
611
0
            }
612
860k
            DEFER_RELEASE_RESERVED();
613
860k
            _get_block_counter->update(1);
614
            // Sum reserve sizes across all operators in this pipeline.
615
            // Each operator reports only its own requirement (non-recursive).
616
860k
            size_t reserve_size = 0;
617
860k
            for (auto& op : _operators) {
618
860k
                reserve_size += op->get_reserve_mem_size(_state);
619
860k
                op->reset_reserve_mem_size(_state);
620
860k
            }
621
860k
            if (workload_group &&
622
860k
                _state->get_query_ctx()
623
45.8k
                        ->resource_ctx()
624
45.8k
                        ->task_controller()
625
45.8k
                        ->is_enable_reserve_memory() &&
626
860k
                reserve_size > 0) {
627
758
                if (_should_trigger_revoking(reserve_size)) {
628
0
                    LOG(INFO) << fmt::format(
629
0
                            "Query: {} sink: {}, node id: {}, task id: {}, reserve size: {} when "
630
0
                            "high memory pressure, try to spill",
631
0
                            print_id(_query_id), _sink->get_name(), _sink->node_id(),
632
0
                            _state->task_id(), reserve_size);
633
0
                    ExecEnv::GetInstance()->workload_group_mgr()->add_paused_query(
634
0
                            _state->get_query_ctx()->resource_ctx()->shared_from_this(),
635
0
                            reserve_size,
636
0
                            Status::Error<ErrorCode::QUERY_MEMORY_EXCEEDED>(
637
0
                                    "high memory pressure, try to spill"));
638
0
                    _spilling = true;
639
0
                    continue;
640
0
                }
641
758
                if (!_try_to_reserve_memory(reserve_size, _root)) {
642
756
                    continue;
643
756
                }
644
758
            }
645
646
859k
            bool eos = false;
647
859k
            RETURN_IF_ERROR(_root->get_block_after_projects(_state, block, &eos));
648
859k
            RETURN_IF_ERROR(block->check_type_and_column());
649
859k
            _eos = eos;
650
859k
        }
651
652
860k
        if (!_block->empty() || _eos) {
653
792
            SCOPED_TIMER(_sink_timer);
654
792
            Status status = Status::OK();
655
792
            DEFER_RELEASE_RESERVED();
656
792
            if (_state->get_query_ctx()
657
792
                        ->resource_ctx()
658
792
                        ->task_controller()
659
792
                        ->is_enable_reserve_memory() &&
660
792
                workload_group && !(_wake_up_early || _dry_run)) {
661
776
                const auto sink_reserve_size = _sink->get_reserve_mem_size(_state, _eos);
662
663
776
                if (sink_reserve_size > 0 && _should_trigger_revoking(sink_reserve_size)) {
664
0
                    LOG(INFO) << fmt::format(
665
0
                            "Query: {} sink: {}, node id: {}, task id: {}, reserve size: {} when "
666
0
                            "high memory pressure, try to spill",
667
0
                            print_id(_query_id), _sink->get_name(), _sink->node_id(),
668
0
                            _state->task_id(), sink_reserve_size);
669
0
                    ExecEnv::GetInstance()->workload_group_mgr()->add_paused_query(
670
0
                            _state->get_query_ctx()->resource_ctx()->shared_from_this(),
671
0
                            sink_reserve_size,
672
0
                            Status::Error<ErrorCode::QUERY_MEMORY_EXCEEDED>(
673
0
                                    "high memory pressure, try to spill"));
674
0
                    _spilling = true;
675
0
                    continue;
676
0
                }
677
678
776
                if (sink_reserve_size > 0 &&
679
776
                    !_try_to_reserve_memory(sink_reserve_size, _sink.get())) {
680
775
                    continue;
681
775
                }
682
776
            }
683
684
17
            DBUG_EXECUTE_IF("PipelineTask::execute.sink_eos_sleep", {
685
17
                auto required_pipeline_id =
686
17
                        DebugPoints::instance()->get_debug_param_or_default<int32_t>(
687
17
                                "PipelineTask::execute.sink_eos_sleep", "pipeline_id", -1);
688
17
                auto required_task_id =
689
17
                        DebugPoints::instance()->get_debug_param_or_default<int32_t>(
690
17
                                "PipelineTask::execute.sink_eos_sleep", "task_id", -1);
691
17
                if (required_pipeline_id == pipeline_id() && required_task_id == task_id()) {
692
17
                    LOG(WARNING) << "PipelineTask::execute.sink_eos_sleep sleep 10s";
693
17
                    sleep(10);
694
17
                }
695
17
            });
696
697
17
            DBUG_EXECUTE_IF("PipelineTask::execute.terminate", {
698
17
                if (_eos) {
699
17
                    auto required_pipeline_id =
700
17
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
701
17
                                    "PipelineTask::execute.terminate", "pipeline_id", -1);
702
17
                    auto required_task_id =
703
17
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
704
17
                                    "PipelineTask::execute.terminate", "task_id", -1);
705
17
                    auto required_fragment_id =
706
17
                            DebugPoints::instance()->get_debug_param_or_default<int32_t>(
707
17
                                    "PipelineTask::execute.terminate", "fragment_id", -1);
708
17
                    if (required_pipeline_id == pipeline_id() && required_task_id == task_id() &&
709
17
                        fragment_context->get_fragment_id() == required_fragment_id) {
710
17
                        _wake_up_early = true;
711
17
                        terminate();
712
17
                    } else if (required_pipeline_id == pipeline_id() &&
713
17
                               fragment_context->get_fragment_id() == required_fragment_id) {
714
17
                        LOG(WARNING) << "PipelineTask::execute.terminate sleep 5s";
715
17
                        sleep(5);
716
17
                    }
717
17
                }
718
17
            });
719
17
            RETURN_IF_ERROR(block->check_type_and_column());
720
17
            status = _sink->sink(_state, block, _eos);
721
722
17
            if (_eos) {
723
11
                if (_sink->reset_to_rerun(_state, _root)) {
724
0
                    _eos = false;
725
11
                } else {
726
11
                    RETURN_IF_ERROR(close(Status::OK(), false));
727
11
                }
728
11
            }
729
730
17
            if (status.is<ErrorCode::END_OF_FILE>()) {
731
1
                set_wake_up_early();
732
1
                return Status::OK();
733
16
            } else if (!status) {
734
0
                return status;
735
0
            }
736
737
16
            if (_eos) { // just return, the scheduler will do finish work
738
10
                return Status::OK();
739
10
            }
740
16
        }
741
860k
    }
742
743
4
    RETURN_IF_ERROR(_state->get_query_ctx()->get_pipe_exec_scheduler()->submit(shared_from_this()));
744
4
    return Status::OK();
745
4
}
746
747
7
Status PipelineTask::do_revoke_memory(const std::shared_ptr<SpillContext>& spill_context) {
748
7
    auto fragment_context = _fragment_context.lock();
749
7
    if (!fragment_context) {
750
1
        return Status::InternalError("Fragment already finished! Query: {}", print_id(_query_id));
751
1
    }
752
753
6
    SCOPED_ATTACH_TASK(_state);
754
6
    ThreadCpuStopWatch cpu_time_stop_watch;
755
6
    cpu_time_stop_watch.start();
756
6
    Defer running_defer {[&]() {
757
6
        int64_t delta_cpu_time = cpu_time_stop_watch.elapsed_time();
758
6
        _task_cpu_timer->update(delta_cpu_time);
759
6
        fragment_context->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(
760
6
                delta_cpu_time);
761
762
        // If task is woke up early, we should terminate all operators, and this task could be closed immediately.
763
6
        if (_wake_up_early) {
764
1
            terminate();
765
1
            THROW_IF_ERROR(_root->terminate(_state));
766
1
            THROW_IF_ERROR(_sink->terminate(_state));
767
1
            _eos = true;
768
1
        }
769
770
        // SpillContext tracks pipeline task count, not operator count.
771
        // Notify completion once after all operators + sink have finished revoking.
772
6
        if (spill_context) {
773
3
            spill_context->on_task_finished();
774
3
        }
775
6
    }};
776
777
    // Revoke memory from every operator that has enough revocable memory,
778
    // then revoke from the sink.
779
6
    for (auto& op : _operators) {
780
6
        if (op->revocable_mem_size(_state) >= SpillFile::MIN_SPILL_WRITE_BATCH_MEM) {
781
2
            RETURN_IF_ERROR(op->revoke_memory(_state));
782
2
        }
783
6
    }
784
785
6
    if (_sink->revocable_mem_size(_state) >= SpillFile::MIN_SPILL_WRITE_BATCH_MEM) {
786
1
        RETURN_IF_ERROR(_sink->revoke_memory(_state));
787
1
    }
788
6
    return Status::OK();
789
6
}
790
791
1.53k
bool PipelineTask::_try_to_reserve_memory(const size_t reserve_size, OperatorBase* op) {
792
1.53k
    auto st = thread_context()->thread_mem_tracker_mgr->try_reserve(reserve_size);
793
    // If reserve memory failed and the query is not enable spill, just disable reserve memory(this will enable
794
    // memory hard limit check, and will cancel the query if allocate memory failed) and let it run.
795
1.53k
    if (!st.ok() && !_state->enable_spill()) {
796
2
        LOG(INFO) << print_id(_query_id) << " reserve memory failed due to " << st
797
2
                  << ", and it is not enable spill, disable reserve memory and let it run";
798
2
        _state->get_query_ctx()->resource_ctx()->task_controller()->disable_reserve_memory();
799
2
        return true;
800
2
    }
801
1.53k
    COUNTER_UPDATE(_memory_reserve_times, 1);
802
803
    // Compute total revocable memory across all operators and the sink.
804
1.53k
    size_t total_revocable_mem_size = 0;
805
1.53k
    size_t operator_max_revocable_mem_size = 0;
806
807
1.53k
    if (!st.ok() || _state->enable_force_spill()) {
808
        // Compute total revocable memory across all operators and the sink.
809
1.53k
        total_revocable_mem_size = _sink->revocable_mem_size(_state);
810
1.53k
        operator_max_revocable_mem_size = total_revocable_mem_size;
811
1.53k
        for (auto& cur_op : _operators) {
812
1.53k
            total_revocable_mem_size += cur_op->revocable_mem_size(_state);
813
1.53k
            operator_max_revocable_mem_size =
814
1.53k
                    std::max(cur_op->revocable_mem_size(_state), operator_max_revocable_mem_size);
815
1.53k
        }
816
1.53k
    }
817
818
    // During enable force spill, other operators like scan opeartor will also try to reserve memory and will failed
819
    // here, if not add this check, it will always paused and resumed again.
820
1.53k
    if (st.ok() && _state->enable_force_spill()) {
821
0
        if (operator_max_revocable_mem_size >= _state->spill_min_revocable_mem()) {
822
0
            st = Status::Error<ErrorCode::QUERY_MEMORY_EXCEEDED>(
823
0
                    "force spill and there is an operator has memory "
824
0
                    "size {} exceeds min mem size {}",
825
0
                    PrettyPrinter::print_bytes(operator_max_revocable_mem_size),
826
0
                    PrettyPrinter::print_bytes(_state->spill_min_revocable_mem()));
827
0
        }
828
0
    }
829
830
1.53k
    if (!st.ok()) {
831
1.53k
        COUNTER_UPDATE(_memory_reserve_failed_times, 1);
832
        // build per-operator revocable memory info string for debugging
833
1.53k
        std::string ops_revocable_info;
834
1.53k
        {
835
1.53k
            fmt::memory_buffer buf;
836
1.53k
            for (auto& cur_op : _operators) {
837
1.53k
                fmt::format_to(buf, "{}({})-> ", cur_op->get_name(),
838
1.53k
                               PrettyPrinter::print_bytes(cur_op->revocable_mem_size(_state)));
839
1.53k
            }
840
1.53k
            if (_sink) {
841
1.53k
                fmt::format_to(buf, "{}({}) ", _sink->get_name(),
842
1.53k
                               PrettyPrinter::print_bytes(_sink->revocable_mem_size(_state)));
843
1.53k
            }
844
1.53k
            ops_revocable_info = fmt::to_string(buf);
845
1.53k
        }
846
847
1.53k
        auto debug_msg = fmt::format(
848
1.53k
                "Query: {} , try to reserve: {}, total revocable mem size: {}, failed reason: {}",
849
1.53k
                print_id(_query_id), PrettyPrinter::print_bytes(reserve_size),
850
1.53k
                PrettyPrinter::print_bytes(total_revocable_mem_size), st.to_string());
851
1.53k
        if (!ops_revocable_info.empty()) {
852
1.53k
            debug_msg += fmt::format(", ops_revocable=[{}]", ops_revocable_info);
853
1.53k
        }
854
        // PROCESS_MEMORY_EXCEEDED error msg already contains process_mem_log_str
855
1.53k
        if (!st.is<ErrorCode::PROCESS_MEMORY_EXCEEDED>()) {
856
1.53k
            debug_msg +=
857
1.53k
                    fmt::format(", debug info: {}", GlobalMemoryArbitrator::process_mem_log_str());
858
1.53k
        }
859
1.53k
        LOG(INFO) << debug_msg;
860
1.53k
        ExecEnv::GetInstance()->workload_group_mgr()->add_paused_query(
861
1.53k
                _state->get_query_ctx()->resource_ctx()->shared_from_this(), reserve_size, st);
862
1.53k
        _spilling = true;
863
1.53k
        return false;
864
1.53k
    }
865
0
    return true;
866
1.53k
}
867
868
371k
void PipelineTask::stop_if_finished() {
869
371k
    auto fragment = _fragment_context.lock();
870
371k
    if (!fragment) {
871
0
        return;
872
0
    }
873
371k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(fragment->get_query_ctx()->query_mem_tracker());
874
371k
    if (auto sink = _sink) {
875
371k
        if (sink->is_finished(_state)) {
876
1
            set_wake_up_early();
877
1
            terminate();
878
1
        }
879
371k
    }
880
371k
}
881
882
1
Status PipelineTask::finalize() {
883
1
    auto fragment = _fragment_context.lock();
884
1
    if (!fragment) {
885
0
        return Status::OK();
886
0
    }
887
1
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(fragment->get_query_ctx()->query_mem_tracker());
888
1
    RETURN_IF_ERROR(_state_transition(State::FINALIZED));
889
1
    std::unique_lock<std::mutex> lc(_dependency_lock);
890
1
    _sink_shared_state.reset();
891
1
    _op_shared_states.clear();
892
1
    _shared_state_map.clear();
893
1
    _block.reset();
894
1
    _operators.clear();
895
1
    _sink.reset();
896
1
    _pipeline.reset();
897
1
    return Status::OK();
898
1
}
899
900
17
Status PipelineTask::close(Status exec_status, bool close_sink) {
901
17
    int64_t close_ns = 0;
902
17
    Status s;
903
17
    {
904
17
        SCOPED_RAW_TIMER(&close_ns);
905
17
        if (close_sink) {
906
6
            s = _sink->close(_state, exec_status);
907
6
        }
908
21
        for (auto& op : _operators) {
909
21
            auto tem = op->close(_state);
910
21
            if (!tem.ok() && s.ok()) {
911
0
                s = std::move(tem);
912
0
            }
913
21
        }
914
17
    }
915
17
    if (_opened) {
916
17
        COUNTER_UPDATE(_close_timer, close_ns);
917
17
        COUNTER_UPDATE(_task_profile->total_time_counter(), close_ns);
918
17
    }
919
920
17
    if (close_sink && _opened) {
921
6
        _task_profile->add_info_string("WakeUpEarly", std::to_string(_wake_up_early.load()));
922
6
        _fresh_profile_counter();
923
6
    }
924
925
17
    if (close_sink) {
926
6
        RETURN_IF_ERROR(_state_transition(State::FINISHED));
927
6
    }
928
17
    return s;
929
17
}
930
931
44.8k
std::string PipelineTask::debug_string() {
932
44.8k
    fmt::memory_buffer debug_string_buffer;
933
934
44.8k
    fmt::format_to(debug_string_buffer, "QueryId: {}\n", print_id(_query_id));
935
44.8k
    fmt::format_to(debug_string_buffer, "InstanceId: {}\n",
936
44.8k
                   print_id(_state->fragment_instance_id()));
937
938
44.8k
    fmt::format_to(debug_string_buffer,
939
44.8k
                   "PipelineTask[id = {}, open = {}, eos = {}, state = {}, dry run = "
940
44.8k
                   "{}, _wake_up_early = {}, _wake_up_by = {}, time elapsed since last state "
941
44.8k
                   "changing = {}s, spilling = {}, is running = {}]",
942
44.8k
                   _index, _opened, _eos, _to_string(_exec_state), _dry_run, _wake_up_early.load(),
943
44.8k
                   _wake_by, _state_change_watcher.elapsed_time() / NANOS_PER_SEC, _spilling,
944
44.8k
                   is_running());
945
44.8k
    std::unique_lock<std::mutex> lc(_dependency_lock);
946
44.8k
    auto* cur_blocked_dep = _blocked_dep;
947
44.8k
    auto fragment = _fragment_context.lock();
948
44.8k
    if (is_finalized() || !fragment) {
949
5
        fmt::format_to(debug_string_buffer, " pipeline name = {}", _pipeline_name);
950
5
        return fmt::to_string(debug_string_buffer);
951
5
    }
952
44.8k
    auto elapsed = fragment->elapsed_time() / NANOS_PER_SEC;
953
44.8k
    fmt::format_to(debug_string_buffer, " elapse time = {}s, block dependency = [{}]\n", elapsed,
954
44.8k
                   cur_blocked_dep && !is_finalized() ? cur_blocked_dep->debug_string() : "NULL");
955
956
44.8k
    if (_state && _state->local_runtime_filter_mgr()) {
957
0
        fmt::format_to(debug_string_buffer, "local_runtime_filter_mgr: [{}]\n",
958
0
                       _state->local_runtime_filter_mgr()->debug_string());
959
0
    }
960
961
44.8k
    fmt::format_to(debug_string_buffer, "operators: ");
962
89.6k
    for (size_t i = 0; i < _operators.size(); i++) {
963
44.8k
        fmt::format_to(debug_string_buffer, "\n{}",
964
44.8k
                       _opened && !is_finalized()
965
44.8k
                               ? _operators[i]->debug_string(_state, cast_set<int>(i))
966
44.8k
                               : _operators[i]->debug_string(cast_set<int>(i)));
967
44.8k
    }
968
44.8k
    fmt::format_to(debug_string_buffer, "\n{}\n",
969
44.8k
                   _opened && !is_finalized()
970
44.8k
                           ? _sink->debug_string(_state, cast_set<int>(_operators.size()))
971
44.8k
                           : _sink->debug_string(cast_set<int>(_operators.size())));
972
973
44.8k
    fmt::format_to(debug_string_buffer, "\nRead Dependency Information: \n");
974
975
44.8k
    size_t i = 0;
976
89.6k
    for (; i < _read_dependencies.size(); i++) {
977
89.6k
        for (size_t j = 0; j < _read_dependencies[i].size(); j++) {
978
44.8k
            fmt::format_to(debug_string_buffer, "{}. {}\n", i,
979
44.8k
                           _read_dependencies[i][j]->debug_string(cast_set<int>(i) + 1));
980
44.8k
        }
981
44.8k
    }
982
983
44.8k
    fmt::format_to(debug_string_buffer, "{}. {}\n", i,
984
44.8k
                   _memory_sufficient_dependency->debug_string(cast_set<int>(i++)));
985
986
44.8k
    fmt::format_to(debug_string_buffer, "\nWrite Dependency Information: \n");
987
89.6k
    for (size_t j = 0; j < _write_dependencies.size(); j++, i++) {
988
44.8k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
989
44.8k
                       _write_dependencies[j]->debug_string(cast_set<int>(j) + 1));
990
44.8k
    }
991
992
44.8k
    fmt::format_to(debug_string_buffer, "\nExecution Dependency Information: \n");
993
134k
    for (size_t j = 0; j < _execution_dependencies.size(); j++, i++) {
994
89.6k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
995
89.6k
                       _execution_dependencies[j]->debug_string(cast_set<int>(i) + 1));
996
89.6k
    }
997
998
44.8k
    fmt::format_to(debug_string_buffer, "Finish Dependency Information: \n");
999
134k
    for (size_t j = 0; j < _finish_dependencies.size(); j++, i++) {
1000
89.6k
        fmt::format_to(debug_string_buffer, "{}. {}\n", i,
1001
89.6k
                       _finish_dependencies[j]->debug_string(cast_set<int>(i) + 1));
1002
89.6k
    }
1003
44.8k
    return fmt::to_string(debug_string_buffer);
1004
44.8k
}
1005
1006
2
size_t PipelineTask::get_revocable_size() const {
1007
2
    if (!_opened || is_finalized() || _running || (_eos && !_spilling)) {
1008
0
        return 0;
1009
0
    }
1010
1011
    // Sum revocable memory from every operator in the pipeline + the sink.
1012
    // Each operator reports only its own revocable memory (no child recursion).
1013
2
    size_t total = _sink->revocable_mem_size(_state);
1014
2
    for (const auto& op : _operators) {
1015
2
        total += op->revocable_mem_size(_state);
1016
2
    }
1017
2
    return total;
1018
2
}
1019
1020
3
Status PipelineTask::revoke_memory(const std::shared_ptr<SpillContext>& spill_context) {
1021
3
    DCHECK(spill_context);
1022
3
    if (is_finalized()) {
1023
1
        spill_context->on_task_finished();
1024
1
        VLOG_DEBUG << "Query: " << print_id(_state->query_id()) << ", task: " << ((void*)this)
1025
0
                   << " finalized";
1026
1
        return Status::OK();
1027
1
    }
1028
1029
2
    const auto revocable_size = get_revocable_size();
1030
2
    if (revocable_size >= SpillFile::MIN_SPILL_WRITE_BATCH_MEM) {
1031
1
        auto revokable_task = std::make_shared<RevokableTask>(shared_from_this(), spill_context);
1032
        // Submit a revocable task to run, the run method will call revoke memory. Currently the
1033
        // underline pipeline task is still blocked.
1034
1
        RETURN_IF_ERROR(_state->get_query_ctx()->get_pipe_exec_scheduler()->submit(revokable_task));
1035
1
    } else {
1036
1
        spill_context->on_task_finished();
1037
1
        VLOG_DEBUG << "Query: " << print_id(_state->query_id()) << ", task: " << ((void*)this)
1038
0
                   << " has not enough data to revoke: " << revocable_size;
1039
1
    }
1040
2
    return Status::OK();
1041
2
}
1042
1043
25
Status PipelineTask::wake_up(Dependency* dep, std::unique_lock<std::mutex>& /* dep_lock */) {
1044
    // call by dependency
1045
25
    DCHECK_EQ(_blocked_dep, dep) << "dep : " << dep->debug_string(0) << "task: " << debug_string();
1046
25
    _blocked_dep = nullptr;
1047
25
    auto holder = std::dynamic_pointer_cast<PipelineTask>(shared_from_this());
1048
25
    RETURN_IF_ERROR(_state_transition(PipelineTask::State::RUNNABLE));
1049
25
    if (auto f = _fragment_context.lock(); f) {
1050
25
        RETURN_IF_ERROR(_state->get_query_ctx()->get_pipe_exec_scheduler()->submit(holder));
1051
25
    }
1052
25
    return Status::OK();
1053
25
}
1054
1055
102
Status PipelineTask::_state_transition(State new_state) {
1056
102
    if (_exec_state != new_state) {
1057
97
        _state_change_watcher.reset();
1058
97
        _state_change_watcher.start();
1059
97
    }
1060
102
    _task_profile->add_info_string("TaskState", _to_string(new_state));
1061
102
    _task_profile->add_info_string("BlockedByDependency", _blocked_dep ? _blocked_dep->name() : "");
1062
102
    if (!LEGAL_STATE_TRANSITION[(int)new_state].contains(_exec_state)) {
1063
17
        return Status::InternalError(
1064
17
                "Task state transition from {} to {} is not allowed! Task info: {}",
1065
17
                _to_string(_exec_state), _to_string(new_state), debug_string());
1066
17
    }
1067
85
    _exec_state = new_state;
1068
85
    return Status::OK();
1069
102
}
1070
1071
#include "common/compile_check_end.h"
1072
} // namespace doris