Coverage Report

Created: 2026-05-09 05:26

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
1.39M
                                std::shared_ptr<ScanTask> scan_task) {
56
1.39M
    if (ctx->done()) {
57
0
        return Status::OK();
58
0
    }
59
1.39M
    auto task_lock = ctx->task_exec_ctx();
60
1.39M
    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
1.39M
    std::shared_ptr<ScannerDelegate> scanner_delegate = scan_task->scanner.lock();
66
1.39M
    if (scanner_delegate == nullptr) {
67
0
        return Status::OK();
68
0
    }
69
70
1.39M
    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
1.39M
    scanner_delegate->_scanner->start_wait_worker_timer();
75
1.39M
    TabletStorageType type = scanner_delegate->_scanner->get_storage_type();
76
1.39M
    auto sumbit_task = [&]() {
77
1.39M
        auto work_func = [scanner_ref = scan_task, ctx]() {
78
1.39M
            auto status = [&] {
79
1.39M
                RETURN_IF_CATCH_EXCEPTION(_scanner_scan(ctx, scanner_ref));
80
1.38M
                return Status::OK();
81
1.39M
            }();
82
83
1.39M
            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
1.39M
            return scanner_ref->is_eos();
89
1.39M
        };
90
1.39M
        SimplifiedScanTask simple_scan_task = {work_func, ctx, scan_task};
91
1.39M
        return this->submit_scan_task(simple_scan_task);
92
1.39M
    };
93
94
1.39M
    Status submit_status = sumbit_task();
95
1.39M
    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
1.39M
    return Status::OK();
105
1.39M
}
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
void ScannerScheduler::_scanner_scan(std::shared_ptr<ScannerContext> ctx,
131
1.39M
                                     std::shared_ptr<ScanTask> scan_task) {
132
1.39M
    auto task_lock = ctx->task_exec_ctx();
133
1.39M
    if (task_lock == nullptr) {
134
0
        return;
135
0
    }
136
1.39M
    SCOPED_ATTACH_TASK(ctx->state());
137
138
1.39M
    ctx->update_peak_running_scanner(1);
139
1.39M
    Defer defer([&] { ctx->update_peak_running_scanner(-1); });
140
141
1.39M
    std::shared_ptr<ScannerDelegate> scanner_delegate = scan_task->scanner.lock();
142
1.39M
    if (scanner_delegate == nullptr) {
143
0
        return;
144
0
    }
145
146
1.39M
    ScannerSPtr& scanner = scanner_delegate->_scanner;
147
    // for cpu hard limit, thread name should not be reset
148
1.39M
    if (ctx->_should_reset_thread_name) {
149
0
        Thread::set_self_name("_scanner_scan");
150
0
    }
151
152
1.39M
#ifndef __APPLE__
153
    // The configuration item is used to lower the priority of the scanner thread,
154
    // typically employed to ensure CPU scheduling for write operations.
155
1.39M
    if (config::scan_thread_nice_value != 0 && scanner->get_name() != FileScanner::NAME) {
156
0
        Thread::set_thread_nice_value();
157
0
    }
158
1.39M
#endif
159
160
    // 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.
161
    // 1. update_wait_worker_timer to make sure the time of waiting for worker thread is recorded in the timer
162
    // 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
163
    // 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
164
    // 4. start_wait_worker_timer when defer, to make sure the time of waiting for worker thread is recorded in the timer
165
166
1.39M
    MonotonicStopWatch max_run_time_watch;
167
1.39M
    max_run_time_watch.start();
168
1.39M
    scanner->resume();
169
170
1.39M
    auto update_scanner_profile = [&]() {
171
1.38M
        scanner->pause();
172
1.38M
        scanner->update_realtime_counters();
173
1.38M
    };
174
175
1.39M
    Status status = Status::OK();
176
1.39M
    bool eos = false;
177
178
1.39M
    ASSIGN_STATUS_IF_CATCH_EXCEPTION(
179
1.39M
            RuntimeState* state = ctx->state(); DCHECK(nullptr != state);
180
            // scanner->open may alloc plenty amount of memory(read blocks of data),
181
            // so better to also check low memory and clear free blocks here.
182
1.39M
            if (ctx->low_memory_mode()) { ctx->clear_free_blocks(); }
183
184
1.39M
            if (!scanner->has_prepared()) {
185
1.39M
                status = scanner->prepare();
186
1.39M
                if (!status.ok()) {
187
1.39M
                    eos = true;
188
1.39M
                }
189
1.39M
            }
190
191
1.39M
            if (!eos && !scanner->is_open()) {
192
1.39M
                status = scanner->open(state);
193
1.39M
                if (!status.ok()) {
194
1.39M
                    eos = true;
195
1.39M
                }
196
1.39M
                scanner->set_opened();
197
1.39M
            }
198
199
1.39M
            Status rf_status = scanner->try_append_late_arrival_runtime_filter();
200
1.39M
            if (!rf_status.ok()) {
201
1.39M
                LOG(WARNING) << "Failed to append late arrival runtime filter: "
202
1.39M
                             << rf_status.to_string();
203
1.39M
            }
204
205
1.39M
            size_t raw_bytes_threshold = config::doris_scanner_row_bytes;
206
1.39M
            if (ctx->low_memory_mode()) {
207
1.39M
                ctx->clear_free_blocks();
208
1.39M
                if (raw_bytes_threshold > ctx->low_memory_mode_scan_bytes_per_scanner()) {
209
1.39M
                    raw_bytes_threshold = ctx->low_memory_mode_scan_bytes_per_scanner();
210
1.39M
                }
211
1.39M
            }
212
213
1.39M
            bool first_read = true;
214
1.39M
            int64_t limit = scanner->limit();
215
1.39M
            if (UNLIKELY(ctx->done())) { eos = true; } else if (!eos) {
216
1.39M
                do {
217
1.39M
                    DEFER_RELEASE_RESERVED();
218
1.39M
                    BlockUPtr free_block;
219
1.39M
                    if (first_read) {
220
1.39M
                        free_block = ctx->get_free_block(first_read);
221
1.39M
                    } else {
222
1.39M
                        if (state->get_query_ctx()
223
1.39M
                                    ->resource_ctx()
224
1.39M
                                    ->task_controller()
225
1.39M
                                    ->is_enable_reserve_memory()) {
226
1.39M
                            size_t block_avg_bytes = scanner->get_block_avg_bytes();
227
1.39M
                            auto st = thread_context()->thread_mem_tracker_mgr->try_reserve(
228
1.39M
                                    block_avg_bytes);
229
1.39M
                            if (!st.ok()) {
230
1.39M
                                handle_reserve_memory_failure(state, ctx, st, block_avg_bytes);
231
1.39M
                                break;
232
1.39M
                            }
233
1.39M
                        }
234
1.39M
                        free_block = ctx->get_free_block(first_read);
235
1.39M
                    }
236
1.39M
                    if (free_block == nullptr) {
237
1.39M
                        break;
238
1.39M
                    }
239
                    // We got a new created block or a reused block.
240
1.39M
                    status = scanner->get_block_after_projects(state, free_block.get(), &eos);
241
1.39M
                    first_read = false;
242
1.39M
                    if (!status.ok()) {
243
1.39M
                        LOG(WARNING) << "Scan thread read Scanner failed: " << status.to_string();
244
1.39M
                        break;
245
1.39M
                    }
246
                    // Check column type only after block is read successfully.
247
                    // Or it may cause a crash when the block is not normal.
248
1.39M
                    _make_sure_virtual_col_is_materialized(scanner, free_block.get());
249
250
                    // Projection will truncate useless columns, makes block size change.
251
1.39M
                    auto free_block_bytes = free_block->allocated_bytes();
252
1.39M
                    ctx->reestimated_block_mem_bytes(cast_set<int64_t>(free_block_bytes));
253
1.39M
                    DCHECK(scan_task->cached_block == nullptr);
254
1.39M
                    ctx->inc_block_usage(free_block->allocated_bytes());
255
1.39M
                    scan_task->cached_block = std::move(free_block);
256
257
                    // Per-scanner small-limit optimization: if limit is small (< batch_size),
258
                    // return immediately instead of accumulating to raw_bytes_threshold.
259
1.39M
                    if (limit > 0 && limit < ctx->batch_size()) {
260
1.39M
                        break;
261
1.39M
                    }
262
263
1.39M
                    if (scan_task->cached_block->rows() > 0) {
264
1.39M
                        auto block_avg_bytes = (scan_task->cached_block->bytes() +
265
1.39M
                                                scan_task->cached_block->rows() - 1) /
266
1.39M
                                               scan_task->cached_block->rows() * ctx->batch_size();
267
1.39M
                        scanner->update_block_avg_bytes(block_avg_bytes);
268
1.39M
                    }
269
1.39M
                    if (ctx->low_memory_mode()) {
270
1.39M
                        ctx->clear_free_blocks();
271
1.39M
                    }
272
1.39M
                } while (false);
273
1.39M
            }
274
275
1.39M
            if (UNLIKELY(!status.ok())) {
276
1.39M
                scan_task->set_status(status);
277
1.39M
                eos = true;
278
1.39M
            },
279
1.39M
            status);
280
281
1.38M
    if (UNLIKELY(!status.ok())) {
282
1.38k
        scan_task->set_status(status);
283
1.38k
        eos = true;
284
1.38k
    }
285
286
    // Always update scanner profile to properly account for CPU time on the same
287
    // thread that started the CPU timer (CLOCK_THREAD_CPUTIME_ID is per-thread).
288
1.38M
    update_scanner_profile();
289
290
1.38M
    if (eos) {
291
1.29M
        scanner->mark_to_need_to_close();
292
1.29M
        scan_task->set_state(ScanTask::State::EOS);
293
1.29M
    } else {
294
97.9k
        scan_task->set_state(ScanTask::State::COMPLETED);
295
97.9k
    }
296
297
18.4E
    VLOG_DEBUG << fmt::format(
298
18.4E
            "Scanner context {} has finished task, current scheduled task is "
299
18.4E
            "{}, eos: {}, status: {}",
300
18.4E
            ctx->ctx_id, ctx->num_scheduled_scanners(), eos, status.to_string());
301
302
1.38M
    ctx->push_back_scan_task(scan_task);
303
1.38M
}
304
76.3k
int ScannerScheduler::default_local_scan_thread_num() {
305
76.3k
    return config::doris_scanner_thread_pool_thread_num > 0
306
76.3k
                   ? config::doris_scanner_thread_pool_thread_num
307
76.3k
                   : std::max(48, CpuInfo::num_cores() * 2);
308
76.3k
}
309
69.3k
int ScannerScheduler::default_remote_scan_thread_num() {
310
69.3k
    int num = config::doris_max_remote_scanner_thread_pool_thread_num > 0
311
69.3k
                      ? config::doris_max_remote_scanner_thread_pool_thread_num
312
69.3k
                      : std::max(512, CpuInfo::num_cores() * 10);
313
69.3k
    return std::max(num, default_local_scan_thread_num());
314
69.3k
}
315
316
39
int ScannerScheduler::get_remote_scan_thread_queue_size() {
317
39
    return config::doris_remote_scanner_thread_pool_queue_size;
318
39
}
319
320
7.02k
int ScannerScheduler::default_min_active_scan_threads() {
321
7.02k
    return config::min_active_scan_threads > 0
322
7.02k
                   ? config::min_active_scan_threads
323
7.02k
                   : config::min_active_scan_threads = CpuInfo::num_cores() * 2;
324
7.02k
}
325
326
7.02k
int ScannerScheduler::default_min_active_file_scan_threads() {
327
7.02k
    return config::min_active_file_scan_threads > 0
328
7.02k
                   ? config::min_active_file_scan_threads
329
7.02k
                   : config::min_active_file_scan_threads = CpuInfo::num_cores() * 8;
330
7.02k
}
331
332
void ScannerScheduler::_make_sure_virtual_col_is_materialized(
333
1.38M
        const std::shared_ptr<Scanner>& scanner, Block* free_block) {
334
1.38M
#ifndef NDEBUG
335
    // Currently, virtual column can only be used on olap table.
336
1.38M
    std::shared_ptr<OlapScanner> olap_scanner = std::dynamic_pointer_cast<OlapScanner>(scanner);
337
1.38M
    if (olap_scanner == nullptr) {
338
144k
        return;
339
144k
    }
340
341
1.24M
    if (free_block->rows() == 0) {
342
1.01M
        return;
343
1.01M
    }
344
345
230k
    size_t idx = 0;
346
721k
    for (const auto& entry : *free_block) {
347
        // Virtual column must be materialized on the end of SegmentIterator's next batch method.
348
721k
        const ColumnNothing* column_nothing =
349
721k
                check_and_get_column<ColumnNothing>(entry.column.get());
350
721k
        if (column_nothing == nullptr) {
351
721k
            idx++;
352
721k
            continue;
353
721k
        }
354
355
18.4E
        std::vector<std::string> vcid_to_idx;
356
357
18.4E
        for (const auto& pair : olap_scanner->_vir_cid_to_idx_in_block) {
358
0
            vcid_to_idx.push_back(fmt::format("{}-{}", pair.first, pair.second));
359
0
        }
360
361
18.4E
        std::string error_msg = fmt::format(
362
18.4E
                "Column in idx {} is nothing, block columns {}, normal_columns "
363
18.4E
                "{}, "
364
18.4E
                "vir_cid_to_idx_in_block_msg {}",
365
18.4E
                idx, free_block->columns(), olap_scanner->_return_columns.size(),
366
18.4E
                fmt::format("_vir_cid_to_idx_in_block:[{}]", fmt::join(vcid_to_idx, ",")));
367
18.4E
        throw doris::Exception(ErrorCode::INTERNAL_ERROR, error_msg);
368
721k
    }
369
230k
#endif
370
230k
}
371
372
1.39M
Result<SharedListenableFuture<Void>> ScannerSplitRunner::process_for(std::chrono::nanoseconds) {
373
1.39M
    _started = true;
374
1.39M
    bool is_completed = _scan_func();
375
1.39M
    if (is_completed) {
376
1.29M
        _completion_future.set_value(Void {});
377
1.29M
    }
378
1.39M
    return SharedListenableFuture<Void>::create_ready(Void {});
379
1.39M
}
380
381
1.39M
bool ScannerSplitRunner::is_finished() {
382
1.39M
    return _completion_future.is_done();
383
1.39M
}
384
385
1.29M
Status ScannerSplitRunner::finished_status() {
386
1.29M
    return _completion_future.get_status();
387
1.29M
}
388
389
0
bool ScannerSplitRunner::is_started() const {
390
0
    return _started.load();
391
0
}
392
393
97.8k
bool ScannerSplitRunner::is_auto_reschedule() const {
394
97.8k
    return false;
395
97.8k
}
396
397
} // namespace doris