Coverage Report

Created: 2026-07-27 12:46

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 "exec/scan/task_executor/task_executor.h"
44
#include "runtime/descriptors.h"
45
#include "runtime/exec_env.h"
46
#include "runtime/runtime_profile.h"
47
#include "runtime/runtime_state.h"
48
#include "storage/tablet/tablet.h"
49
#include "util/time.h"
50
#include "util/uid_util.h"
51
52
namespace doris {
53
54
using namespace std::chrono_literals;
55
56
// ==================== ScannerContext ====================
57
ScannerContext::ScannerContext(RuntimeState* state, ScanLocalStateBase* local_state,
58
                               const TupleDescriptor* output_tuple_desc,
59
                               const RowDescriptor* output_row_descriptor,
60
                               const std::list<std::shared_ptr<ScannerDelegate>>& scanners,
61
                               int64_t limit_, std::shared_ptr<Dependency> dependency,
62
                               std::atomic<int64_t>* shared_scan_limit,
63
                               std::shared_ptr<MemShareArbitrator> arb,
64
                               std::shared_ptr<MemLimiter> limiter, int ins_idx,
65
                               bool enable_adaptive_scan
66
#ifdef BE_TEST
67
                               ,
68
                               int num_parallel_instances
69
#endif
70
                               )
71
317k
        : HasTaskExecutionCtx(state),
72
317k
          _state(state),
73
317k
          _local_state(local_state),
74
317k
          _output_tuple_desc(output_row_descriptor
75
317k
                                     ? output_row_descriptor->tuple_descriptors().front()
76
317k
                                     : output_tuple_desc),
77
317k
          _output_row_descriptor(output_row_descriptor),
78
317k
          _batch_size(state->batch_size()),
79
317k
          limit(limit_),
80
317k
          _shared_scan_limit(shared_scan_limit),
81
317k
          _all_scanners(scanners.begin(), scanners.end()),
82
#ifndef BE_TEST
83
317k
          _scanner_scheduler(local_state->scan_scheduler(state)),
84
          _min_scan_concurrency_of_scan_scheduler(
85
317k
                  _scanner_scheduler->get_min_active_scan_threads()),
86
317k
          _max_scan_concurrency(std::min(local_state->max_scanners_concurrency(state),
87
317k
                                         cast_set<int>(scanners.size()))),
88
#else
89
          _scanner_scheduler(state->get_query_ctx()->get_scan_scheduler()),
90
          _min_scan_concurrency_of_scan_scheduler(0),
91
          _max_scan_concurrency(num_parallel_instances),
92
#endif
93
317k
          _min_scan_concurrency(local_state->min_scanners_concurrency(state)),
94
317k
          _scanner_mem_limiter(limiter),
95
317k
          _mem_share_arb(arb),
96
317k
          _ins_idx(ins_idx),
97
317k
          _enable_adaptive_scanners(enable_adaptive_scan) {
98
317k
    DCHECK(_state != nullptr);
99
317k
    DCHECK(_output_row_descriptor == nullptr ||
100
317k
           _output_row_descriptor->tuple_descriptors().size() == 1);
101
317k
    _query_id = _state->get_query_ctx()->query_id();
102
317k
    _resource_ctx = _state->get_query_ctx()->resource_ctx();
103
317k
    ctx_id = UniqueId::gen_uid().to_string();
104
1.43M
    for (auto& scanner : _all_scanners) {
105
1.43M
        _pending_tasks.push(std::make_shared<ScanTask>(scanner));
106
1.43M
    }
107
319k
    if (limit < 0) {
108
319k
        limit = -1;
109
319k
    }
110
317k
    _dependency = dependency;
111
    // Initialize adaptive processor
112
317k
    _adaptive_processor = ScannerAdaptiveProcessor::create_shared();
113
317k
    DorisMetrics::instance()->scanner_ctx_cnt->increment(1);
114
317k
}
115
116
2.04M
void ScannerContext::_adjust_scan_mem_limit(int64_t old_value, int64_t new_value) {
117
2.04M
    if (!_enable_adaptive_scanners) {
118
0
        return;
119
0
    }
120
121
2.04M
    int64_t new_scan_mem_limit = _mem_share_arb->update_mem_bytes(old_value, new_value);
122
2.04M
    _scanner_mem_limiter->update_mem_limit(new_scan_mem_limit);
123
2.04M
    _scanner_mem_limiter->update_arb_mem_bytes(new_value);
124
125
18.4E
    VLOG_DEBUG << fmt::format(
126
18.4E
            "adjust_scan_mem_limit. context = {}, new mem scan limit = {}, scanner mem bytes = {} "
127
18.4E
            "-> {}",
128
18.4E
            debug_string(), new_scan_mem_limit, old_value, new_value);
129
2.04M
}
130
131
1.86M
int ScannerContext::_available_pickup_scanner_count() {
132
1.86M
    if (!_enable_adaptive_scanners) {
133
19.9k
        return _max_scan_concurrency;
134
19.9k
    }
135
136
1.84M
    int min_scanners = std::max(1, _min_scan_concurrency);
137
1.84M
    int max_scanners = _scanner_mem_limiter->available_scanner_count(_ins_idx);
138
1.84M
    max_scanners = std::min(max_scanners, _max_scan_concurrency);
139
1.84M
    min_scanners = std::min(min_scanners, max_scanners);
140
1.84M
    if (_ins_idx == 0) {
141
        // Adjust memory limit via memory share arbitrator
142
1.55M
        _adjust_scan_mem_limit(_scanner_mem_limiter->get_arb_scanner_mem_bytes(),
143
1.55M
                               _scanner_mem_limiter->get_estimated_block_mem_bytes());
144
1.55M
    }
145
146
1.84M
    ScannerAdaptiveProcessor& P = *_adaptive_processor;
147
1.84M
    int& scanners = P.expected_scanners;
148
1.84M
    int64_t now = UnixMillis();
149
    // Avoid frequent adjustment - only adjust every 100ms
150
1.84M
    if (now - P.adjust_scanners_last_timestamp <= config::doris_scanner_dynamic_interval_ms) {
151
1.44M
        return scanners;
152
1.44M
    }
153
399k
    P.adjust_scanners_last_timestamp = now;
154
399k
    auto old_scanners = P.expected_scanners;
155
156
399k
    scanners = std::max(min_scanners, scanners);
157
399k
    scanners = std::min(max_scanners, scanners);
158
18.4E
    VLOG_DEBUG << fmt::format(
159
18.4E
            "_available_pickup_scanner_count. context = {}, old_scanners = {}, scanners = {} "
160
18.4E
            ", min_scanners: {}, max_scanners: {}",
161
18.4E
            debug_string(), old_scanners, scanners, min_scanners, max_scanners);
162
163
    // TODO(gabriel): Scanners are scheduled adaptively based on the memory usage now.
164
399k
    return scanners;
165
1.84M
}
166
167
// After init function call, should not access _parent
168
318k
Status ScannerContext::init() {
169
318k
#ifndef BE_TEST
170
318k
    _scanner_profile = _local_state->_scanner_profile;
171
318k
    _newly_create_free_blocks_num = _local_state->_newly_create_free_blocks_num;
172
318k
    _scanner_memory_used_counter = _local_state->_memory_used_counter;
173
174
    // 3. get thread token
175
318k
    if (!_state->get_query_ctx()) {
176
0
        return Status::InternalError("Query context of {} is not set",
177
0
                                     print_id(_state->query_id()));
178
0
    }
179
180
319k
    if (_state->get_query_ctx()->get_scan_scheduler()) {
181
319k
        _should_reset_thread_name = false;
182
319k
    }
183
184
318k
    auto scanner = _all_scanners.front().lock();
185
318k
    DCHECK(scanner != nullptr);
186
187
318k
    if (auto* task_executor_scheduler =
188
319k
                dynamic_cast<TaskExecutorSimplifiedScanScheduler*>(_scanner_scheduler)) {
189
319k
        std::shared_ptr<TaskExecutor> task_executor = task_executor_scheduler->task_executor();
190
319k
        _task_executor = task_executor;
191
319k
        TaskId task_id(fmt::format("{}-{}", print_id(_state->query_id()), ctx_id));
192
319k
        _task_handle = DORIS_TRY(task_executor->create_task(
193
319k
                task_id, []() { return 0.0; },
194
319k
                config::task_executor_initial_max_concurrency_per_task > 0
195
319k
                        ? config::task_executor_initial_max_concurrency_per_task
196
319k
                        : std::max(48, CpuInfo::num_cores() * 2),
197
319k
                std::chrono::milliseconds(100), std::nullopt));
198
319k
    }
199
318k
#endif
200
    // _max_bytes_in_queue controls the maximum memory that can be used by a single scan operator.
201
    // scan_queue_mem_limit on FE is 100MB by default, on backend we will make sure its actual value
202
    // is larger than 10MB.
203
318k
    _max_bytes_in_queue = std::max(_state->scan_queue_mem_limit(), (int64_t)1024 * 1024 * 10);
204
205
    // Provide more memory for wide tables, increase proportionally by multiples of 300
206
318k
    _max_bytes_in_queue *= _output_tuple_desc->slots().size() / 300 + 1;
207
208
318k
    if (_all_scanners.empty()) {
209
0
        _is_finished = true;
210
0
        _set_scanner_done();
211
0
    }
212
213
    // Initialize memory limiter if memory-aware scheduling is enabled
214
318k
    if (_enable_adaptive_scanners) {
215
316k
        DCHECK(_scanner_mem_limiter && _mem_share_arb);
216
316k
        int64_t c = _scanner_mem_limiter->update_open_tasks_count(1);
217
        // TODO(gabriel): set estimated block size
218
316k
        _scanner_mem_limiter->reestimated_block_mem_bytes(DEFAULT_SCANNER_MEM_BYTES);
219
316k
        _scanner_mem_limiter->update_arb_mem_bytes(DEFAULT_SCANNER_MEM_BYTES);
220
316k
        if (c == 0) {
221
            // First scanner context to open, adjust scan memory limit
222
247k
            _adjust_scan_mem_limit(DEFAULT_SCANNER_MEM_BYTES,
223
247k
                                   _scanner_mem_limiter->get_arb_scanner_mem_bytes());
224
247k
        }
225
316k
    }
226
227
    // when user not specify scan_thread_num, so we can try downgrade _max_thread_num.
228
    // becaue we found in a table with 5k columns, column reader may ocuppy too much memory.
229
    // you can refer https://github.com/apache/doris/issues/35340 for details.
230
318k
    const int32_t max_column_reader_num = _state->max_column_reader_num();
231
232
318k
    if (_max_scan_concurrency != 1 && max_column_reader_num > 0) {
233
198k
        int32_t scan_column_num = cast_set<int32_t>(_output_tuple_desc->slots().size());
234
198k
        int32_t current_column_num = scan_column_num * _max_scan_concurrency;
235
198k
        if (current_column_num > max_column_reader_num) {
236
0
            int32_t new_max_thread_num = max_column_reader_num / scan_column_num;
237
0
            new_max_thread_num = new_max_thread_num <= 0 ? 1 : new_max_thread_num;
238
0
            if (new_max_thread_num < _max_scan_concurrency) {
239
0
                int32_t origin_max_thread_num = _max_scan_concurrency;
240
0
                _max_scan_concurrency = new_max_thread_num;
241
0
                LOG(INFO) << "downgrade query:" << print_id(_state->query_id())
242
0
                          << " scan's max_thread_num from " << origin_max_thread_num << " to "
243
0
                          << _max_scan_concurrency << ",column num: " << scan_column_num
244
0
                          << ", max_column_reader_num: " << max_column_reader_num;
245
0
            }
246
0
        }
247
198k
    }
248
249
318k
    COUNTER_SET(_local_state->_max_scan_concurrency, (int64_t)_max_scan_concurrency);
250
318k
    COUNTER_SET(_local_state->_min_scan_concurrency, (int64_t)_min_scan_concurrency);
251
252
318k
    std::unique_lock<std::mutex> l(_transfer_lock);
253
318k
    RETURN_IF_ERROR(_scanner_scheduler->schedule_scan_task(shared_from_this(), nullptr, l));
254
255
318k
    return Status::OK();
256
318k
}
257
258
321k
ScannerContext::~ScannerContext() {
259
321k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_resource_ctx->memory_context()->mem_tracker());
260
321k
    _completed_tasks.clear();
261
321k
    BlockUPtr block;
262
537k
    while (_free_blocks.try_dequeue(block)) {
263
        // do nothing
264
215k
    }
265
321k
    block.reset();
266
321k
    DorisMetrics::instance()->scanner_ctx_cnt->increment(-1);
267
268
    // Cleanup memory limiter if last context closing
269
321k
    if (_enable_adaptive_scanners) {
270
316k
        if (_scanner_mem_limiter->update_open_tasks_count(-1) == 1) {
271
            // Last scanner context to close, reset scan memory limit
272
247k
            _adjust_scan_mem_limit(_scanner_mem_limiter->get_arb_scanner_mem_bytes(), 0);
273
247k
        }
274
316k
    }
275
276
321k
    if (_task_handle) {
277
0
        if (auto task_executor = _task_executor.lock()) {
278
0
            static_cast<void>(task_executor->remove_task(_task_handle));
279
0
        }
280
0
        _task_handle = nullptr;
281
0
        _task_executor.reset();
282
0
    }
283
321k
}
284
285
1.54M
BlockUPtr ScannerContext::get_free_block(bool force) {
286
1.54M
    BlockUPtr block = nullptr;
287
1.54M
    if (_free_blocks.try_dequeue(block)) {
288
904k
        DCHECK(block->mem_reuse());
289
904k
        _block_memory_usage -= block->allocated_bytes();
290
904k
        _scanner_memory_used_counter->set(_block_memory_usage);
291
        // A free block is reused, so the memory usage should be decreased
292
        // The caller of get_free_block will increase the memory usage
293
904k
    } else if (_block_memory_usage < _max_bytes_in_queue || force) {
294
643k
        _newly_create_free_blocks_num->update(1);
295
643k
        block = Block::create_unique(_output_tuple_desc->slots(), 0);
296
643k
    }
297
1.54M
    return block;
298
1.54M
}
299
300
1.54M
void ScannerContext::return_free_block(BlockUPtr block) {
301
    // If under low memory mode, should not return the freeblock, it will occupy too much memory.
302
1.54M
    if (!_local_state->low_memory_mode() && block->mem_reuse() &&
303
1.54M
        _block_memory_usage < _max_bytes_in_queue) {
304
1.12M
        size_t block_size_to_reuse = block->allocated_bytes();
305
1.12M
        _block_memory_usage += block_size_to_reuse;
306
1.12M
        _scanner_memory_used_counter->set(_block_memory_usage);
307
1.12M
        block->clear_column_data();
308
        // Free blocks is used to improve memory efficiency. Failure during pushing back
309
        // free block will not incur any bad result so just ignore the return value.
310
1.12M
        _free_blocks.enqueue(std::move(block));
311
1.12M
    }
312
1.54M
}
313
314
Status ScannerContext::submit_scan_task(std::shared_ptr<ScanTask> scan_task,
315
1.54M
                                        std::unique_lock<std::mutex>& /*transfer_lock*/) {
316
    // increase _num_finished_scanners no matter the scan_task is submitted successfully or not.
317
    // since if submit failed, it will be added back by ScannerContext::push_back_scan_task
318
    // and _num_finished_scanners will be reduced.
319
    // if submit succeed, it will be also added back by ScannerContext::push_back_scan_task
320
    // see ScannerScheduler::_scanner_scan.
321
1.54M
    _in_flight_tasks_num++;
322
1.54M
    return _scanner_scheduler->submit(shared_from_this(), scan_task);
323
1.54M
}
324
325
0
void ScannerContext::clear_free_blocks() {
326
0
    clear_blocks(_free_blocks);
327
0
}
328
329
1.54M
void ScannerContext::push_back_scan_task(std::shared_ptr<ScanTask> scan_task) {
330
1.54M
    if (scan_task->status_ok()) {
331
1.54M
        if (scan_task->cached_block && scan_task->cached_block->rows() > 0) {
332
371k
            Status st = validate_block_schema(scan_task->cached_block.get());
333
371k
            if (!st.ok()) {
334
0
                scan_task->set_status(st);
335
0
            }
336
371k
        }
337
1.54M
    }
338
339
1.54M
    std::lock_guard<std::mutex> l(_transfer_lock);
340
1.54M
    if (!scan_task->status_ok()) {
341
1.49k
        _process_status = scan_task->get_status();
342
1.49k
    }
343
1.54M
    _completed_tasks.push_back(scan_task);
344
1.54M
    _in_flight_tasks_num--;
345
346
1.54M
    _dependency->set_ready();
347
1.54M
}
348
349
1.54M
Status ScannerContext::get_block_from_queue(RuntimeState* state, Block* block, bool* eos, int id) {
350
1.54M
    if (state->is_cancelled()) {
351
1
        _set_scanner_done();
352
1
        return state->cancel_reason();
353
1
    }
354
1.54M
    std::unique_lock l(_transfer_lock);
355
356
1.54M
    if (!_process_status.ok()) {
357
1.26k
        _set_scanner_done();
358
1.26k
        return _process_status;
359
1.26k
    }
360
361
1.54M
    std::shared_ptr<ScanTask> scan_task = nullptr;
362
363
1.54M
    if (!_completed_tasks.empty() && !done()) {
364
        // https://en.cppreference.com/w/cpp/container/list/front
365
        // The behavior is undefined if the list is empty.
366
1.54M
        scan_task = _completed_tasks.front();
367
1.54M
        _completed_tasks.pop_front();
368
1.54M
    }
369
370
1.54M
    if (scan_task != nullptr) {
371
        // The abnormal status of scanner may come from the execution of the scanner itself,
372
        // or come from the scanner scheduler, such as TooManyTasks.
373
1.54M
        if (!scan_task->status_ok()) {
374
            // TODO: If the scanner status is TooManyTasks, maybe we can retry the scanner after a while.
375
0
            _process_status = scan_task->get_status();
376
0
            _set_scanner_done();
377
0
            return _process_status;
378
0
        }
379
380
1.54M
        if (scan_task->cached_block) {
381
            // No need to worry about small block, block is merged together when they are appended to cached_blocks.
382
1.54M
            auto current_block = std::move(scan_task->cached_block);
383
1.54M
            auto block_size = current_block->allocated_bytes();
384
1.54M
            scan_task->cached_block.reset();
385
1.54M
            _block_memory_usage -= block_size;
386
            // consume current block
387
1.54M
            block->swap(*current_block);
388
1.54M
            return_free_block(std::move(current_block));
389
1.54M
        }
390
18.4E
        VLOG_DEBUG << fmt::format(
391
18.4E
                "ScannerContext {} get block from queue, current scan "
392
18.4E
                "task remaing cached_block size {}, eos {}, scheduled tasks {}",
393
18.4E
                ctx_id, _completed_tasks.size(), scan_task->is_eos(), _in_flight_tasks_num);
394
1.54M
        if (scan_task->is_eos()) {
395
            // 1. if eos, record a finished scanner.
396
1.42M
            _num_finished_scanners++;
397
1.42M
            RETURN_IF_ERROR(_scanner_scheduler->schedule_scan_task(shared_from_this(), nullptr, l));
398
1.42M
        } else {
399
118k
            scan_task->set_state(ScanTask::State::IN_FLIGHT);
400
118k
            RETURN_IF_ERROR(
401
118k
                    _scanner_scheduler->schedule_scan_task(shared_from_this(), scan_task, l));
402
118k
        }
403
1.54M
    }
404
405
1.54M
    if (_completed_tasks.empty() &&
406
1.54M
        (_num_finished_scanners == _all_scanners.size() ||
407
1.47M
         (_is_shared_scan_limit_exhausted() && _in_flight_tasks_num == 0))) {
408
320k
        _set_scanner_done();
409
320k
        _is_finished = true;
410
320k
    }
411
412
1.54M
    *eos = done();
413
414
1.54M
    if (_completed_tasks.empty()) {
415
1.47M
        _dependency->block();
416
1.47M
    }
417
418
1.54M
    return Status::OK();
419
1.54M
}
420
421
371k
Status ScannerContext::validate_block_schema(Block* block) {
422
371k
    size_t index = 0;
423
1.32M
    for (auto& slot : _output_tuple_desc->slots()) {
424
1.32M
        auto& data = block->get_by_position(index++);
425
1.32M
        if (data.column->is_nullable() != data.type->is_nullable()) {
426
0
            return Status::Error<ErrorCode::INVALID_SCHEMA>(
427
0
                    "column(name: {}) nullable({}) does not match type nullable({}), slot(id: "
428
0
                    "{}, "
429
0
                    "name:{})",
430
0
                    data.name, data.column->is_nullable(), data.type->is_nullable(), slot->id(),
431
0
                    slot->col_name());
432
0
        }
433
434
1.32M
        if (data.column->is_nullable() != slot->is_nullable()) {
435
0
            return Status::Error<ErrorCode::INVALID_SCHEMA>(
436
0
                    "column(name: {}) nullable({}) does not match slot(id: {}, name: {}) "
437
0
                    "nullable({})",
438
0
                    data.name, data.column->is_nullable(), slot->id(), slot->col_name(),
439
0
                    slot->is_nullable());
440
0
        }
441
1.32M
    }
442
371k
    return Status::OK();
443
371k
}
444
445
642k
void ScannerContext::stop_scanners(RuntimeState* state) {
446
642k
    std::lock_guard<std::mutex> l(_transfer_lock);
447
642k
    if (_should_stop) {
448
320k
        return;
449
320k
    }
450
322k
    _should_stop = true;
451
322k
    _set_scanner_done();
452
1.43M
    for (const std::weak_ptr<ScannerDelegate>& scanner : _all_scanners) {
453
1.43M
        if (std::shared_ptr<ScannerDelegate> sc = scanner.lock()) {
454
1.43M
            sc->_scanner->try_stop();
455
1.43M
        }
456
1.43M
    }
457
322k
    _completed_tasks.clear();
458
322k
    if (_task_handle) {
459
322k
        if (auto task_executor = _task_executor.lock()) {
460
322k
            static_cast<void>(task_executor->remove_task(_task_handle));
461
322k
        }
462
322k
        _task_handle = nullptr;
463
322k
        _task_executor.reset();
464
322k
    }
465
    // TODO yiguolei, call mark close to scanners
466
322k
    if (state->enable_profile()) {
467
2.72k
        std::stringstream scanner_statistics;
468
2.72k
        std::stringstream scanner_rows_read;
469
2.72k
        std::stringstream scanner_wait_worker_time;
470
2.72k
        std::stringstream scanner_projection;
471
2.72k
        std::stringstream scanner_prepare_time;
472
2.72k
        std::stringstream scanner_open_time;
473
2.72k
        scanner_statistics << "[";
474
2.72k
        scanner_rows_read << "[";
475
2.72k
        scanner_wait_worker_time << "[";
476
2.72k
        scanner_projection << "[";
477
2.72k
        scanner_prepare_time << "[";
478
2.72k
        scanner_open_time << "[";
479
        // Scanners can in 3 state
480
        //  state 1: in scanner context, not scheduled
481
        //  state 2: in scanner worker pool's queue, scheduled but not running
482
        //  state 3: scanner is running.
483
5.98k
        for (auto& scanner_ref : _all_scanners) {
484
5.98k
            auto scanner = scanner_ref.lock();
485
5.98k
            if (scanner == nullptr) {
486
0
                continue;
487
0
            }
488
            // Add per scanner running time before close them
489
5.98k
            scanner_statistics << PrettyPrinter::print(scanner->_scanner->get_time_cost_ns(),
490
5.98k
                                                       TUnit::TIME_NS)
491
5.98k
                               << ", ";
492
5.98k
            scanner_projection << PrettyPrinter::print(scanner->_scanner->projection_time(),
493
5.98k
                                                       TUnit::TIME_NS)
494
5.98k
                               << ", ";
495
5.98k
            scanner_rows_read << PrettyPrinter::print(scanner->_scanner->get_rows_read(),
496
5.98k
                                                      TUnit::UNIT)
497
5.98k
                              << ", ";
498
5.98k
            scanner_wait_worker_time
499
5.98k
                    << PrettyPrinter::print(scanner->_scanner->get_scanner_wait_worker_timer(),
500
5.98k
                                            TUnit::TIME_NS)
501
5.98k
                    << ", ";
502
5.98k
            scanner_prepare_time << PrettyPrinter::print(
503
5.98k
                                            scanner->_scanner->get_prepare_time_cost_ns(),
504
5.98k
                                            TUnit::TIME_NS)
505
5.98k
                                 << ", ";
506
5.98k
            scanner_open_time << PrettyPrinter::print(scanner->_scanner->get_open_time_cost_ns(),
507
5.98k
                                                      TUnit::TIME_NS)
508
5.98k
                              << ", ";
509
            // since there are all scanners, some scanners is running, so that could not call scanner
510
            // close here.
511
5.98k
        }
512
2.72k
        scanner_statistics << "]";
513
2.72k
        scanner_rows_read << "]";
514
2.72k
        scanner_wait_worker_time << "]";
515
2.72k
        scanner_projection << "]";
516
2.72k
        scanner_prepare_time << "]";
517
2.72k
        scanner_open_time << "]";
518
2.72k
        _scanner_profile->add_info_string("PerScannerRunningTime", scanner_statistics.str());
519
2.72k
        _scanner_profile->add_info_string("PerScannerRowsRead", scanner_rows_read.str());
520
2.72k
        _scanner_profile->add_info_string("PerScannerWaitTime", scanner_wait_worker_time.str());
521
2.72k
        _scanner_profile->add_info_string("PerScannerProjectionTime", scanner_projection.str());
522
2.72k
        _scanner_profile->add_info_string("PerScannerPrepareTime", scanner_prepare_time.str());
523
2.72k
        _scanner_profile->add_info_string("PerScannerOpenTime", scanner_open_time.str());
524
2.72k
    }
525
322k
}
526
527
18
std::string ScannerContext::debug_string() {
528
18
    return fmt::format(
529
18
            "_query_id: {}, id: {}, total scanners: {}, pending tasks: {}, completed tasks: {},"
530
18
            " _should_stop: {}, _is_finished: {}, free blocks: {},"
531
18
            " limit: {}, _in_flight_tasks_num: {}, remaining_limit: {}, _num_running_scanners: {}, "
532
18
            "_max_thread_num: {},"
533
18
            " _max_bytes_in_queue: {}, _ins_idx: {}, _enable_adaptive_scanners: {}, "
534
18
            "_mem_share_arb: {}, _scanner_mem_limiter: {}",
535
18
            print_id(_query_id), ctx_id, _all_scanners.size(), _pending_tasks.size(),
536
18
            _completed_tasks.size(), _should_stop, _is_finished, _free_blocks.size_approx(), limit,
537
18
            _shared_scan_limit->load(std::memory_order_relaxed), _in_flight_tasks_num,
538
18
            _num_finished_scanners, _max_scan_concurrency, _max_bytes_in_queue, _ins_idx,
539
18
            _enable_adaptive_scanners,
540
18
            _enable_adaptive_scanners ? _mem_share_arb->debug_string() : "NULL",
541
18
            _enable_adaptive_scanners ? _scanner_mem_limiter->debug_string() : "NULL");
542
18
}
543
544
643k
void ScannerContext::_set_scanner_done() {
545
643k
    _dependency->set_always_ready();
546
643k
}
547
548
2.58M
bool ScannerContext::_is_shared_scan_limit_exhausted() const {
549
2.58M
    return limit >= 0 && _shared_scan_limit->load(std::memory_order_acquire) <= 0;
550
2.58M
}
551
552
3.09M
void ScannerContext::update_peak_running_scanner(int num) {
553
3.09M
#ifndef BE_TEST
554
3.09M
    _local_state->_peak_running_scanner->add(num);
555
3.09M
#endif
556
3.09M
    if (_enable_adaptive_scanners) {
557
3.06M
        _scanner_mem_limiter->update_running_tasks_count(num);
558
3.06M
    }
559
3.09M
}
560
561
1.54M
void ScannerContext::reestimated_block_mem_bytes(int64_t num) {
562
1.54M
    if (_enable_adaptive_scanners) {
563
1.53M
        _scanner_mem_limiter->reestimated_block_mem_bytes(num);
564
1.53M
    }
565
1.54M
}
566
567
int32_t ScannerContext::_get_margin(std::unique_lock<std::mutex>& transfer_lock,
568
1.86M
                                    std::unique_lock<std::shared_mutex>& scheduler_lock) {
569
    // Get effective max concurrency considering adaptive scheduling
570
1.86M
    int32_t effective_max_concurrency = _available_pickup_scanner_count();
571
1.86M
    DCHECK_LE(effective_max_concurrency, _max_scan_concurrency);
572
573
    // margin_1 is used to ensure each scan operator could have at least _min_scan_concurrency scan tasks.
574
1.86M
    int32_t margin_1 = _min_scan_concurrency -
575
1.86M
                       (cast_set<int32_t>(_completed_tasks.size()) + _in_flight_tasks_num);
576
577
    // margin_2 is used to ensure the scan scheduler could have at least _min_scan_concurrency_of_scan_scheduler scan tasks.
578
1.86M
    int32_t margin_2 =
579
1.86M
            _min_scan_concurrency_of_scan_scheduler -
580
1.86M
            (_scanner_scheduler->get_active_threads() + _scanner_scheduler->get_queue_size());
581
582
    // margin_3 is used to respect adaptive max concurrency limit
583
1.86M
    int32_t margin_3 =
584
1.86M
            std::max(effective_max_concurrency -
585
1.86M
                             (cast_set<int32_t>(_completed_tasks.size()) + _in_flight_tasks_num),
586
1.86M
                     1);
587
588
1.86M
    if (margin_1 <= 0 && margin_2 <= 0) {
589
1
        return 0;
590
1
    }
591
592
1.86M
    int32_t margin = std::max(margin_1, margin_2);
593
1.86M
    if (_enable_adaptive_scanners) {
594
1.84M
        margin = std::min(margin, margin_3); // Cap by adaptive limit
595
1.84M
    }
596
597
1.86M
    if (low_memory_mode()) {
598
        // In low memory mode, we will limit the number of running scanners to `low_memory_mode_scanners()`.
599
        // So that we will not submit too many scan tasks to scheduler.
600
0
        margin = std::min(low_memory_mode_scanners() - _in_flight_tasks_num, margin);
601
0
    }
602
603
1.86M
    VLOG_DEBUG << fmt::format(
604
5
            "[{}|{}] schedule scan task, margin_1: {} = {} - ({} + {}), margin_2: {} = {} - "
605
5
            "({} + {}), margin_3: {} = {} - ({} + {}), margin: {}, adaptive: {}",
606
5
            print_id(_query_id), ctx_id, margin_1, _min_scan_concurrency, _completed_tasks.size(),
607
5
            _in_flight_tasks_num, margin_2, _min_scan_concurrency_of_scan_scheduler,
608
5
            _scanner_scheduler->get_active_threads(), _scanner_scheduler->get_queue_size(),
609
5
            margin_3, effective_max_concurrency, _completed_tasks.size(), _in_flight_tasks_num,
610
5
            margin, _enable_adaptive_scanners);
611
612
1.86M
    return margin;
613
1.86M
}
614
615
// This function must be called with:
616
// 1. _transfer_lock held.
617
// 2. ScannerScheduler::_lock held.
618
Status ScannerContext::schedule_scan_task(std::shared_ptr<ScanTask> current_scan_task,
619
                                          std::unique_lock<std::mutex>& transfer_lock,
620
1.86M
                                          std::unique_lock<std::shared_mutex>& scheduler_lock) {
621
1.86M
    if (current_scan_task &&
622
1.86M
        (current_scan_task->cached_block != nullptr || current_scan_task->is_eos())) {
623
1
        throw doris::Exception(ErrorCode::INTERNAL_ERROR, "Scanner scheduler logical error.");
624
1
    }
625
626
1.86M
    std::list<std::shared_ptr<ScanTask>> tasks_to_submit;
627
628
1.86M
    int32_t margin = _get_margin(transfer_lock, scheduler_lock);
629
630
    // margin is less than zero. Means this scan operator could not submit any scan task for now.
631
1.86M
    if (margin <= 0) {
632
        // Be careful with current scan task.
633
        // We need to add it back to task queue to make sure it could be resubmitted.
634
0
        if (current_scan_task) {
635
            // This usually happens when we should downgrade the concurrency.
636
0
            current_scan_task->set_state(ScanTask::State::PENDING);
637
0
            _pending_tasks.push(current_scan_task);
638
0
            VLOG_DEBUG << fmt::format(
639
0
                    "{} push back scanner to task queue, because diff <= 0, _completed_tasks size "
640
0
                    "{}, _in_flight_tasks_num {}",
641
0
                    ctx_id, _completed_tasks.size(), _in_flight_tasks_num);
642
0
        }
643
644
0
#ifndef NDEBUG
645
        // This DCHECK is necessary.
646
        // We need to make sure each scan operator could have at least 1 scan tasks.
647
        // Or this scan operator will not be re-scheduled.
648
0
        if (!_pending_tasks.empty() && _in_flight_tasks_num == 0 && _completed_tasks.empty()) {
649
0
            throw doris::Exception(ErrorCode::INTERNAL_ERROR, "Scanner scheduler logical error.");
650
0
        }
651
0
#endif
652
653
0
        return Status::OK();
654
0
    }
655
656
1.86M
    bool first_pull = true;
657
658
3.41M
    while (margin-- > 0) {
659
1.96M
        std::shared_ptr<ScanTask> task_to_run;
660
1.96M
        const int32_t current_concurrency = cast_set<int32_t>(
661
1.96M
                _completed_tasks.size() + _in_flight_tasks_num + tasks_to_submit.size());
662
1.96M
        VLOG_DEBUG << fmt::format("{} currenct concurrency: {} = {} + {} + {}", ctx_id,
663
8
                                  current_concurrency, _completed_tasks.size(),
664
8
                                  _in_flight_tasks_num, tasks_to_submit.size());
665
1.96M
        if (first_pull) {
666
1.86M
            task_to_run = _pull_next_scan_task(current_scan_task, current_concurrency);
667
1.86M
            if (task_to_run == nullptr) {
668
                // In three situations we will get nullptr.
669
                // 1. current_concurrency already reached _max_scan_concurrency.
670
                // 2. all scanners are finished.
671
                // 3. The shared LIMIT is exhausted while completed or in-flight tasks can still
672
                //    make progress.
673
394k
                if (current_scan_task) {
674
1
                    DCHECK(current_scan_task->cached_block == nullptr);
675
1
                    DCHECK(!current_scan_task->is_eos());
676
1
                    if (current_scan_task->cached_block != nullptr || current_scan_task->is_eos()) {
677
                        // This should not happen.
678
0
                        throw doris::Exception(ErrorCode::INTERNAL_ERROR,
679
0
                                               "Scanner scheduler logical error.");
680
0
                    }
681
                    // Current scan task is not scheduled, we need to add it back to task queue to make sure it could be resubmitted.
682
1
                    current_scan_task->set_state(ScanTask::State::PENDING);
683
1
                    _pending_tasks.push(current_scan_task);
684
1
                }
685
394k
            }
686
1.86M
            first_pull = false;
687
1.86M
        } else {
688
98.6k
            task_to_run = _pull_next_scan_task(nullptr, current_concurrency);
689
98.6k
        }
690
691
1.96M
        if (task_to_run) {
692
1.54M
            tasks_to_submit.push_back(task_to_run);
693
1.54M
        } else {
694
418k
            break;
695
418k
        }
696
1.96M
    }
697
698
1.86M
    if (tasks_to_submit.empty()) {
699
394k
        return Status::OK();
700
394k
    }
701
702
1.47M
    VLOG_DEBUG << fmt::format("[{}:{}] submit {} scan tasks to scheduler, remaining scanner: {}",
703
1
                              print_id(_query_id), ctx_id, tasks_to_submit.size(),
704
1
                              _pending_tasks.size());
705
706
1.54M
    for (auto& scan_task_iter : tasks_to_submit) {
707
1.54M
        Status submit_status = submit_scan_task(scan_task_iter, transfer_lock);
708
1.54M
        if (!submit_status.ok()) {
709
0
            _process_status = submit_status;
710
0
            _set_scanner_done();
711
0
            return _process_status;
712
0
        }
713
1.54M
    }
714
715
1.47M
    return Status::OK();
716
1.47M
}
717
718
std::shared_ptr<ScanTask> ScannerContext::_pull_next_scan_task(
719
1.96M
        std::shared_ptr<ScanTask> current_scan_task, int32_t current_concurrency) {
720
1.96M
    int32_t effective_max_concurrency = _max_scan_concurrency;
721
1.96M
    if (_enable_adaptive_scanners) {
722
1.93M
        effective_max_concurrency = _adaptive_processor->expected_scanners > 0
723
1.93M
                                            ? _adaptive_processor->expected_scanners
724
1.93M
                                            : _max_scan_concurrency;
725
1.93M
    }
726
727
1.96M
    if (current_concurrency >= effective_max_concurrency) {
728
14.4k
        VLOG_DEBUG << fmt::format(
729
0
                "ScannerContext {} current concurrency {} >= effective_max_concurrency {}, skip "
730
0
                "pull",
731
0
                ctx_id, current_concurrency, effective_max_concurrency);
732
14.4k
        return nullptr;
733
14.4k
    }
734
735
1.95M
    if (current_scan_task != nullptr) {
736
118k
        if (current_scan_task->cached_block != nullptr || current_scan_task->is_eos()) {
737
            // This should not happen.
738
2
            throw doris::Exception(ErrorCode::INTERNAL_ERROR, "Scanner scheduler logical error.");
739
2
        }
740
118k
        return current_scan_task;
741
118k
    }
742
743
1.83M
    if (!_pending_tasks.empty()) {
744
        // Do not submit more pending scanners after the shared LIMIT is exhausted while
745
        // completed or in-flight tasks can still make progress. If neither exists, allow pending
746
        // scanners to be submitted so they can report EOS and wake the pipeline task.
747
1.43M
        if (_is_shared_scan_limit_exhausted() &&
748
1.43M
            (_in_flight_tasks_num != 0 || !_completed_tasks.empty())) {
749
0
            return nullptr;
750
0
        }
751
1.43M
        std::shared_ptr<ScanTask> next_scan_task;
752
1.43M
        next_scan_task = _pending_tasks.top();
753
1.43M
        _pending_tasks.pop();
754
1.43M
        return next_scan_task;
755
1.43M
    } else {
756
404k
        return nullptr;
757
404k
    }
758
1.83M
}
759
760
6.50M
bool ScannerContext::low_memory_mode() const {
761
6.50M
    return _local_state->low_memory_mode();
762
6.50M
}
763
} // namespace doris