Coverage Report

Created: 2026-03-25 14:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/scanner_context.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_context.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Metrics_types.h>
22
#include <glog/logging.h>
23
#include <zconf.h>
24
25
#include <cstdint>
26
#include <ctime>
27
#include <memory>
28
#include <mutex>
29
#include <ostream>
30
#include <shared_mutex>
31
#include <tuple>
32
#include <utility>
33
34
#include "common/config.h"
35
#include "common/exception.h"
36
#include "common/logging.h"
37
#include "common/metrics/doris_metrics.h"
38
#include "common/status.h"
39
#include "core/block/block.h"
40
#include "exec/operator/scan_operator.h"
41
#include "exec/scan/scan_node.h"
42
#include "exec/scan/scanner_scheduler.h"
43
#include "runtime/descriptors.h"
44
#include "runtime/exec_env.h"
45
#include "runtime/runtime_profile.h"
46
#include "runtime/runtime_state.h"
47
#include "storage/tablet/tablet.h"
48
#include "util/time.h"
49
#include "util/uid_util.h"
50
51
namespace doris {
52
53
using namespace std::chrono_literals;
54
#include "common/compile_check_begin.h"
55
ScannerContext::ScannerContext(RuntimeState* state, ScanLocalStateBase* local_state,
56
                               const TupleDescriptor* output_tuple_desc,
57
                               const RowDescriptor* output_row_descriptor,
58
                               const std::list<std::shared_ptr<ScannerDelegate>>& scanners,
59
                               int64_t limit_, std::shared_ptr<Dependency> dependency,
60
                               std::atomic<int64_t>* shared_scan_limit
61
#ifdef BE_TEST
62
                               ,
63
                               int num_parallel_instances
64
#endif
65
                               )
66
86.2k
        : HasTaskExecutionCtx(state),
67
86.2k
          _state(state),
68
86.2k
          _local_state(local_state),
69
86.2k
          _output_tuple_desc(output_row_descriptor
70
86.2k
                                     ? output_row_descriptor->tuple_descriptors().front()
71
86.2k
                                     : output_tuple_desc),
72
86.2k
          _output_row_descriptor(output_row_descriptor),
73
86.2k
          _batch_size(state->batch_size()),
74
86.2k
          limit(limit_),
75
86.2k
          _shared_scan_limit(shared_scan_limit),
76
86.2k
          _all_scanners(scanners.begin(), scanners.end()),
77
#ifndef BE_TEST
78
86.2k
          _scanner_scheduler(local_state->scan_scheduler(state)),
79
          _min_scan_concurrency_of_scan_scheduler(
80
86.2k
                  _scanner_scheduler->get_min_active_scan_threads()),
81
86.2k
          _max_scan_concurrency(std::min(local_state->max_scanners_concurrency(state),
82
86.2k
                                         cast_set<int>(scanners.size()))),
83
#else
84
          _scanner_scheduler(state->get_query_ctx()->get_scan_scheduler()),
85
          _min_scan_concurrency_of_scan_scheduler(0),
86
          _max_scan_concurrency(num_parallel_instances),
87
#endif
88
86.2k
          _min_scan_concurrency(local_state->min_scanners_concurrency(state)) {
89
86.2k
    DCHECK(_state != nullptr);
90
86.2k
    DCHECK(_output_row_descriptor == nullptr ||
91
86.2k
           _output_row_descriptor->tuple_descriptors().size() == 1);
92
86.2k
    _query_id = _state->get_query_ctx()->query_id();
93
86.2k
    _resource_ctx = _state->get_query_ctx()->resource_ctx();
94
86.2k
    ctx_id = UniqueId::gen_uid().to_string();
95
429k
    for (auto& scanner : _all_scanners) {
96
429k
        _pending_scanners.push(std::make_shared<ScanTask>(scanner));
97
429k
    };
98
86.2k
    if (limit < 0) {
99
84.4k
        limit = -1;
100
84.4k
    }
101
86.2k
    _dependency = dependency;
102
86.2k
    DorisMetrics::instance()->scanner_ctx_cnt->increment(1);
103
86.5k
    if (auto ctx = task_exec_ctx(); ctx) {
104
86.5k
        ctx->ref_task_execution_ctx();
105
86.5k
    }
106
86.2k
}
107
108
117k
int64_t ScannerContext::acquire_limit_quota(int64_t desired) {
109
117k
    DCHECK(desired > 0);
110
117k
    int64_t remaining = _shared_scan_limit->load(std::memory_order_acquire);
111
117k
    while (true) {
112
117k
        if (remaining < 0) {
113
            // No limit set, grant all desired rows.
114
115k
            return desired;
115
115k
        }
116
2.10k
        if (remaining == 0) {
117
58
            return 0;
118
58
        }
119
2.04k
        int64_t granted = std::min(desired, remaining);
120
2.04k
        if (_shared_scan_limit->compare_exchange_weak(remaining, remaining - granted,
121
2.04k
                                                      std::memory_order_acq_rel,
122
2.04k
                                                      std::memory_order_acquire)) {
123
2.03k
            return granted;
124
2.03k
        }
125
        // CAS failed, `remaining` is updated to current value, retry.
126
2.04k
    }
127
117k
}
128
129
// After init function call, should not access _parent
130
86.2k
Status ScannerContext::init() {
131
86.2k
#ifndef BE_TEST
132
86.2k
    _scanner_profile = _local_state->_scanner_profile;
133
86.2k
    _newly_create_free_blocks_num = _local_state->_newly_create_free_blocks_num;
134
86.2k
    _scanner_memory_used_counter = _local_state->_memory_used_counter;
135
136
    // 3. get thread token
137
86.2k
    if (!_state->get_query_ctx()) {
138
0
        return Status::InternalError("Query context of {} is not set",
139
0
                                     print_id(_state->query_id()));
140
0
    }
141
142
86.3k
    if (_state->get_query_ctx()->get_scan_scheduler()) {
143
86.3k
        _should_reset_thread_name = false;
144
86.3k
    }
145
146
86.2k
    auto scanner = _all_scanners.front().lock();
147
86.2k
    DCHECK(scanner != nullptr);
148
149
86.2k
    if (auto* task_executor_scheduler =
150
86.3k
                dynamic_cast<TaskExecutorSimplifiedScanScheduler*>(_scanner_scheduler)) {
151
86.3k
        std::shared_ptr<TaskExecutor> task_executor = task_executor_scheduler->task_executor();
152
86.3k
        TaskId task_id(fmt::format("{}-{}", print_id(_state->query_id()), ctx_id));
153
86.3k
        _task_handle = DORIS_TRY(task_executor->create_task(
154
86.3k
                task_id, []() { return 0.0; },
155
86.3k
                config::task_executor_initial_max_concurrency_per_task > 0
156
86.3k
                        ? config::task_executor_initial_max_concurrency_per_task
157
86.3k
                        : std::max(48, CpuInfo::num_cores() * 2),
158
86.3k
                std::chrono::milliseconds(100), std::nullopt));
159
86.3k
    }
160
86.2k
#endif
161
    // _max_bytes_in_queue controls the maximum memory that can be used by a single scan operator.
162
    // scan_queue_mem_limit on FE is 100MB by default, on backend we will make sure its actual value
163
    // is larger than 10MB.
164
86.2k
    _max_bytes_in_queue = std::max(_state->scan_queue_mem_limit(), (int64_t)1024 * 1024 * 10);
165
166
    // Provide more memory for wide tables, increase proportionally by multiples of 300
167
86.2k
    _max_bytes_in_queue *= _output_tuple_desc->slots().size() / 300 + 1;
168
169
86.2k
    if (_all_scanners.empty()) {
170
0
        _is_finished = true;
171
0
        _set_scanner_done();
172
0
    }
173
174
    // when user not specify scan_thread_num, so we can try downgrade _max_thread_num.
175
    // becaue we found in a table with 5k columns, column reader may ocuppy too much memory.
176
    // you can refer https://github.com/apache/doris/issues/35340 for details.
177
86.2k
    const int32_t max_column_reader_num = _state->max_column_reader_num();
178
179
86.2k
    if (_max_scan_concurrency != 1 && max_column_reader_num > 0) {
180
63.7k
        int32_t scan_column_num = cast_set<int32_t>(_output_tuple_desc->slots().size());
181
63.7k
        int32_t current_column_num = scan_column_num * _max_scan_concurrency;
182
63.7k
        if (current_column_num > max_column_reader_num) {
183
0
            int32_t new_max_thread_num = max_column_reader_num / scan_column_num;
184
0
            new_max_thread_num = new_max_thread_num <= 0 ? 1 : new_max_thread_num;
185
0
            if (new_max_thread_num < _max_scan_concurrency) {
186
0
                int32_t origin_max_thread_num = _max_scan_concurrency;
187
0
                _max_scan_concurrency = new_max_thread_num;
188
0
                LOG(INFO) << "downgrade query:" << print_id(_state->query_id())
189
0
                          << " scan's max_thread_num from " << origin_max_thread_num << " to "
190
0
                          << _max_scan_concurrency << ",column num: " << scan_column_num
191
0
                          << ", max_column_reader_num: " << max_column_reader_num;
192
0
            }
193
0
        }
194
63.7k
    }
195
196
86.2k
    COUNTER_SET(_local_state->_max_scan_concurrency, (int64_t)_max_scan_concurrency);
197
86.2k
    COUNTER_SET(_local_state->_min_scan_concurrency, (int64_t)_min_scan_concurrency);
198
199
86.2k
    std::unique_lock<std::mutex> l(_transfer_lock);
200
86.2k
    RETURN_IF_ERROR(_scanner_scheduler->schedule_scan_task(shared_from_this(), nullptr, l));
201
202
86.2k
    return Status::OK();
203
86.2k
}
204
205
86.5k
ScannerContext::~ScannerContext() {
206
86.5k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_resource_ctx->memory_context()->mem_tracker());
207
86.5k
    _tasks_queue.clear();
208
86.5k
    BlockUPtr block;
209
265k
    while (_free_blocks.try_dequeue(block)) {
210
        // do nothing
211
178k
    }
212
86.5k
    block.reset();
213
86.5k
    DorisMetrics::instance()->scanner_ctx_cnt->increment(-1);
214
86.5k
    if (_task_handle) {
215
0
        if (auto* task_executor_scheduler =
216
0
                    dynamic_cast<TaskExecutorSimplifiedScanScheduler*>(_scanner_scheduler)) {
217
0
            static_cast<void>(task_executor_scheduler->task_executor()->remove_task(_task_handle));
218
0
        }
219
0
        _task_handle = nullptr;
220
0
    }
221
86.5k
    if (auto ctx = task_exec_ctx(); ctx) {
222
81.4k
        ctx->unref_task_execution_ctx();
223
81.4k
    }
224
86.5k
}
225
226
496k
BlockUPtr ScannerContext::get_free_block(bool force) {
227
496k
    BlockUPtr block = nullptr;
228
496k
    if (_free_blocks.try_dequeue(block)) {
229
209k
        DCHECK(block->mem_reuse());
230
209k
        _block_memory_usage -= block->allocated_bytes();
231
209k
        _scanner_memory_used_counter->set(_block_memory_usage);
232
        // A free block is reused, so the memory usage should be decreased
233
        // The caller of get_free_block will increase the memory usage
234
286k
    } else if (_block_memory_usage < _max_bytes_in_queue || force) {
235
286k
        _newly_create_free_blocks_num->update(1);
236
286k
        block = Block::create_unique(_output_tuple_desc->slots(), 0);
237
286k
    }
238
496k
    return block;
239
496k
}
240
241
496k
void ScannerContext::return_free_block(BlockUPtr block) {
242
    // If under low memory mode, should not return the freeblock, it will occupy too much memory.
243
496k
    if (!_local_state->low_memory_mode() && block->mem_reuse() &&
244
496k
        _block_memory_usage < _max_bytes_in_queue) {
245
388k
        size_t block_size_to_reuse = block->allocated_bytes();
246
388k
        _block_memory_usage += block_size_to_reuse;
247
388k
        _scanner_memory_used_counter->set(_block_memory_usage);
248
388k
        block->clear_column_data();
249
        // Free blocks is used to improve memory efficiency. Failure during pushing back
250
        // free block will not incur any bad result so just ignore the return value.
251
388k
        _free_blocks.enqueue(std::move(block));
252
388k
    }
253
496k
}
254
255
Status ScannerContext::submit_scan_task(std::shared_ptr<ScanTask> scan_task,
256
434k
                                        std::unique_lock<std::mutex>& /*transfer_lock*/) {
257
    // increase _num_finished_scanners no matter the scan_task is submitted successfully or not.
258
    // since if submit failed, it will be added back by ScannerContext::push_back_scan_task
259
    // and _num_finished_scanners will be reduced.
260
    // if submit succeed, it will be also added back by ScannerContext::push_back_scan_task
261
    // see ScannerScheduler::_scanner_scan.
262
434k
    _num_scheduled_scanners++;
263
434k
    return _scanner_scheduler->submit(shared_from_this(), scan_task);
264
434k
}
265
266
0
void ScannerContext::clear_free_blocks() {
267
0
    clear_blocks(_free_blocks);
268
0
}
269
270
434k
void ScannerContext::push_back_scan_task(std::shared_ptr<ScanTask> scan_task) {
271
434k
    if (scan_task->status_ok()) {
272
467k
        for (const auto& [block, _] : scan_task->cached_blocks) {
273
467k
            if (block->rows() > 0) {
274
113k
                Status st = validate_block_schema(block.get());
275
113k
                if (!st.ok()) {
276
0
                    scan_task->set_status(st);
277
0
                    break;
278
0
                }
279
113k
            }
280
467k
        }
281
433k
    }
282
283
434k
    std::lock_guard<std::mutex> l(_transfer_lock);
284
434k
    if (!scan_task->status_ok()) {
285
90
        _process_status = scan_task->get_status();
286
90
    }
287
434k
    _tasks_queue.push_back(scan_task);
288
434k
    _num_scheduled_scanners--;
289
290
434k
    _dependency->set_ready();
291
434k
}
292
293
468k
Status ScannerContext::get_block_from_queue(RuntimeState* state, Block* block, bool* eos, int id) {
294
468k
    if (state->is_cancelled()) {
295
1
        _set_scanner_done();
296
1
        return state->cancel_reason();
297
1
    }
298
468k
    std::unique_lock l(_transfer_lock);
299
300
468k
    if (!_process_status.ok()) {
301
61
        _set_scanner_done();
302
61
        return _process_status;
303
61
    }
304
305
468k
    std::shared_ptr<ScanTask> scan_task = nullptr;
306
307
468k
    if (!_tasks_queue.empty() && !done()) {
308
        // https://en.cppreference.com/w/cpp/container/list/front
309
        // The behavior is undefined if the list is empty.
310
468k
        scan_task = _tasks_queue.front();
311
468k
    }
312
313
468k
    if (scan_task != nullptr) {
314
        // The abnormal status of scanner may come from the execution of the scanner itself,
315
        // or come from the scanner scheduler, such as TooManyTasks.
316
468k
        if (!scan_task->status_ok()) {
317
            // TODO: If the scanner status is TooManyTasks, maybe we can retry the scanner after a while.
318
0
            _process_status = scan_task->get_status();
319
0
            _set_scanner_done();
320
0
            return _process_status;
321
0
        }
322
323
        // No need to worry about small block, block is merged together when they are appended to cached_blocks.
324
468k
        if (!scan_task->cached_blocks.empty()) {
325
468k
            auto [current_block, block_size] = std::move(scan_task->cached_blocks.front());
326
468k
            scan_task->cached_blocks.pop_front();
327
468k
            _block_memory_usage -= block_size;
328
            // consume current block
329
468k
            block->swap(*current_block);
330
468k
            return_free_block(std::move(current_block));
331
468k
        }
332
333
468k
        VLOG_DEBUG << fmt::format(
334
36
                "ScannerContext {} get block from queue, task_queue size {}, current scan "
335
36
                "task remaing cached_block size {}, eos {}, scheduled tasks {}",
336
36
                ctx_id, _tasks_queue.size(), scan_task->cached_blocks.size(), scan_task->is_eos(),
337
36
                _num_scheduled_scanners);
338
339
468k
        if (scan_task->cached_blocks.empty()) {
340
            // All Cached blocks are consumed, pop this task from task_queue.
341
434k
            if (!_tasks_queue.empty()) {
342
434k
                _tasks_queue.pop_front();
343
434k
            }
344
345
434k
            if (scan_task->is_eos()) {
346
                // 1. if eos, record a finished scanner.
347
429k
                _num_finished_scanners++;
348
429k
                RETURN_IF_ERROR(
349
429k
                        _scanner_scheduler->schedule_scan_task(shared_from_this(), nullptr, l));
350
429k
            } else {
351
4.76k
                RETURN_IF_ERROR(
352
4.76k
                        _scanner_scheduler->schedule_scan_task(shared_from_this(), scan_task, l));
353
4.76k
            }
354
434k
        }
355
468k
    }
356
357
    // Mark finished when either:
358
    // (1) all scanners completed normally, or
359
    // (2) shared limit exhausted and no scanners are still running.
360
468k
    if (_tasks_queue.empty() && (_num_finished_scanners == _all_scanners.size() ||
361
336k
                                 (_shared_scan_limit->load(std::memory_order_acquire) == 0 &&
362
250k
                                  _num_scheduled_scanners == 0))) {
363
86.4k
        _set_scanner_done();
364
86.4k
        _is_finished = true;
365
86.4k
    }
366
367
468k
    *eos = done();
368
369
468k
    if (_tasks_queue.empty()) {
370
336k
        _dependency->block();
371
336k
    }
372
373
468k
    return Status::OK();
374
468k
}
375
376
113k
Status ScannerContext::validate_block_schema(Block* block) {
377
113k
    size_t index = 0;
378
579k
    for (auto& slot : _output_tuple_desc->slots()) {
379
579k
        auto& data = block->get_by_position(index++);
380
579k
        if (data.column->is_nullable() != data.type->is_nullable()) {
381
0
            return Status::Error<ErrorCode::INVALID_SCHEMA>(
382
0
                    "column(name: {}) nullable({}) does not match type nullable({}), slot(id: "
383
0
                    "{}, "
384
0
                    "name:{})",
385
0
                    data.name, data.column->is_nullable(), data.type->is_nullable(), slot->id(),
386
0
                    slot->col_name());
387
0
        }
388
389
579k
        if (data.column->is_nullable() != slot->is_nullable()) {
390
0
            return Status::Error<ErrorCode::INVALID_SCHEMA>(
391
0
                    "column(name: {}) nullable({}) does not match slot(id: {}, name: {}) "
392
0
                    "nullable({})",
393
0
                    data.name, data.column->is_nullable(), slot->id(), slot->col_name(),
394
0
                    slot->is_nullable());
395
0
        }
396
579k
    }
397
113k
    return Status::OK();
398
113k
}
399
400
173k
void ScannerContext::stop_scanners(RuntimeState* state) {
401
173k
    std::lock_guard<std::mutex> l(_transfer_lock);
402
173k
    if (_should_stop) {
403
86.4k
        return;
404
86.4k
    }
405
86.5k
    _should_stop = true;
406
86.5k
    _set_scanner_done();
407
430k
    for (const std::weak_ptr<ScannerDelegate>& scanner : _all_scanners) {
408
430k
        if (std::shared_ptr<ScannerDelegate> sc = scanner.lock()) {
409
430k
            sc->_scanner->try_stop();
410
430k
        }
411
430k
    }
412
86.5k
    _tasks_queue.clear();
413
86.5k
    if (_task_handle) {
414
86.5k
        if (auto* task_executor_scheduler =
415
86.5k
                    dynamic_cast<TaskExecutorSimplifiedScanScheduler*>(_scanner_scheduler)) {
416
86.5k
            static_cast<void>(task_executor_scheduler->task_executor()->remove_task(_task_handle));
417
86.5k
        }
418
86.5k
        _task_handle = nullptr;
419
86.5k
    }
420
    // TODO yiguolei, call mark close to scanners
421
86.5k
    if (state->enable_profile()) {
422
472
        std::stringstream scanner_statistics;
423
472
        std::stringstream scanner_rows_read;
424
472
        std::stringstream scanner_wait_worker_time;
425
472
        std::stringstream scanner_projection;
426
472
        scanner_statistics << "[";
427
472
        scanner_rows_read << "[";
428
472
        scanner_wait_worker_time << "[";
429
472
        scanner_projection << "[";
430
        // Scanners can in 3 state
431
        //  state 1: in scanner context, not scheduled
432
        //  state 2: in scanner worker pool's queue, scheduled but not running
433
        //  state 3: scanner is running.
434
568
        for (auto& scanner_ref : _all_scanners) {
435
568
            auto scanner = scanner_ref.lock();
436
568
            if (scanner == nullptr) {
437
0
                continue;
438
0
            }
439
            // Add per scanner running time before close them
440
568
            scanner_statistics << PrettyPrinter::print(scanner->_scanner->get_time_cost_ns(),
441
568
                                                       TUnit::TIME_NS)
442
568
                               << ", ";
443
568
            scanner_projection << PrettyPrinter::print(scanner->_scanner->projection_time(),
444
568
                                                       TUnit::TIME_NS)
445
568
                               << ", ";
446
568
            scanner_rows_read << PrettyPrinter::print(scanner->_scanner->get_rows_read(),
447
568
                                                      TUnit::UNIT)
448
568
                              << ", ";
449
568
            scanner_wait_worker_time
450
568
                    << PrettyPrinter::print(scanner->_scanner->get_scanner_wait_worker_timer(),
451
568
                                            TUnit::TIME_NS)
452
568
                    << ", ";
453
            // since there are all scanners, some scanners is running, so that could not call scanner
454
            // close here.
455
568
        }
456
472
        scanner_statistics << "]";
457
472
        scanner_rows_read << "]";
458
472
        scanner_wait_worker_time << "]";
459
472
        scanner_projection << "]";
460
472
        _scanner_profile->add_info_string("PerScannerRunningTime", scanner_statistics.str());
461
472
        _scanner_profile->add_info_string("PerScannerRowsRead", scanner_rows_read.str());
462
472
        _scanner_profile->add_info_string("PerScannerWaitTime", scanner_wait_worker_time.str());
463
472
        _scanner_profile->add_info_string("PerScannerProjectionTime", scanner_projection.str());
464
472
    }
465
86.5k
}
466
467
18
std::string ScannerContext::debug_string() {
468
18
    return fmt::format(
469
18
            "id: {}, total scanners: {}, pending tasks: {},"
470
18
            " _should_stop: {}, _is_finished: {}, free blocks: {},"
471
18
            " limit: {}, remaining_limit: {}, _num_running_scanners: {}, _max_thread_num: {},"
472
18
            " _max_bytes_in_queue: {}, query_id: {}",
473
18
            ctx_id, _all_scanners.size(), _tasks_queue.size(), _should_stop, _is_finished,
474
18
            _free_blocks.size_approx(), limit, _shared_scan_limit->load(std::memory_order_relaxed),
475
18
            _num_scheduled_scanners, _max_scan_concurrency, _max_bytes_in_queue,
476
18
            print_id(_query_id));
477
18
}
478
479
173k
void ScannerContext::_set_scanner_done() {
480
173k
    _dependency->set_always_ready();
481
173k
}
482
483
869k
void ScannerContext::update_peak_running_scanner(int num) {
484
869k
    _local_state->_peak_running_scanner->add(num);
485
869k
}
486
487
int32_t ScannerContext::_get_margin(std::unique_lock<std::mutex>& transfer_lock,
488
521k
                                    std::unique_lock<std::shared_mutex>& scheduler_lock) {
489
    // margin_1 is used to ensure each scan operator could have at least _min_scan_concurrency scan tasks.
490
521k
    int32_t margin_1 = _min_scan_concurrency -
491
521k
                       (cast_set<int32_t>(_tasks_queue.size()) + _num_scheduled_scanners);
492
493
    // margin_2 is used to ensure the scan scheduler could have at least _min_scan_concurrency_of_scan_scheduler scan tasks.
494
521k
    int32_t margin_2 =
495
521k
            _min_scan_concurrency_of_scan_scheduler -
496
521k
            (_scanner_scheduler->get_active_threads() + _scanner_scheduler->get_queue_size());
497
498
521k
    if (margin_1 <= 0 && margin_2 <= 0) {
499
3.43k
        return 0;
500
3.43k
    }
501
502
517k
    int32_t margin = std::max(margin_1, margin_2);
503
504
517k
    if (low_memory_mode()) {
505
        // In low memory mode, we will limit the number of running scanners to `low_memory_mode_scanners()`.
506
        // So that we will not submit too many scan tasks to scheduler.
507
0
        margin = std::min(low_memory_mode_scanners() - _num_scheduled_scanners, margin);
508
0
    }
509
510
18.4E
    VLOG_DEBUG << fmt::format(
511
18.4E
            "[{}|{}] schedule scan task, margin_1: {} = {} - ({} + {}), margin_2: {} = {} - "
512
18.4E
            "({} + {}), margin: {}",
513
18.4E
            print_id(_query_id), ctx_id, margin_1, _min_scan_concurrency, _tasks_queue.size(),
514
18.4E
            _num_scheduled_scanners, margin_2, _min_scan_concurrency_of_scan_scheduler,
515
18.4E
            _scanner_scheduler->get_active_threads(), _scanner_scheduler->get_queue_size(), margin);
516
517
517k
    return margin;
518
521k
}
519
520
// This function must be called with:
521
// 1. _transfer_lock held.
522
// 2. ScannerScheduler::_lock held.
523
Status ScannerContext::schedule_scan_task(std::shared_ptr<ScanTask> current_scan_task,
524
                                          std::unique_lock<std::mutex>& transfer_lock,
525
521k
                                          std::unique_lock<std::shared_mutex>& scheduler_lock) {
526
521k
    if (current_scan_task &&
527
521k
        (!current_scan_task->cached_blocks.empty() || current_scan_task->is_eos())) {
528
1
        throw doris::Exception(ErrorCode::INTERNAL_ERROR, "Scanner scheduler logical error.");
529
1
    }
530
531
521k
    std::list<std::shared_ptr<ScanTask>> tasks_to_submit;
532
533
521k
    int32_t margin = _get_margin(transfer_lock, scheduler_lock);
534
535
    // margin is less than zero. Means this scan operator could not submit any scan task for now.
536
521k
    if (margin <= 0) {
537
        // Be careful with current scan task.
538
        // We need to add it back to task queue to make sure it could be resubmitted.
539
3.43k
        if (current_scan_task) {
540
            // This usually happens when we should downgrade the concurrency.
541
16
            _pending_scanners.push(current_scan_task);
542
16
            VLOG_DEBUG << fmt::format(
543
0
                    "{} push back scanner to task queue, because diff <= 0, task_queue size "
544
0
                    "{}, _num_scheduled_scanners {}",
545
0
                    ctx_id, _tasks_queue.size(), _num_scheduled_scanners);
546
16
        }
547
548
3.43k
#ifndef NDEBUG
549
        // This DCHECK is necessary.
550
        // We need to make sure each scan operator could have at least 1 scan tasks.
551
        // Or this scan operator will not be re-scheduled.
552
3.43k
        if (!_pending_scanners.empty() && _num_scheduled_scanners == 0 && _tasks_queue.empty()) {
553
0
            throw doris::Exception(ErrorCode::INTERNAL_ERROR, "Scanner scheduler logical error.");
554
0
        }
555
3.43k
#endif
556
557
3.43k
        return Status::OK();
558
3.43k
    }
559
560
517k
    bool first_pull = true;
561
562
952k
    while (margin-- > 0) {
563
946k
        std::shared_ptr<ScanTask> task_to_run;
564
946k
        const int32_t current_concurrency = cast_set<int32_t>(
565
946k
                _tasks_queue.size() + _num_scheduled_scanners + tasks_to_submit.size());
566
946k
        VLOG_DEBUG << fmt::format("{} currenct concurrency: {} = {} + {} + {}", ctx_id,
567
0
                                  current_concurrency, _tasks_queue.size(), _num_scheduled_scanners,
568
0
                                  tasks_to_submit.size());
569
946k
        if (first_pull) {
570
517k
            task_to_run = _pull_next_scan_task(current_scan_task, current_concurrency);
571
517k
            if (task_to_run == nullptr) {
572
                // In two situations we will get nullptr.
573
                // 1. current_concurrency already reached _max_scan_concurrency.
574
                // 2. all scanners are finished.
575
284k
                if (current_scan_task) {
576
1
                    DCHECK(current_scan_task->cached_blocks.empty());
577
1
                    DCHECK(!current_scan_task->is_eos());
578
1
                    if (!current_scan_task->cached_blocks.empty() || current_scan_task->is_eos()) {
579
                        // This should not happen.
580
0
                        throw doris::Exception(ErrorCode::INTERNAL_ERROR,
581
0
                                               "Scanner scheduler logical error.");
582
0
                    }
583
                    // Current scan task is not eos, but we can not resubmit it.
584
                    // Add current_scan_task back to task queue, so that we have chance to resubmit it in the future.
585
1
                    _pending_scanners.push(current_scan_task);
586
1
                }
587
284k
            }
588
517k
            first_pull = false;
589
517k
        } else {
590
428k
            task_to_run = _pull_next_scan_task(nullptr, current_concurrency);
591
428k
        }
592
593
946k
        if (task_to_run) {
594
434k
            tasks_to_submit.push_back(task_to_run);
595
511k
        } else {
596
511k
            break;
597
511k
        }
598
946k
    }
599
600
517k
    if (tasks_to_submit.empty()) {
601
284k
        return Status::OK();
602
284k
    }
603
604
18.4E
    VLOG_DEBUG << fmt::format("[{}:{}] submit {} scan tasks to scheduler, remaining scanner: {}",
605
18.4E
                              print_id(_query_id), ctx_id, tasks_to_submit.size(),
606
18.4E
                              _pending_scanners.size());
607
608
434k
    for (auto& scan_task_iter : tasks_to_submit) {
609
434k
        Status submit_status = submit_scan_task(scan_task_iter, transfer_lock);
610
434k
        if (!submit_status.ok()) {
611
0
            _process_status = submit_status;
612
0
            _set_scanner_done();
613
0
            return _process_status;
614
0
        }
615
434k
    }
616
617
233k
    return Status::OK();
618
233k
}
619
620
std::shared_ptr<ScanTask> ScannerContext::_pull_next_scan_task(
621
946k
        std::shared_ptr<ScanTask> current_scan_task, int32_t current_concurrency) {
622
946k
    if (current_concurrency >= _max_scan_concurrency) {
623
225k
        VLOG_DEBUG << fmt::format(
624
0
                "ScannerContext {} current concurrency {} >= _max_scan_concurrency {}, skip "
625
0
                "pull",
626
0
                ctx_id, current_concurrency, _max_scan_concurrency);
627
225k
        return nullptr;
628
225k
    }
629
630
720k
    if (current_scan_task != nullptr) {
631
4.72k
        if (!current_scan_task->cached_blocks.empty() || current_scan_task->is_eos()) {
632
            // This should not happen.
633
2
            throw doris::Exception(ErrorCode::INTERNAL_ERROR, "Scanner scheduler logical error.");
634
2
        }
635
4.72k
        return current_scan_task;
636
4.72k
    }
637
638
716k
    if (!_pending_scanners.empty()) {
639
        // If shared limit quota is exhausted, do not submit new scanners from pending queue.
640
430k
        int64_t remaining = _shared_scan_limit->load(std::memory_order_acquire);
641
430k
        if (remaining == 0) {
642
18
            return nullptr;
643
18
        }
644
430k
        std::shared_ptr<ScanTask> next_scan_task;
645
430k
        next_scan_task = _pending_scanners.top();
646
430k
        _pending_scanners.pop();
647
430k
        return next_scan_task;
648
430k
    } else {
649
285k
        return nullptr;
650
285k
    }
651
716k
}
652
653
2.37M
bool ScannerContext::low_memory_mode() const {
654
2.37M
    return _local_state->low_memory_mode();
655
2.37M
}
656
#include "common/compile_check_end.h"
657
} // namespace doris