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 | 201k | 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 | 2.79k | void set_status(Status _status) { |
120 | 2.79k | 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 | 2.79k | status = _status; |
125 | 2.79k | } |
126 | 1.39k | Status get_status() const { return status; } |
127 | 2.83M | bool status_ok() { return status.ok() || status.is<ErrorCode::END_OF_FILE>(); } |
128 | 2.74M | bool is_eos() const { return _state == State::EOS; } |
129 | 1.89M | void set_state(State state) { |
130 | 1.89M | switch (state) { |
131 | 23 | case State::PENDING: |
132 | | // A task returns to PENDING after the operator consumes its non-EOS cached block. |
133 | | // For example, one scanner may produce several blocks, so COMPLETED is not terminal. |
134 | 23 | DCHECK(_state == State::PENDING || _state == State::IN_FLIGHT || |
135 | 0 | _state == State::COMPLETED) |
136 | 0 | << (int)_state; |
137 | 23 | DCHECK(cached_block == nullptr); |
138 | 23 | break; |
139 | 947k | case State::IN_FLIGHT: |
140 | 947k | DCHECK(_state == State::COMPLETED || _state == State::PENDING || |
141 | 1 | _state == State::IN_FLIGHT) |
142 | 1 | << (int)_state; |
143 | 947k | DCHECK(cached_block == nullptr); |
144 | 947k | break; |
145 | 53.3k | case State::COMPLETED: |
146 | 18.4E | DCHECK(_state == State::IN_FLIGHT) << (int)_state; |
147 | 53.3k | DCHECK(cached_block != nullptr); |
148 | 53.3k | break; |
149 | 892k | case State::EOS: |
150 | 18.4E | DCHECK(_state == State::IN_FLIGHT || status.is<ErrorCode::END_OF_FILE>()) |
151 | 18.4E | << (int)_state; |
152 | 892k | break; |
153 | 0 | default: |
154 | 0 | break; |
155 | 1.89M | } |
156 | | |
157 | 1.89M | _state = state; |
158 | 1.89M | } |
159 | | }; |
160 | | |
161 | | // ScannerContext is responsible for recording the execution status |
162 | | // of a group of Scanners corresponding to a ScanNode. |
163 | | // Including how many scanners are being scheduled, and maintaining |
164 | | // a producer-consumer blocks queue between scanners and scan nodes. |
165 | | // |
166 | | // ScannerContext is also the scheduling unit of ScannerScheduler. |
167 | | // ScannerScheduler schedules a ScannerContext at a time, |
168 | | // and submits the Scanners to the scanner thread pool for data scanning. |
169 | | class ScannerContext : public std::enable_shared_from_this<ScannerContext>, |
170 | | public HasTaskExecutionCtx { |
171 | | ENABLE_FACTORY_CREATOR(ScannerContext); |
172 | | friend class ScannerScheduler; |
173 | | |
174 | | public: |
175 | | ScannerContext(RuntimeState* state, ScanLocalStateBase* local_state, |
176 | | const TupleDescriptor* output_tuple_desc, bool has_projection, |
177 | | const std::list<std::shared_ptr<ScannerDelegate>>& scanners, int64_t limit_, |
178 | | std::shared_ptr<Dependency> dependency, std::atomic<int64_t>* shared_scan_limit, |
179 | | std::shared_ptr<MemShareArbitrator> arb, std::shared_ptr<MemLimiter> limiter, |
180 | | int ins_idx, bool enable_adaptive_scan |
181 | | #ifdef BE_TEST |
182 | | , |
183 | | int num_parallel_instances |
184 | | #endif |
185 | | ); |
186 | | |
187 | | ~ScannerContext() override; |
188 | | Status init(); |
189 | | |
190 | | // 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. |
191 | | BlockUPtr get_free_block(bool force); |
192 | | void return_free_block(BlockUPtr block); |
193 | | void clear_free_blocks(); |
194 | 945k | inline void inc_block_usage(size_t usage) { _block_memory_usage += usage; } |
195 | | |
196 | 956k | int64_t block_memory_usage() { return _block_memory_usage; } |
197 | | |
198 | | // Caller should make sure the pipeline task is still running when calling this function |
199 | | void update_peak_running_scanner(int num); |
200 | | void reestimated_block_mem_bytes(int64_t num); |
201 | | |
202 | | // Get next block from blocks queue. Called by ScanNode/ScanOperator |
203 | | // Set eos to true if there is no more data to read. |
204 | | Status get_block_from_queue(RuntimeState* state, Block* block, bool* eos, int id); |
205 | | |
206 | | [[nodiscard]] Status validate_block_schema(Block* block); |
207 | | |
208 | | // submit the running scanner to thread pool in `ScannerScheduler` |
209 | | // set the next scanned block to `ScanTask::current_block` |
210 | | // set the error state to `ScanTask::status` |
211 | | // set the `eos` to `ScanTask::eos` if there is no more data in current scanner |
212 | | Status submit_scan_task(std::shared_ptr<ScanTask> scan_task, std::unique_lock<std::mutex>&); |
213 | | |
214 | | // Publish a task whose current scan attempt has completed. The operator consumes its cached |
215 | | // block and returns a non-EOS task to PENDING for its next scan attempt. |
216 | | void push_completed_scan_task(std::shared_ptr<ScanTask> scan_task); |
217 | | |
218 | | // Return true if this ScannerContext need no more process |
219 | 3.78M | bool done() const { return _is_finished || _should_stop; } |
220 | | |
221 | | std::string debug_string(); |
222 | | |
223 | 947k | std::shared_ptr<TaskHandle> task_handle() const { return _task_handle; } |
224 | | |
225 | 0 | std::shared_ptr<ResourceContext> resource_ctx() const { return _resource_ctx; } |
226 | | |
227 | 1.89M | RuntimeState* state() { return _state; } |
228 | | |
229 | | void stop_scanners(RuntimeState* state); |
230 | | |
231 | 242k | int batch_size() const { return _batch_size; } |
232 | | |
233 | | // During low memory mode, there will be at most 4 scanners running and every scanner will |
234 | | // cache at most 1MB data. So that every instance will keep 8MB buffer. |
235 | | bool low_memory_mode() const; |
236 | | |
237 | | // TODO(yiguolei) add this as session variable |
238 | 0 | int32_t low_memory_mode_scan_bytes_per_scanner() const { |
239 | 0 | return 1 * 1024 * 1024; // 1MB |
240 | 0 | } |
241 | | |
242 | 0 | int32_t low_memory_mode_scanners() const { return 4; } |
243 | | |
244 | 0 | ScanLocalStateBase* local_state() const { return _local_state; } |
245 | | |
246 | | // the unique id of this context |
247 | | std::string ctx_id; |
248 | | TUniqueId _query_id; |
249 | | |
250 | | bool _should_reset_thread_name = true; |
251 | | |
252 | 0 | int32_t num_scheduled_scanners() { |
253 | 0 | std::lock_guard<std::mutex> l(_transfer_lock); |
254 | 0 | return _in_flight_tasks_num; |
255 | 0 | } |
256 | | |
257 | | Status schedule_scan_task(std::shared_ptr<ScanTask> current_scan_task, |
258 | | std::unique_lock<std::mutex>& transfer_lock, |
259 | | std::unique_lock<std::shared_mutex>& scheduler_lock); |
260 | | |
261 | | // Context scheduling and operator consumption share this lock so queue-state changes and task |
262 | | // admission form one atomic decision. For example, two worker callbacks cannot both admit the |
263 | | // last available concurrency slot. |
264 | 31 | std::mutex& transfer_lock() { return _transfer_lock; } |
265 | | |
266 | | // One Context submission represents many pending scanners in the ThreadPool scheduler. |
267 | | // Keeping this separate from scanner execution prevents duplicate runnables from accumulating. |
268 | | bool is_context_queued(const std::unique_lock<std::mutex>& transfer_lock) const; |
269 | | // Transition the Context runnable's queue state. The caller must hold _transfer_lock. |
270 | | void set_context_queued(bool queued, const std::unique_lock<std::mutex>& transfer_lock); |
271 | | |
272 | | // Publish a scheduler failure and make the Context terminal. The caller must hold |
273 | | // _transfer_lock so a retained ThreadPool callback cannot admit another scanner concurrently. |
274 | | void set_context_failure(const Status& failure, |
275 | | const std::unique_lock<std::mutex>& transfer_lock); |
276 | | |
277 | | // Return a scanner to the admission queue after its block is consumed. It may not own a cached |
278 | | // block and may not be EOS: EOS scanners are terminal and must not run again. |
279 | | void push_pending_scan_task(std::shared_ptr<ScanTask> scan_task, |
280 | | const std::unique_lock<std::mutex>& transfer_lock); |
281 | | |
282 | | // Return whether a Context worker can currently admit one pending scanner. This check has no |
283 | | // side effects, so the scheduler can avoid submitting a runnable that would immediately exit. |
284 | | // It always admits one scanner when nothing is progressing so the operator can be woken, and it |
285 | | // holds the Context at max(1, _min_scan_concurrency) while the scheduler pool has no slack, |
286 | | // like _get_margin() on the TaskExecutor path. The caller must hold _transfer_lock. |
287 | | bool can_admit_scan_task(const std::unique_lock<std::mutex>& transfer_lock) const; |
288 | | |
289 | | // Atomically check whether this context can start another scan task, move one task from |
290 | | // pending to in-flight, and return it. The caller must hold _transfer_lock. |
291 | | std::shared_ptr<ScanTask> try_get_next_scan_task( |
292 | | const std::unique_lock<std::mutex>& transfer_lock); |
293 | | |
294 | | protected: |
295 | | /// Four criteria to determine whether to increase the parallelism of the scanners |
296 | | /// 1. It ran for at least `SCALE_UP_DURATION` ms after last scale up |
297 | | /// 2. Half(`WAIT_BLOCK_DURATION_RATIO`) of the duration is waiting to get blocks |
298 | | /// 3. `_free_blocks_memory_usage` < `_max_bytes_in_queue`, remains enough memory to scale up |
299 | | /// 4. At most scale up `MAX_SCALE_UP_RATIO` times to `_max_thread_num` |
300 | | void _set_scanner_done(); |
301 | | bool _is_shared_scan_limit_exhausted() const; |
302 | | |
303 | | RuntimeState* _state = nullptr; |
304 | | ScanLocalStateBase* _local_state = nullptr; |
305 | | |
306 | | // the comment of same fields in VScanNode |
307 | | const TupleDescriptor* _output_tuple_desc = nullptr; |
308 | | |
309 | | Status _process_status = Status::OK(); |
310 | | std::atomic_bool _should_stop = false; |
311 | | std::atomic_bool _is_finished = false; |
312 | | |
313 | | // Lazy-allocated blocks for all scanners to share, for memory reuse. |
314 | | moodycamel::ConcurrentQueue<BlockUPtr> _free_blocks; |
315 | | |
316 | | int _batch_size; |
317 | | // The limit from SQL's limit clause |
318 | | int64_t limit; |
319 | | // Points to the shared remaining limit on ScanOperatorX, shared across all |
320 | | // parallel instances and their scanners. -1 means no limit. |
321 | | std::atomic<int64_t>* _shared_scan_limit = nullptr; |
322 | | |
323 | | int64_t _max_bytes_in_queue = 0; |
324 | | // _transfer_lock protects _completed_tasks, _pending_tasks, and all other shared state |
325 | | // accessed by both the scanner thread pool and the operator (get_block_from_queue). |
326 | | std::mutex _transfer_lock; |
327 | | |
328 | | // Together, _completed_tasks and _in_flight_tasks_num represent all "occupied" concurrency |
329 | | // slots. The scheduler uses their sum as the current concurrency: |
330 | | // |
331 | | // current_concurrency = _completed_tasks.size() + _in_flight_tasks_num |
332 | | // |
333 | | // Lifecycle of a ScanTask: |
334 | | // _pending_tasks --(submit_scan_task on the TaskExecutor path, |
335 | | // try_get_next_scan_task on the ThreadPool path)--> [thread pool] |
336 | | // --(push_completed_scan_task)--> _completed_tasks --(get_block_from_queue)--> operator |
337 | | // After consumption: non-EOS task goes back to _pending_tasks; EOS increments |
338 | | // _num_finished_scanners. |
339 | | |
340 | | // Completed scan tasks whose cached_block is ready for the operator to consume. |
341 | | // Protected by _transfer_lock. Written by push_completed_scan_task() (scanner thread), |
342 | | // read/popped by get_block_from_queue() (operator thread). |
343 | | std::list<std::shared_ptr<ScanTask>> _completed_tasks; |
344 | | |
345 | | // Scanners waiting to be admitted for execution. Stored as a stack (LIFO) so that |
346 | | // recently-used scanners are re-scheduled first, which is more likely to be cache-friendly. |
347 | | // Protected by _transfer_lock. Populated in the constructor and when an operator returns a |
348 | | // non-EOS task; drained by try_get_next_scan_task() or the TaskExecutor scheduler. |
349 | | std::stack<std::shared_ptr<ScanTask>> _pending_tasks; |
350 | | |
351 | | // True from the start of one Context submission until its runnable starts. The marker may |
352 | | // remain true when no runnable was retained: a failed submission makes the Context terminal, |
353 | | // and a submission that threw inside _run_context() publishes the error through the task that |
354 | | // was already admitted. In both cases the operator observes _process_status, so no further |
355 | | // submission is attempted. It does not describe scanners executing on workers. Protected by |
356 | | // _transfer_lock. |
357 | | bool _is_context_queued = false; |
358 | | |
359 | | // Number of scan tasks currently submitted to the scanner scheduler thread pool |
360 | | // (i.e. in-flight). Incremented before a task is submitted or directly admitted for |
361 | | // thread-pool execution, and decremented by push_completed_scan_task() when the worker |
362 | | // returns it. |
363 | | // Declared atomic so it can be read without _transfer_lock in non-critical paths, |
364 | | // but must be read under _transfer_lock whenever combined with _completed_tasks.size() |
365 | | // to form a consistent concurrency snapshot. |
366 | | std::atomic_int _in_flight_tasks_num = 0; |
367 | | // Scanner that is eos or error. |
368 | | int32_t _num_finished_scanners = 0; |
369 | | // weak pointer for _scanners, used in stop function |
370 | | std::vector<std::weak_ptr<ScannerDelegate>> _all_scanners; |
371 | | std::shared_ptr<RuntimeProfile> _scanner_profile; |
372 | | // This counter refers to scan operator's local state |
373 | | RuntimeProfile::Counter* _scanner_memory_used_counter = nullptr; |
374 | | RuntimeProfile::Counter* _newly_create_free_blocks_num = nullptr; |
375 | | RuntimeProfile::Counter* _scale_up_scanners_counter = nullptr; |
376 | | std::shared_ptr<ResourceContext> _resource_ctx; |
377 | | std::shared_ptr<Dependency> _dependency = nullptr; |
378 | | std::shared_ptr<doris::TaskHandle> _task_handle; |
379 | | std::weak_ptr<doris::TaskExecutor> _task_executor; |
380 | | |
381 | | std::atomic<int64_t> _block_memory_usage = 0; |
382 | | |
383 | | // adaptive scan concurrency related |
384 | | |
385 | | ScannerScheduler* _scanner_scheduler = nullptr; |
386 | | MOCK_REMOVE(const) int32_t _min_scan_concurrency_of_scan_scheduler = 0; |
387 | | // The overall target of our system is to make full utilization of the resources. |
388 | | // At the same time, we dont want too many tasks are queued by scheduler, that is not necessary. |
389 | | // Each scan operator can submit _max_scan_concurrency scanner to scheduelr if scheduler has enough resource. |
390 | | // So that for a single query, we can make sure it could make full utilization of the resource. |
391 | | int32_t _max_scan_concurrency = 0; |
392 | | MOCK_REMOVE(const) int32_t _min_scan_concurrency = 1; |
393 | | |
394 | | std::shared_ptr<ScanTask> _pull_next_scan_task(std::shared_ptr<ScanTask> current_scan_task, |
395 | | int32_t current_concurrency); |
396 | | |
397 | | int32_t _get_margin(std::unique_lock<std::mutex>& transfer_lock, |
398 | | std::unique_lock<std::shared_mutex>& scheduler_lock); |
399 | | |
400 | | // Memory-aware adaptive scheduling |
401 | | std::shared_ptr<MemLimiter> _scanner_mem_limiter = nullptr; |
402 | | std::shared_ptr<MemShareArbitrator> _mem_share_arb = nullptr; |
403 | | std::shared_ptr<ScannerAdaptiveProcessor> _adaptive_processor = nullptr; |
404 | | const int _ins_idx; |
405 | | const bool _enable_adaptive_scanners = false; |
406 | | |
407 | | // Adjust scan memory limit based on arbitrator feedback |
408 | | void _adjust_scan_mem_limit(int64_t old_scanner_mem_bytes, int64_t new_scanner_mem_bytes); |
409 | | |
410 | | // Calculate available scanner count for adaptive scheduling |
411 | | int _available_pickup_scanner_count(); |
412 | | |
413 | | // TODO: Add implementation of runtime_info_feed_back |
414 | | // adaptive scan concurrency related end |
415 | | }; |
416 | | } // namespace doris |