alamb commented on code in PR #4522: URL: https://github.com/apache/arrow-datafusion/pull/4522#discussion_r1051387834
########## datafusion/core/src/execution/memory_pool/pool.rs: ########## @@ -0,0 +1,280 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::execution::memory_pool::{AllocationOptions, MemoryPool, TrackedAllocation}; +use datafusion_common::{DataFusionError, Result}; +use parking_lot::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A [`MemoryPool`] that enforces no limit +#[derive(Debug, Default)] +pub struct UnboundedMemoryPool { + used: AtomicUsize, +} + +impl MemoryPool for UnboundedMemoryPool { + fn grow(&self, _allocation: &TrackedAllocation, additional: usize) { + self.used.fetch_add(additional, Ordering::Relaxed); + } + + fn shrink(&self, _allocation: &TrackedAllocation, shrink: usize) { + self.used.fetch_sub(shrink, Ordering::Relaxed); + } + + fn try_grow(&self, allocation: &TrackedAllocation, additional: usize) -> Result<()> { + self.grow(allocation, additional); + Ok(()) + } + + fn allocated(&self) -> usize { + self.used.load(Ordering::Relaxed) + } +} + +/// A [`MemoryPool`] that implements a greedy first-come first-serve limit +#[derive(Debug)] +pub struct GreedyMemoryPool { + pool_size: usize, + used: AtomicUsize, +} + +impl GreedyMemoryPool { + /// Allocate up to `limit` bytes + pub fn new(pool_size: usize) -> Self { + Self { + pool_size, + used: AtomicUsize::new(0), + } + } +} + +impl MemoryPool for GreedyMemoryPool { + fn grow(&self, _allocation: &TrackedAllocation, additional: usize) { + self.used.fetch_add(additional, Ordering::Relaxed); + } + + fn shrink(&self, _allocation: &TrackedAllocation, shrink: usize) { + self.used.fetch_sub(shrink, Ordering::Relaxed); + } + + fn try_grow(&self, allocation: &TrackedAllocation, additional: usize) -> Result<()> { + self.used + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| { + let new_used = used + additional; + (new_used <= self.pool_size).then_some(new_used) + }) + .map_err(|used| { + insufficient_capacity_err(allocation, additional, self.pool_size - used) + })?; + Ok(()) + } + + fn allocated(&self) -> usize { + self.used.load(Ordering::Relaxed) + } +} + +/// A [`MemoryPool`] that prevents spillable allocations from using more than +/// an even fraction of the available memory sans any unspillable allocations +/// (i.e. `(pool_size - unspillable_memory) / num_spillable_allocations`) +/// +/// ┌───────────────────────z──────────────────────z───────────────┐ +/// │ z z │ +/// │ z z │ +/// │ Spillable z Unspillable z Free │ +/// │ Memory z Memory z Memory │ +/// │ z z │ +/// │ z z │ +/// └───────────────────────z──────────────────────z───────────────┘ +/// +/// Unspillable memory is allocated in a first-come, first-serve fashion +#[derive(Debug)] +pub struct FairSpillPool { + /// The total memory limit + pool_size: usize, + + state: Mutex<FairSpillPoolState>, +} + +#[derive(Debug)] +struct FairSpillPoolState { + /// The number of allocations that can spill + num_spill: usize, + + /// The total amount of memory allocated that can be spilled + spillable: usize, + + /// The total amount of memory allocated by consumers that cannot spill + unspillable: usize, +} + +impl FairSpillPool { + /// Allocate up to `limit` bytes + pub fn new(pool_size: usize) -> Self { + Self { + pool_size, + state: Mutex::new(FairSpillPoolState { + num_spill: 0, + spillable: 0, + unspillable: 0, + }), + } + } +} + +impl MemoryPool for FairSpillPool { + fn allocate(&self, options: &AllocationOptions) { Review Comment: I spent some time convincing myself this would work correctly if there are multiple SortExecs in the plan such that one would completely run before the other (e.g. as happens when there are multiple window functions with different partition / order by clauses) I believe it will be fine because each `ExternalSorter` creates the potentially spilling allocation allocation upon construction, though I am still not 100% sure. What would you think about moving the construction of `TrackedAllocation` into `MemoryPool`, something like ```rust /// Create a new tracked allocation with the MemoryManager. Subsequent requests /// can grow or shrink the memory allocated to this allocation. /// /// The allocation is automatically deregistered on drop fn register(self: &Arc<Self>, options: AllocationOptions) -> TrackedAllocation; ``` That way the intent would be clearer that all ExternalSort instances register themselves with the MemoryManager on creation, and part of registering would increase the `num_spill` count. I think having the MemoryPool create TrackedAllocations makes more logical sense as they are so tightly bound and you need a MemoryPool for a tracked allocation anyways ########## datafusion/core/src/execution/memory_manager/pool.rs: ########## @@ -0,0 +1,282 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::execution::memory_manager::{AllocationOptions, MemoryPool}; +use crate::execution::TrackedAllocation; +use datafusion_common::{DataFusionError, Result}; +use parking_lot::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A [`MemoryPool`] that enforces no limit +#[derive(Debug, Default)] +pub struct UnboundedMemoryPool { Review Comment: This is very nice -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
