| 57 | } |
| 58 | |
| 59 | bool ScannerMemLimiter::ClaimMemoryForScannerThread( |
| 60 | ScanNode* node, int64_t estimated_thread_mem) { |
| 61 | shared_lock<shared_mutex> read_lock(registered_scans_lock_); |
| 62 | RegisteredScan* found_scan = nullptr; |
| 63 | // Calculate the memory consumption in excess of the current consumption that we expect |
| 64 | // from already-started threads plus the new thread. We need to compute the global |
| 65 | // total across all scans because multiple scans can compete for the same memory. |
| 66 | int64_t addtl_consumption = 0; |
| 67 | for (const auto& element : registered_scans_) { |
| 68 | const unique_ptr<RegisteredScan>& scan = element.second; |
| 69 | int64_t consumption = element.first->mem_tracker()->consumption(); |
| 70 | int64_t num_threads = scan->num_threads.Load(); |
| 71 | int64_t estimated_mem = scan->estimated_mem.Load(); |
| 72 | if (consumption > estimated_mem) { |
| 73 | // Memory exceeded our estimate. Use a crude heuristic of guessing that the scan |
| 74 | // will use up to 50% more memory. This is carried over from old versions of the |
| 75 | // code pre-IMPALA-4835, which were initially added in the commit titled |
| 76 | // "Dynamically scale down mem usage in scanners and io mgr." |
| 77 | if (node == element.first) { |
| 78 | // Add consumption for the new thread. |
| 79 | addtl_consumption += static_cast<int64_t>((consumption * 1.5) / num_threads); |
| 80 | } |
| 81 | // We guess that consumption of existing threads will grow up to 50% above the |
| 82 | // current consumption. |
| 83 | addtl_consumption += static_cast<int64_t>(consumption * 0.5); |
| 84 | } else { |
| 85 | // The scan hasn't used all the estimated memory yet - make sure that that is |
| 86 | // accounted for. |
| 87 | addtl_consumption += estimated_mem - consumption; |
| 88 | if (node == element.first) addtl_consumption += estimated_thread_mem; |
| 89 | } |
| 90 | if (node == element.first) found_scan = scan.get(); |
| 91 | } |
| 92 | DCHECK(found_scan != nullptr) << "Increase mem on unregistered scan"; |
| 93 | // Check if we have capacity for the expected increase in consumption. |
| 94 | if (addtl_consumption >= node->mem_tracker()->SpareCapacity(MemLimit::SOFT)) { |
| 95 | return false; |
| 96 | } |
| 97 | // There is enough memory - update the estimated memory with the estimate. |
| 98 | found_scan->estimated_mem.Add(estimated_thread_mem); |
| 99 | found_scan->num_threads.Add(1); |
| 100 | return true; |
| 101 | } |
| 102 | |
| 103 | void ScannerMemLimiter::ReleaseMemoryForScannerThread( |
| 104 | ScanNode* node, int64_t estimated_thread_mem) { |
no test coverage detected