Coverage Report

Created: 2026-05-28 13:45

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