Coverage Report

Created: 2026-08-04 11:20

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