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 | 18 | 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 | 11 | bool status_ok() { return status.ok() || status.is<ErrorCode::END_OF_FILE>(); } |
128 | 6 | bool is_eos() const { return _state == State::EOS; } |
129 | 3 | void set_state(State state) { |
130 | 3 | 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 | 0 | case State::IN_FLIGHT: |
136 | 0 | DCHECK(_state == State::COMPLETED || _state == State::PENDING || |
137 | 0 | _state == State::IN_FLIGHT) |
138 | 0 | << (int)_state; |
139 | 0 | DCHECK(cached_block == nullptr); |
140 | 0 | break; |
141 | 0 | case State::COMPLETED: |
142 | 0 | DCHECK(_state == State::IN_FLIGHT) << (int)_state; |
143 | 0 | DCHECK(cached_block != nullptr); |
144 | 0 | break; |
145 | 2 | case State::EOS: |
146 | 2 | DCHECK(_state == State::IN_FLIGHT || status.is<ErrorCode::END_OF_FILE>()) |
147 | 0 | << (int)_state; |
148 | 2 | break; |
149 | 0 | default: |
150 | 0 | break; |
151 | 3 | } |
152 | | |
153 | 3 | _state = state; |
154 | 3 | } |
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, |
173 | | const RowDescriptor* output_row_descriptor, |
174 | | const std::list<std::shared_ptr<ScannerDelegate>>& scanners, int64_t limit_, |
175 | | std::shared_ptr<Dependency> dependency, std::atomic<int64_t>* shared_scan_limit, |
176 | | std::shared_ptr<MemShareArbitrator> arb, std::shared_ptr<MemLimiter> limiter, |
177 | | int ins_idx, bool enable_adaptive_scan |
178 | | #ifdef BE_TEST |
179 | | , |
180 | | int num_parallel_instances |
181 | | #endif |
182 | | ); |
183 | | |
184 | | ~ScannerContext() override; |
185 | | Status init(); |
186 | | |
187 | | // 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. |
188 | | BlockUPtr get_free_block(bool force); |
189 | | void return_free_block(BlockUPtr block); |
190 | | void clear_free_blocks(); |
191 | 0 | inline void inc_block_usage(size_t usage) { _block_memory_usage += usage; } |
192 | | |
193 | 0 | int64_t block_memory_usage() { return _block_memory_usage; } |
194 | | |
195 | | // Caller should make sure the pipeline task is still running when calling this function |
196 | | void update_peak_running_scanner(int num); |
197 | | void reestimated_block_mem_bytes(int64_t num); |
198 | | |
199 | | // Get next block from blocks queue. Called by ScanNode/ScanOperator |
200 | | // Set eos to true if there is no more data to read. |
201 | | Status get_block_from_queue(RuntimeState* state, Block* block, bool* eos, int id); |
202 | | |
203 | | [[nodiscard]] Status validate_block_schema(Block* block); |
204 | | |
205 | | // submit the running scanner to thread pool in `ScannerScheduler` |
206 | | // set the next scanned block to `ScanTask::current_block` |
207 | | // set the error state to `ScanTask::status` |
208 | | // set the `eos` to `ScanTask::eos` if there is no more data in current scanner |
209 | | Status submit_scan_task(std::shared_ptr<ScanTask> scan_task, std::unique_lock<std::mutex>&); |
210 | | |
211 | | // Push back a scan task. |
212 | | void push_back_scan_task(std::shared_ptr<ScanTask> scan_task); |
213 | | |
214 | | // Return true if this ScannerContext need no more process |
215 | 20 | bool done() const { return _is_finished || _should_stop; } |
216 | | |
217 | | std::string debug_string(); |
218 | | |
219 | 0 | std::shared_ptr<TaskHandle> task_handle() const { return _task_handle; } |
220 | | |
221 | 0 | std::shared_ptr<ResourceContext> resource_ctx() const { return _resource_ctx; } |
222 | | |
223 | 0 | RuntimeState* state() { return _state; } |
224 | | |
225 | | void stop_scanners(RuntimeState* state); |
226 | | |
227 | 0 | int batch_size() const { return _batch_size; } |
228 | | |
229 | | // During low memory mode, there will be at most 4 scanners running and every scanner will |
230 | | // cache at most 1MB data. So that every instance will keep 8MB buffer. |
231 | | bool low_memory_mode() const; |
232 | | |
233 | | // TODO(yiguolei) add this as session variable |
234 | 0 | int32_t low_memory_mode_scan_bytes_per_scanner() const { |
235 | 0 | return 1 * 1024 * 1024; // 1MB |
236 | 0 | } |
237 | | |
238 | 0 | int32_t low_memory_mode_scanners() const { return 4; } |
239 | | |
240 | 0 | ScanLocalStateBase* local_state() const { return _local_state; } |
241 | | |
242 | | // the unique id of this context |
243 | | std::string ctx_id; |
244 | | TUniqueId _query_id; |
245 | | |
246 | | bool _should_reset_thread_name = true; |
247 | | |
248 | 0 | int32_t num_scheduled_scanners() { |
249 | 0 | std::lock_guard<std::mutex> l(_transfer_lock); |
250 | 0 | return _in_flight_tasks_num; |
251 | 0 | } |
252 | | |
253 | | Status schedule_scan_task(std::shared_ptr<ScanTask> current_scan_task, |
254 | | std::unique_lock<std::mutex>& transfer_lock, |
255 | | std::unique_lock<std::shared_mutex>& scheduler_lock); |
256 | | |
257 | | protected: |
258 | | /// Four criteria to determine whether to increase the parallelism of the scanners |
259 | | /// 1. It ran for at least `SCALE_UP_DURATION` ms after last scale up |
260 | | /// 2. Half(`WAIT_BLOCK_DURATION_RATIO`) of the duration is waiting to get blocks |
261 | | /// 3. `_free_blocks_memory_usage` < `_max_bytes_in_queue`, remains enough memory to scale up |
262 | | /// 4. At most scale up `MAX_SCALE_UP_RATIO` times to `_max_thread_num` |
263 | | void _set_scanner_done(); |
264 | | bool _is_shared_scan_limit_exhausted() const; |
265 | | |
266 | | RuntimeState* _state = nullptr; |
267 | | ScanLocalStateBase* _local_state = nullptr; |
268 | | |
269 | | // the comment of same fields in VScanNode |
270 | | const TupleDescriptor* _output_tuple_desc = nullptr; |
271 | | const RowDescriptor* _output_row_descriptor = nullptr; |
272 | | |
273 | | Status _process_status = Status::OK(); |
274 | | std::atomic_bool _should_stop = false; |
275 | | std::atomic_bool _is_finished = false; |
276 | | |
277 | | // Lazy-allocated blocks for all scanners to share, for memory reuse. |
278 | | moodycamel::ConcurrentQueue<BlockUPtr> _free_blocks; |
279 | | |
280 | | int _batch_size; |
281 | | // The limit from SQL's limit clause |
282 | | int64_t limit; |
283 | | // Points to the shared remaining limit on ScanOperatorX, shared across all |
284 | | // parallel instances and their scanners. -1 means no limit. |
285 | | std::atomic<int64_t>* _shared_scan_limit = nullptr; |
286 | | |
287 | | int64_t _max_bytes_in_queue = 0; |
288 | | // _transfer_lock protects _completed_tasks, _pending_tasks, and all other shared state |
289 | | // accessed by both the scanner thread pool and the operator (get_block_from_queue). |
290 | | std::mutex _transfer_lock; |
291 | | |
292 | | // Together, _completed_tasks and _in_flight_tasks_num represent all "occupied" concurrency |
293 | | // slots. The scheduler uses their sum as the current concurrency: |
294 | | // |
295 | | // current_concurrency = _completed_tasks.size() + _in_flight_tasks_num |
296 | | // |
297 | | // Lifecycle of a ScanTask: |
298 | | // _pending_tasks --(submit_scan_task)--> [thread pool] --(push_back_scan_task)--> |
299 | | // _completed_tasks --(get_block_from_queue)--> operator |
300 | | // After consumption: non-EOS task goes back to _pending_tasks; EOS increments |
301 | | // _num_finished_scanners. |
302 | | |
303 | | // Completed scan tasks whose cached_block is ready for the operator to consume. |
304 | | // Protected by _transfer_lock. Written by push_back_scan_task() (scanner thread), |
305 | | // read/popped by get_block_from_queue() (operator thread). |
306 | | std::list<std::shared_ptr<ScanTask>> _completed_tasks; |
307 | | |
308 | | // Scanners waiting to be submitted to the scheduler thread pool. Stored as a stack |
309 | | // (LIFO) so that recently-used scanners are re-scheduled first, which is more likely |
310 | | // to be cache-friendly. Protected by _transfer_lock. Populated in the constructor |
311 | | // and by schedule_scan_task() when the concurrency limit is reached; drained by |
312 | | // _pull_next_scan_task() during scheduling. |
313 | | std::stack<std::shared_ptr<ScanTask>> _pending_tasks; |
314 | | |
315 | | // Number of scan tasks currently submitted to the scanner scheduler thread pool |
316 | | // (i.e. in-flight). Incremented by submit_scan_task() before submission and |
317 | | // decremented by push_back_scan_task() when the thread pool returns the task. |
318 | | // Declared atomic so it can be read without _transfer_lock in non-critical paths, |
319 | | // but must be read under _transfer_lock whenever combined with _completed_tasks.size() |
320 | | // to form a consistent concurrency snapshot. |
321 | | std::atomic_int _in_flight_tasks_num = 0; |
322 | | // Scanner that is eos or error. |
323 | | int32_t _num_finished_scanners = 0; |
324 | | // weak pointer for _scanners, used in stop function |
325 | | std::vector<std::weak_ptr<ScannerDelegate>> _all_scanners; |
326 | | std::shared_ptr<RuntimeProfile> _scanner_profile; |
327 | | // This counter refers to scan operator's local state |
328 | | RuntimeProfile::Counter* _scanner_memory_used_counter = nullptr; |
329 | | RuntimeProfile::Counter* _newly_create_free_blocks_num = nullptr; |
330 | | RuntimeProfile::Counter* _scale_up_scanners_counter = nullptr; |
331 | | std::shared_ptr<ResourceContext> _resource_ctx; |
332 | | std::shared_ptr<Dependency> _dependency = nullptr; |
333 | | std::shared_ptr<doris::TaskHandle> _task_handle; |
334 | | std::weak_ptr<doris::TaskExecutor> _task_executor; |
335 | | |
336 | | std::atomic<int64_t> _block_memory_usage = 0; |
337 | | |
338 | | // adaptive scan concurrency related |
339 | | |
340 | | ScannerScheduler* _scanner_scheduler = nullptr; |
341 | | MOCK_REMOVE(const) int32_t _min_scan_concurrency_of_scan_scheduler = 0; |
342 | | // The overall target of our system is to make full utilization of the resources. |
343 | | // At the same time, we dont want too many tasks are queued by scheduler, that is not necessary. |
344 | | // Each scan operator can submit _max_scan_concurrency scanner to scheduelr if scheduler has enough resource. |
345 | | // So that for a single query, we can make sure it could make full utilization of the resource. |
346 | | int32_t _max_scan_concurrency = 0; |
347 | | MOCK_REMOVE(const) int32_t _min_scan_concurrency = 1; |
348 | | |
349 | | std::shared_ptr<ScanTask> _pull_next_scan_task(std::shared_ptr<ScanTask> current_scan_task, |
350 | | int32_t current_concurrency); |
351 | | |
352 | | int32_t _get_margin(std::unique_lock<std::mutex>& transfer_lock, |
353 | | std::unique_lock<std::shared_mutex>& scheduler_lock); |
354 | | |
355 | | // Memory-aware adaptive scheduling |
356 | | std::shared_ptr<MemLimiter> _scanner_mem_limiter = nullptr; |
357 | | std::shared_ptr<MemShareArbitrator> _mem_share_arb = nullptr; |
358 | | std::shared_ptr<ScannerAdaptiveProcessor> _adaptive_processor = nullptr; |
359 | | const int _ins_idx; |
360 | | const bool _enable_adaptive_scanners = false; |
361 | | |
362 | | // Adjust scan memory limit based on arbitrator feedback |
363 | | void _adjust_scan_mem_limit(int64_t old_scanner_mem_bytes, int64_t new_scanner_mem_bytes); |
364 | | |
365 | | // Calculate available scanner count for adaptive scheduling |
366 | | int _available_pickup_scanner_count(); |
367 | | |
368 | | // TODO: Add implementation of runtime_info_feed_back |
369 | | // adaptive scan concurrency related end |
370 | | }; |
371 | | } // namespace doris |