Coverage Report

Created: 2026-08-21 09:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/scanner_context.h
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
#pragma once
19
20
#include <bthread/types.h>
21
#include <stdint.h>
22
23
#include <atomic>
24
#include <cstdint>
25
#include <list>
26
#include <memory>
27
#include <mutex>
28
#include <stack>
29
#include <string>
30
#include <utility>
31
#include <vector>
32
33
#include "common/config.h"
34
#include "common/factory_creator.h"
35
#include "common/metrics/doris_metrics.h"
36
#include "common/status.h"
37
#include "concurrentqueue.h"
38
#include "core/block/block.h"
39
#include "exec/common/memory.h"
40
#include "exec/scan/scanner.h"
41
#include "exec/scan/task_executor/split_runner.h"
42
#include "runtime/runtime_profile.h"
43
44
namespace doris {
45
46
class ResourceContext;
47
class RuntimeState;
48
class TupleDescriptor;
49
class WorkloadGroup;
50
51
class ScanLocalStateBase;
52
class Dependency;
53
54
class Scanner;
55
class ScannerDelegate;
56
class ScannerScheduler;
57
class TaskExecutor;
58
class TaskHandle;
59
60
// Adaptive processor for dynamic scanner concurrency adjustment
61
struct ScannerAdaptiveProcessor {
62
    ENABLE_FACTORY_CREATOR(ScannerAdaptiveProcessor)
63
1.09k
    ScannerAdaptiveProcessor() = default;
64
    ~ScannerAdaptiveProcessor() = default;
65
    // Expected scanners in this cycle
66
67
    int expected_scanners = 0;
68
    // Timing metrics
69
    // int64_t context_start_time = 0;
70
    // int64_t scanner_total_halt_time = 0;
71
    // int64_t scanner_gen_blocks_time = 0;
72
    // std::atomic_int64_t scanner_total_io_time = 0;
73
    // std::atomic_int64_t scanner_total_running_time = 0;
74
    // std::atomic_int64_t scanner_total_scan_bytes = 0;
75
76
    // Timestamps
77
    // std::atomic_int64_t last_scanner_finish_timestamp = 0;
78
    // int64_t check_all_scanners_last_timestamp = 0;
79
    // int64_t last_driver_output_full_timestamp = 0;
80
    int64_t adjust_scanners_last_timestamp = 0;
81
82
    // Adjustment strategy fields
83
    // bool try_add_scanners = false;
84
    // double expected_speedup_ratio = 0;
85
    // double last_scanner_scan_speed = 0;
86
    // int64_t last_scanner_total_scan_bytes = 0;
87
    // int try_add_scanners_fail_count = 0;
88
    // int check_slow_io = 0;
89
    // int32_t slow_io_latency_ms = 100; // Default from config
90
};
91
92
class ScanTask {
93
public:
94
    enum class State : int {
95
        PENDING,   // not scheduled yet
96
        IN_FLIGHT, // scheduled and running
97
        COMPLETED, // finished with result or error, waiting to be collected by scan node
98
        EOS,       // finished and no more data, waiting to be collected by scan node
99
    };
100
    ScanTask(std::weak_ptr<ScannerDelegate> delegate_scanner);
101
102
    ~ScanTask();
103
104
private:
105
    // whether current scanner is finished
106
    Status status = Status::OK();
107
    std::shared_ptr<ResourceContext> _resource_ctx;
108
    State _state = State::PENDING;
109
110
public:
111
    std::weak_ptr<ScannerDelegate> scanner;
112
    BlockUPtr cached_block = nullptr;
113
    bool is_first_schedule = true;
114
    // Use weak_ptr to avoid circular references and potential memory leaks with SplitRunner.
115
    // ScannerContext only needs to observe the lifetime of SplitRunner without owning it.
116
    // When SplitRunner is destroyed, split_runner.lock() will return nullptr, ensuring safe access.
117
    std::weak_ptr<SplitRunner> split_runner;
118
119
0
    void set_status(Status _status) {
120
0
        if (_status.is<ErrorCode::END_OF_FILE>()) {
121
            // set `eos` if `END_OF_FILE`, don't take `END_OF_FILE` as error
122
0
            _state = State::EOS;
123
0
        }
124
0
        status = _status;
125
0
    }
126
0
    Status get_status() const { return status; }
127
63.6k
    bool status_ok() { return status.ok() || status.is<ErrorCode::END_OF_FILE>(); }
128
42.6k
    bool is_eos() const { return _state == State::EOS; }
129
42.5k
    void set_state(State state) {
130
42.5k
        switch (state) {
131
1
        case State::PENDING:
132
1
            DCHECK(_state == State::PENDING || _state == State::IN_FLIGHT) << (int)_state;
133
1
            DCHECK(cached_block == nullptr);
134
1
            break;
135
21.3k
        case State::IN_FLIGHT:
136
21.3k
            DCHECK(_state == State::COMPLETED || _state == State::PENDING ||
137
0
                   _state == State::IN_FLIGHT)
138
0
                    << (int)_state;
139
21.3k
            DCHECK(cached_block == nullptr);
140
21.3k
            break;
141
112
        case State::COMPLETED:
142
112
            DCHECK(_state == State::IN_FLIGHT) << (int)_state;
143
112
            DCHECK(cached_block != nullptr);
144
112
            break;
145
21.1k
        case State::EOS:
146
18.4E
            DCHECK(_state == State::IN_FLIGHT || status.is<ErrorCode::END_OF_FILE>())
147
18.4E
                    << (int)_state;
148
21.1k
            break;
149
0
        default:
150
0
            break;
151
42.5k
        }
152
153
42.5k
        _state = state;
154
42.5k
    }
155
};
156
157
// ScannerContext is responsible for recording the execution status
158
// of a group of Scanners corresponding to a ScanNode.
159
// Including how many scanners are being scheduled, and maintaining
160
// a producer-consumer blocks queue between scanners and scan nodes.
161
//
162
// ScannerContext is also the scheduling unit of ScannerScheduler.
163
// ScannerScheduler schedules a ScannerContext at a time,
164
// and submits the Scanners to the scanner thread pool for data scanning.
165
class ScannerContext : public std::enable_shared_from_this<ScannerContext>,
166
                       public HasTaskExecutionCtx {
167
    ENABLE_FACTORY_CREATOR(ScannerContext);
168
    friend class ScannerScheduler;
169
170
public:
171
    ScannerContext(RuntimeState* state, ScanLocalStateBase* local_state,
172
                   const TupleDescriptor* output_tuple_desc, bool has_projection,
173
                   const std::list<std::shared_ptr<ScannerDelegate>>& scanners, int64_t limit_,
174
                   std::shared_ptr<Dependency> dependency, std::atomic<int64_t>* shared_scan_limit,
175
                   std::shared_ptr<MemShareArbitrator> arb, std::shared_ptr<MemLimiter> limiter,
176
                   int ins_idx, bool enable_adaptive_scan
177
#ifdef BE_TEST
178
                   ,
179
                   int num_parallel_instances
180
#endif
181
    );
182
183
    ~ScannerContext() override;
184
    Status init();
185
186
    // TODO(gabriel): we can also consider to return a list of blocks to reduce the scheduling overhead, but it may cause larger memory usage and more complex logic of block management.
187
    BlockUPtr get_free_block(bool force);
188
    void return_free_block(BlockUPtr block);
189
    void clear_free_blocks();
190
21.2k
    inline void inc_block_usage(size_t usage) { _block_memory_usage += usage; }
191
192
21.2k
    int64_t block_memory_usage() { return _block_memory_usage; }
193
194
    // Caller should make sure the pipeline task is still running when calling this function
195
    void update_peak_running_scanner(int num);
196
    void reestimated_block_mem_bytes(int64_t num);
197
198
    // Get next block from blocks queue. Called by ScanNode/ScanOperator
199
    // Set eos to true if there is no more data to read.
200
    Status get_block_from_queue(RuntimeState* state, Block* block, bool* eos, int id);
201
202
    [[nodiscard]] Status validate_block_schema(Block* block);
203
204
    // submit the running scanner to thread pool in `ScannerScheduler`
205
    // set the next scanned block to `ScanTask::current_block`
206
    // set the error state to `ScanTask::status`
207
    // set the `eos` to `ScanTask::eos` if there is no more data in current scanner
208
    Status submit_scan_task(std::shared_ptr<ScanTask> scan_task, std::unique_lock<std::mutex>&);
209
210
    // Push back a scan task.
211
    void push_back_scan_task(std::shared_ptr<ScanTask> scan_task);
212
213
    // Return true if this ScannerContext need no more process
214
84.9k
    bool done() const { return _is_finished || _should_stop; }
215
216
    std::string debug_string();
217
218
21.2k
    std::shared_ptr<TaskHandle> task_handle() const { return _task_handle; }
219
220
0
    std::shared_ptr<ResourceContext> resource_ctx() const { return _resource_ctx; }
221
222
42.4k
    RuntimeState* state() { return _state; }
223
224
    void stop_scanners(RuntimeState* state);
225
226
4.93k
    int batch_size() const { return _batch_size; }
227
228
    // During low memory mode, there will be at most 4 scanners running and every scanner will
229
    // cache at most 1MB data. So that every instance will keep 8MB buffer.
230
    bool low_memory_mode() const;
231
232
    // TODO(yiguolei) add this as session variable
233
0
    int32_t low_memory_mode_scan_bytes_per_scanner() const {
234
0
        return 1 * 1024 * 1024; // 1MB
235
0
    }
236
237
0
    int32_t low_memory_mode_scanners() const { return 4; }
238
239
0
    ScanLocalStateBase* local_state() const { return _local_state; }
240
241
    // the unique id of this context
242
    std::string ctx_id;
243
    TUniqueId _query_id;
244
245
    bool _should_reset_thread_name = true;
246
247
0
    int32_t num_scheduled_scanners() {
248
0
        std::lock_guard<std::mutex> l(_transfer_lock);
249
0
        return _in_flight_tasks_num;
250
0
    }
251
252
    Status schedule_scan_task(std::shared_ptr<ScanTask> current_scan_task,
253
                              std::unique_lock<std::mutex>& transfer_lock,
254
                              std::unique_lock<std::shared_mutex>& scheduler_lock);
255
256
protected:
257
    /// Four criteria to determine whether to increase the parallelism of the scanners
258
    /// 1. It ran for at least `SCALE_UP_DURATION` ms after last scale up
259
    /// 2. Half(`WAIT_BLOCK_DURATION_RATIO`) of the duration is waiting to get blocks
260
    /// 3. `_free_blocks_memory_usage` < `_max_bytes_in_queue`, remains enough memory to scale up
261
    /// 4. At most scale up `MAX_SCALE_UP_RATIO` times to `_max_thread_num`
262
    void _set_scanner_done();
263
    bool _is_shared_scan_limit_exhausted() const;
264
265
    RuntimeState* _state = nullptr;
266
    ScanLocalStateBase* _local_state = nullptr;
267
268
    // the comment of same fields in VScanNode
269
    const TupleDescriptor* _output_tuple_desc = nullptr;
270
271
    Status _process_status = Status::OK();
272
    std::atomic_bool _should_stop = false;
273
    std::atomic_bool _is_finished = false;
274
275
    // Lazy-allocated blocks for all scanners to share, for memory reuse.
276
    moodycamel::ConcurrentQueue<BlockUPtr> _free_blocks;
277
278
    int _batch_size;
279
    // The limit from SQL's limit clause
280
    int64_t limit;
281
    // Points to the shared remaining limit on ScanOperatorX, shared across all
282
    // parallel instances and their scanners. -1 means no limit.
283
    std::atomic<int64_t>* _shared_scan_limit = nullptr;
284
285
    int64_t _max_bytes_in_queue = 0;
286
    // _transfer_lock protects _completed_tasks, _pending_tasks, and all other shared state
287
    // accessed by both the scanner thread pool and the operator (get_block_from_queue).
288
    std::mutex _transfer_lock;
289
290
    // Together, _completed_tasks and _in_flight_tasks_num represent all "occupied" concurrency
291
    // slots.  The scheduler uses their sum as the current concurrency:
292
    //
293
    //   current_concurrency = _completed_tasks.size() + _in_flight_tasks_num
294
    //
295
    // Lifecycle of a ScanTask:
296
    //   _pending_tasks  --(submit_scan_task)--> [thread pool]  --(push_back_scan_task)-->
297
    //   _completed_tasks  --(get_block_from_queue)--> operator
298
    //   After consumption: non-EOS task goes back to _pending_tasks; EOS increments
299
    //   _num_finished_scanners.
300
301
    // Completed scan tasks whose cached_block is ready for the operator to consume.
302
    // Protected by _transfer_lock.  Written by push_back_scan_task() (scanner thread),
303
    // read/popped by get_block_from_queue() (operator thread).
304
    std::list<std::shared_ptr<ScanTask>> _completed_tasks;
305
306
    // Scanners waiting to be submitted to the scheduler thread pool.  Stored as a stack
307
    // (LIFO) so that recently-used scanners are re-scheduled first, which is more likely
308
    // to be cache-friendly.  Protected by _transfer_lock.  Populated in the constructor
309
    // and by schedule_scan_task() when the concurrency limit is reached; drained by
310
    // _pull_next_scan_task() during scheduling.
311
    std::stack<std::shared_ptr<ScanTask>> _pending_tasks;
312
313
    // Number of scan tasks currently submitted to the scanner scheduler thread pool
314
    // (i.e. in-flight).  Incremented by submit_scan_task() before submission and
315
    // decremented by push_back_scan_task() when the thread pool returns the task.
316
    // Declared atomic so it can be read without _transfer_lock in non-critical paths,
317
    // but must be read under _transfer_lock whenever combined with _completed_tasks.size()
318
    // to form a consistent concurrency snapshot.
319
    std::atomic_int _in_flight_tasks_num = 0;
320
    // Scanner that is eos or error.
321
    int32_t _num_finished_scanners = 0;
322
    // weak pointer for _scanners, used in stop function
323
    std::vector<std::weak_ptr<ScannerDelegate>> _all_scanners;
324
    std::shared_ptr<RuntimeProfile> _scanner_profile;
325
    // This counter refers to scan operator's local state
326
    RuntimeProfile::Counter* _scanner_memory_used_counter = nullptr;
327
    RuntimeProfile::Counter* _newly_create_free_blocks_num = nullptr;
328
    RuntimeProfile::Counter* _scale_up_scanners_counter = nullptr;
329
    std::shared_ptr<ResourceContext> _resource_ctx;
330
    std::shared_ptr<Dependency> _dependency = nullptr;
331
    std::shared_ptr<doris::TaskHandle> _task_handle;
332
    std::weak_ptr<doris::TaskExecutor> _task_executor;
333
334
    std::atomic<int64_t> _block_memory_usage = 0;
335
336
    // adaptive scan concurrency related
337
338
    ScannerScheduler* _scanner_scheduler = nullptr;
339
    MOCK_REMOVE(const) int32_t _min_scan_concurrency_of_scan_scheduler = 0;
340
    // The overall target of our system is to make full utilization of the resources.
341
    // At the same time, we dont want too many tasks are queued by scheduler, that is not necessary.
342
    // Each scan operator can submit _max_scan_concurrency scanner to scheduelr if scheduler has enough resource.
343
    // So that for a single query, we can make sure it could make full utilization of the resource.
344
    int32_t _max_scan_concurrency = 0;
345
    MOCK_REMOVE(const) int32_t _min_scan_concurrency = 1;
346
347
    std::shared_ptr<ScanTask> _pull_next_scan_task(std::shared_ptr<ScanTask> current_scan_task,
348
                                                   int32_t current_concurrency);
349
350
    int32_t _get_margin(std::unique_lock<std::mutex>& transfer_lock,
351
                        std::unique_lock<std::shared_mutex>& scheduler_lock);
352
353
    // Memory-aware adaptive scheduling
354
    std::shared_ptr<MemLimiter> _scanner_mem_limiter = nullptr;
355
    std::shared_ptr<MemShareArbitrator> _mem_share_arb = nullptr;
356
    std::shared_ptr<ScannerAdaptiveProcessor> _adaptive_processor = nullptr;
357
    const int _ins_idx;
358
    const bool _enable_adaptive_scanners = false;
359
360
    // Adjust scan memory limit based on arbitrator feedback
361
    void _adjust_scan_mem_limit(int64_t old_scanner_mem_bytes, int64_t new_scanner_mem_bytes);
362
363
    // Calculate available scanner count for adaptive scheduling
364
    int _available_pickup_scanner_count();
365
366
    // TODO: Add implementation of runtime_info_feed_back
367
    // adaptive scan concurrency related end
368
};
369
} // namespace doris