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