Coverage Report

Created: 2026-03-21 03:59

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