Coverage Report

Created: 2026-06-02 13:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/scanner_scheduler.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/scan/scanner_scheduler.h"
19
20
#include <algorithm>
21
#include <cstdint>
22
#include <functional>
23
#include <list>
24
#include <memory>
25
#include <ostream>
26
#include <string>
27
#include <utility>
28
29
#include "common/compiler_util.h" // IWYU pragma: keep
30
#include "common/config.h"
31
#include "common/exception.h"
32
#include "common/logging.h"
33
#include "common/status.h"
34
#include "core/block/block.h"
35
#include "exec/pipeline/pipeline_task.h"
36
#include "exec/scan/file_scanner.h"
37
#include "exec/scan/olap_scanner.h" // IWYU pragma: keep
38
#include "exec/scan/scan_node.h"
39
#include "exec/scan/scanner.h"
40
#include "exec/scan/scanner_context.h"
41
#include "runtime/exec_env.h"
42
#include "runtime/runtime_state.h"
43
#include "runtime/thread_context.h"
44
#include "runtime/workload_group/workload_group_manager.h"
45
#include "storage/tablet/tablet.h"
46
#include "util/async_io.h" // IWYU pragma: keep
47
#include "util/cpu_info.h"
48
#include "util/defer_op.h"
49
#include "util/thread.h"
50
#include "util/threadpool.h"
51
52
namespace doris {
53
54
Status ScannerScheduler::submit(std::shared_ptr<ScannerContext> ctx,
55
927k
                                std::shared_ptr<ScanTask> scan_task) {
56
927k
    if (ctx->done()) {
57
0
        return Status::OK();
58
0
    }
59
927k
    auto task_lock = ctx->task_exec_ctx();
60
927k
    if (task_lock == nullptr) {
61
18
        LOG(INFO) << "could not lock task execution context, query " << ctx->debug_string()
62
18
                  << " maybe finished";
63
18
        return Status::OK();
64
18
    }
65
927k
    std::shared_ptr<ScannerDelegate> scanner_delegate = scan_task->scanner.lock();
66
927k
    if (scanner_delegate == nullptr) {
67
0
        return Status::OK();
68
0
    }
69
70
927k
    scan_task->set_state(ScanTask::State::IN_FLIGHT);
71
    // Only starts the wait timer without touching the CPU timer, because the CPU
72
    // timer uses CLOCK_THREAD_CPUTIME_ID which must be read on the same thread
73
    // that started it.
74
927k
    scanner_delegate->_scanner->start_wait_worker_timer();
75
927k
    TabletStorageType type = scanner_delegate->_scanner->get_storage_type();
76
927k
    auto sumbit_task = [&]() {
77
927k
        auto work_func = [scanner_ref = scan_task, ctx]() {
78
927k
            auto status = [&] {
79
927k
                RETURN_IF_CATCH_EXCEPTION(_scanner_scan(ctx, scanner_ref));
80
926k
                return Status::OK();
81
927k
            }();
82
83
927k
            if (!status.ok()) {
84
0
                scanner_ref->set_status(status);
85
0
                ctx->push_back_scan_task(scanner_ref);
86
0
                return true;
87
0
            }
88
927k
            return scanner_ref->is_eos();
89
927k
        };
90
927k
        SimplifiedScanTask simple_scan_task = {work_func, ctx, scan_task};
91
927k
        return this->submit_scan_task(simple_scan_task);
92
927k
    };
93
94
927k
    Status submit_status = sumbit_task();
95
927k
    if (!submit_status.ok()) {
96
        // User will see TooManyTasks error. It looks like a more reasonable error.
97
0
        Status scan_task_status = Status::TooManyTasks(
98
0
                "Failed to submit scanner to scanner pool reason:" +
99
0
                std::string(submit_status.msg()) + "|type:" + std::to_string(type));
100
0
        scan_task->set_status(scan_task_status);
101
0
        return scan_task_status;
102
0
    }
103
104
927k
    return Status::OK();
105
927k
}
106
107
void handle_reserve_memory_failure(RuntimeState* state, std::shared_ptr<ScannerContext> ctx,
108
0
                                   const Status& st, size_t reserve_size) {
109
0
    ctx->clear_free_blocks();
110
0
    auto* local_state = ctx->local_state();
111
112
0
    auto debug_msg = fmt::format(
113
0
            "Query: {} , scanner try to reserve: {}, operator name {}, "
114
0
            "operator "
115
0
            "id: {}, "
116
0
            "task id: "
117
0
            "{}, failed: {}",
118
0
            print_id(state->query_id()), PrettyPrinter::print_bytes(reserve_size),
119
0
            local_state->get_name(), local_state->parent()->node_id(), state->task_id(),
120
0
            st.to_string());
121
    // PROCESS_MEMORY_EXCEEDED error msg alread contains process_mem_log_str
122
0
    if (!st.is<ErrorCode::PROCESS_MEMORY_EXCEEDED>()) {
123
0
        debug_msg += fmt::format(", debug info: {}", GlobalMemoryArbitrator::process_mem_log_str());
124
0
    }
125
0
    VLOG_DEBUG << debug_msg;
126
127
0
    state->get_query_ctx()->set_low_memory_mode();
128
0
}
129
130
// NOLINTBEGIN(readability-function-cognitive-complexity,readability-function-size)
131
// Existing scheduler loop owns scanner lifecycle and I/O accounting.
132
void ScannerScheduler::_scanner_scan(std::shared_ptr<ScannerContext> ctx,
133
927k
                                     std::shared_ptr<ScanTask> scan_task) {
134
927k
    auto task_lock = ctx->task_exec_ctx();
135
927k
    if (task_lock == nullptr) {
136
0
        return;
137
0
    }
138
927k
    SCOPED_ATTACH_TASK(ctx->state());
139
140
927k
    ctx->update_peak_running_scanner(1);
141
927k
    Defer defer([&] { ctx->update_peak_running_scanner(-1); });
142
143
927k
    std::shared_ptr<ScannerDelegate> scanner_delegate = scan_task->scanner.lock();
144
927k
    if (scanner_delegate == nullptr) {
145
0
        return;
146
0
    }
147
148
927k
    ScannerSPtr& scanner = scanner_delegate->_scanner;
149
    // for cpu hard limit, thread name should not be reset
150
927k
    if (ctx->_should_reset_thread_name) {
151
0
        Thread::set_self_name("_scanner_scan");
152
0
    }
153
154
927k
#ifndef __APPLE__
155
    // The configuration item is used to lower the priority of the scanner thread,
156
    // typically employed to ensure CPU scheduling for write operations.
157
927k
    if (config::scan_thread_nice_value != 0 && scanner->get_name() != FileScanner::NAME) {
158
0
        Thread::set_thread_nice_value();
159
0
    }
160
927k
#endif
161
162
    // we set and get counter according below order, to make sure the counter is updated before get_block, and the time of get_block is recorded in the counter.
163
    // 1. update_wait_worker_timer to make sure the time of waiting for worker thread is recorded in the timer
164
    // 2. start_scan_cpu_timer to make sure the cpu timer include the time of open and get_block, which is the real cpu time of scanner
165
    // 3. update_scan_cpu_timer when defer, to make sure the cpu timer include the time of open and get_block, which is the real cpu time of scanner
166
    // 4. start_wait_worker_timer when defer, to make sure the time of waiting for worker thread is recorded in the timer
167
168
927k
    MonotonicStopWatch max_run_time_watch;
169
927k
    max_run_time_watch.start();
170
927k
    scanner->resume();
171
172
927k
    auto update_scanner_profile = [&]() {
173
926k
        scanner->pause();
174
926k
        scanner->update_realtime_counters();
175
926k
    };
176
177
927k
    Status status = Status::OK();
178
927k
    bool eos = false;
179
180
927k
    ASSIGN_STATUS_IF_CATCH_EXCEPTION(
181
927k
            RuntimeState* state = ctx->state(); DCHECK(nullptr != state);
182
            // scanner->open may alloc plenty amount of memory(read blocks of data),
183
            // so better to also check low memory and clear free blocks here.
184
927k
            if (ctx->low_memory_mode()) { ctx->clear_free_blocks(); }
185
186
927k
            if (scanner->check_partition_pruned()) { eos = true; }
187
188
927k
            if (!eos && !scanner->has_prepared()) {
189
927k
                status = scanner->prepare();
190
927k
                if (!status.ok()) {
191
927k
                    eos = true;
192
927k
                }
193
927k
            }
194
195
927k
            if (!eos && !scanner->is_open()) {
196
927k
                status = scanner->open(state);
197
927k
                if (!status.ok()) {
198
927k
                    eos = true;
199
927k
                }
200
927k
                scanner->set_opened();
201
927k
            }
202
203
927k
            if (!eos) {
204
927k
                Status rf_status = scanner->try_append_late_arrival_runtime_filter();
205
927k
                if (!rf_status.ok()) {
206
927k
                    LOG(WARNING) << "Failed to append late arrival runtime filter: "
207
927k
                                 << rf_status.to_string();
208
927k
                }
209
927k
            }
210
211
            // After processing late RFs, check if this scanner's partition was pruned.
212
927k
            if (!eos && scanner->check_partition_pruned()) { eos = true; }
213
214
927k
            size_t raw_bytes_threshold = config::doris_scanner_row_bytes;
215
927k
            if (ctx->low_memory_mode()) {
216
927k
                ctx->clear_free_blocks();
217
927k
                if (raw_bytes_threshold > ctx->low_memory_mode_scan_bytes_per_scanner()) {
218
927k
                    raw_bytes_threshold = ctx->low_memory_mode_scan_bytes_per_scanner();
219
927k
                }
220
927k
            }
221
222
927k
            bool first_read = true;
223
927k
            int64_t limit = scanner->limit();
224
927k
            if (UNLIKELY(ctx->done())) { eos = true; } else if (!eos) {
225
927k
                do {
226
927k
                    DEFER_RELEASE_RESERVED();
227
927k
                    BlockUPtr free_block;
228
927k
                    if (first_read) {
229
927k
                        free_block = ctx->get_free_block(first_read);
230
927k
                    } else {
231
927k
                        if (state->get_query_ctx()
232
927k
                                    ->resource_ctx()
233
927k
                                    ->task_controller()
234
927k
                                    ->is_enable_reserve_memory()) {
235
927k
                            size_t block_avg_bytes = scanner->get_block_avg_bytes();
236
927k
                            auto st = thread_context()->thread_mem_tracker_mgr->try_reserve(
237
927k
                                    block_avg_bytes);
238
927k
                            if (!st.ok()) {
239
927k
                                handle_reserve_memory_failure(state, ctx, st, block_avg_bytes);
240
927k
                                break;
241
927k
                            }
242
927k
                        }
243
927k
                        free_block = ctx->get_free_block(first_read);
244
927k
                    }
245
927k
                    if (free_block == nullptr) {
246
927k
                        break;
247
927k
                    }
248
                    // We got a new created block or a reused block.
249
927k
                    status = scanner->get_block_after_projects(state, free_block.get(), &eos);
250
927k
                    first_read = false;
251
927k
                    if (!status.ok()) {
252
927k
                        LOG(WARNING) << "Scan thread read Scanner failed: " << status.to_string();
253
927k
                        break;
254
927k
                    }
255
                    // Check column type only after block is read successfully.
256
                    // Or it may cause a crash when the block is not normal.
257
927k
                    _make_sure_virtual_col_is_materialized(scanner, free_block.get());
258
259
                    // Projection will truncate useless columns, makes block size change.
260
927k
                    auto free_block_bytes = free_block->allocated_bytes();
261
927k
                    ctx->reestimated_block_mem_bytes(cast_set<int64_t>(free_block_bytes));
262
927k
                    DCHECK(scan_task->cached_block == nullptr);
263
927k
                    ctx->inc_block_usage(free_block->allocated_bytes());
264
927k
                    scan_task->cached_block = std::move(free_block);
265
266
                    // Per-scanner small-limit optimization: if limit is small (< batch_size),
267
                    // return immediately instead of accumulating to raw_bytes_threshold.
268
927k
                    if (limit > 0 && limit < ctx->batch_size()) {
269
927k
                        break;
270
927k
                    }
271
272
927k
                    if (scan_task->cached_block->rows() > 0) {
273
927k
                        auto block_avg_bytes = (scan_task->cached_block->bytes() +
274
927k
                                                scan_task->cached_block->rows() - 1) /
275
927k
                                               scan_task->cached_block->rows() * ctx->batch_size();
276
927k
                        scanner->update_block_avg_bytes(block_avg_bytes);
277
927k
                    }
278
927k
                    if (ctx->low_memory_mode()) {
279
927k
                        ctx->clear_free_blocks();
280
927k
                    }
281
927k
                } while (false);
282
927k
            }
283
284
927k
            if (UNLIKELY(!status.ok())) {
285
927k
                scan_task->set_status(status);
286
927k
                eos = true;
287
927k
            },
288
927k
            status);
289
290
926k
    if (UNLIKELY(!status.ok())) {
291
1.29k
        scan_task->set_status(status);
292
1.29k
        eos = true;
293
1.29k
    }
294
295
    // Always update scanner profile to properly account for CPU time on the same
296
    // thread that started the CPU timer (CLOCK_THREAD_CPUTIME_ID is per-thread).
297
926k
    update_scanner_profile();
298
299
926k
    if (eos) {
300
875k
        scanner->mark_to_need_to_close();
301
875k
        scan_task->set_state(ScanTask::State::EOS);
302
875k
    } else {
303
50.7k
        scan_task->set_state(ScanTask::State::COMPLETED);
304
50.7k
    }
305
306
18.4E
    VLOG_DEBUG << fmt::format(
307
18.4E
            "Scanner context {} has finished task, current scheduled task is "
308
18.4E
            "{}, eos: {}, status: {}",
309
18.4E
            ctx->ctx_id, ctx->num_scheduled_scanners(), eos, status.to_string());
310
311
926k
    ctx->push_back_scan_task(scan_task);
312
926k
}
313
// NOLINTEND(readability-function-cognitive-complexity,readability-function-size)
314
315
17.6k
int ScannerScheduler::default_local_scan_thread_num() {
316
17.6k
    return config::doris_scanner_thread_pool_thread_num > 0
317
17.6k
                   ? config::doris_scanner_thread_pool_thread_num
318
17.6k
                   : std::max(48, CpuInfo::num_cores() * 2);
319
17.6k
}
320
11.4k
int ScannerScheduler::default_remote_scan_thread_num() {
321
11.4k
    int num = config::doris_max_remote_scanner_thread_pool_thread_num > 0
322
11.4k
                      ? config::doris_max_remote_scanner_thread_pool_thread_num
323
11.4k
                      : std::max(512, CpuInfo::num_cores() * 10);
324
11.4k
    return std::max(num, default_local_scan_thread_num());
325
11.4k
}
326
327
37
int ScannerScheduler::get_remote_scan_thread_queue_size() {
328
37
    return config::doris_remote_scanner_thread_pool_queue_size;
329
37
}
330
331
6.18k
int ScannerScheduler::default_min_active_scan_threads() {
332
6.18k
    return config::min_active_scan_threads > 0
333
6.18k
                   ? config::min_active_scan_threads
334
6.18k
                   : config::min_active_scan_threads = CpuInfo::num_cores() * 2;
335
6.18k
}
336
337
6.18k
int ScannerScheduler::default_min_active_file_scan_threads() {
338
6.18k
    return config::min_active_file_scan_threads > 0
339
6.18k
                   ? config::min_active_file_scan_threads
340
6.18k
                   : config::min_active_file_scan_threads = CpuInfo::num_cores() * 8;
341
6.18k
}
342
343
void ScannerScheduler::_make_sure_virtual_col_is_materialized(
344
924k
        const std::shared_ptr<Scanner>& scanner, Block* free_block) {
345
924k
#ifndef NDEBUG
346
    // Currently, virtual column can only be used on olap table.
347
924k
    std::shared_ptr<OlapScanner> olap_scanner = std::dynamic_pointer_cast<OlapScanner>(scanner);
348
924k
    if (olap_scanner == nullptr) {
349
12.8k
        return;
350
12.8k
    }
351
352
911k
    if (free_block->rows() == 0) {
353
691k
        return;
354
691k
    }
355
356
220k
    size_t idx = 0;
357
692k
    for (const auto& entry : *free_block) {
358
        // Virtual column must be materialized on the end of SegmentIterator's next batch method.
359
692k
        const auto* column_nothing = check_and_get_column<ColumnNothing>(entry.column.get());
360
692k
        if (column_nothing == nullptr) {
361
692k
            idx++;
362
692k
            continue;
363
692k
        }
364
365
18.4E
        std::vector<std::string> vcid_to_idx;
366
367
18.4E
        for (const auto& pair : olap_scanner->_vir_cid_to_idx_in_block) {
368
0
            vcid_to_idx.push_back(fmt::format("{}-{}", pair.first, pair.second));
369
0
        }
370
371
18.4E
        std::string error_msg = fmt::format(
372
18.4E
                "Column in idx {} is nothing, block columns {}, normal_columns "
373
18.4E
                "{}, "
374
18.4E
                "vir_cid_to_idx_in_block_msg {}",
375
18.4E
                idx, free_block->columns(), olap_scanner->_return_columns.size(),
376
18.4E
                fmt::format("_vir_cid_to_idx_in_block:[{}]", fmt::join(vcid_to_idx, ",")));
377
18.4E
        throw doris::Exception(ErrorCode::INTERNAL_ERROR, error_msg);
378
692k
    }
379
220k
#endif
380
220k
}
381
382
928k
Result<SharedListenableFuture<Void>> ScannerSplitRunner::process_for(std::chrono::nanoseconds) {
383
928k
    _started = true;
384
928k
    bool is_completed = _scan_func();
385
928k
    if (is_completed) {
386
876k
        _completion_future.set_value(Void {});
387
876k
    }
388
928k
    return SharedListenableFuture<Void>::create_ready(Void {});
389
928k
}
390
391
925k
bool ScannerSplitRunner::is_finished() {
392
925k
    return _completion_future.is_done();
393
925k
}
394
395
1.75M
Status ScannerSplitRunner::finished_status() {
396
1.75M
    return _completion_future.get_status();
397
1.75M
}
398
399
0
bool ScannerSplitRunner::is_started() const {
400
0
    return _started.load();
401
0
}
402
403
50.7k
bool ScannerSplitRunner::is_auto_reschedule() const {
404
50.7k
    return false;
405
50.7k
}
406
407
} // namespace doris