Apache DataFusion SQL Query Engine
Cleanup join memory accounting (#6188)
Raphael Taylor-Davies9ef7bff229c8
diff --git a/datafusion/core/src/physical_plan/joins/cross_join.rs b/datafusion/core/src/physical_plan/joins/cross_join.rsindex 67b7fd9718..39d0804c05 100644--- a/datafusion/core/src/physical_plan/joins/cross_join.rs+++ b/datafusion/core/src/physical_plan/joins/cross_join.rs@@ -26,7 +26,6 @@ use arrow::datatypes::{Fields, Schema, SchemaRef};use arrow::record_batch::RecordBatch;use crate::execution::context::TaskContext;-use crate::execution::memory_pool::{SharedOptionalMemoryReservation, TryGrow};use crate::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet};use crate::physical_plan::{coalesce_batches::concat_batches, coalesce_partitions::CoalescePartitionsExec,@@ -37,6 +36,7 @@ use crate::physical_plan::{use crate::{error::Result, scalar::ScalarValue};use async_trait::async_trait;use datafusion_common::DataFusionError;+use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};use super::utils::{adjust_right_output_partitioning, cross_join_equivalence_properties,@@ -44,7 +44,7 @@ use super::utils::{};/// Data of the left side-type JoinLeftData = RecordBatch;+type JoinLeftData = (RecordBatch, MemoryReservation);/// executes partitions in parallel and combines them into a set of/// partitions by combining all values from the left with all values on the right@@ -58,8 +58,6 @@ pub struct CrossJoinExec {schema: SchemaRef,/// Build-side dataleft_fut: OnceAsync<JoinLeftData>,- /// Memory reservation for build-side data- reservation: SharedOptionalMemoryReservation,/// Execution plan metricsmetrics: ExecutionPlanMetricsSet,}@@ -83,7 +81,6 @@ impl CrossJoinExec {right,schema,left_fut: Default::default(),- reservation: Default::default(),metrics: ExecutionPlanMetricsSet::default(),}}@@ -104,7 +101,7 @@ async fn load_left_input(left: Arc<dyn ExecutionPlan>,context: Arc<TaskContext>,metrics: BuildProbeJoinMetrics,- reservation: SharedOptionalMemoryReservation,+ reservation: MemoryReservation,) -> Result<JoinLeftData> {// merge all left parts into a single streamlet merge = {@@ -117,7 +114,7 @@ async fn load_left_input(let stream = merge.execute(0, context)?;// Load all batches and count the rows- let (batches, num_rows, _, _) = stream+ let (batches, num_rows, _, reservation) = stream.try_fold((Vec::new(), 0usize, metrics, reservation),|mut acc, batch| async {@@ -139,7 +136,7 @@ async fn load_left_input(let merged_batch = concat_batches(&left.schema(), &batches, num_rows)?;- Ok(merged_batch)+ Ok((merged_batch, reservation))}impl ExecutionPlan for CrossJoinExec {@@ -224,15 +221,15 @@ impl ExecutionPlan for CrossJoinExec {let join_metrics = BuildProbeJoinMetrics::new(partition, &self.metrics);// Initialization of operator-level reservation- self.reservation- .initialize("CrossJoinExec", context.memory_pool());+ let reservation =+ MemoryConsumer::new("CrossJoinExec").register(context.memory_pool());let left_fut = self.left_fut.once(|| {load_left_input(self.left.clone(),context,join_metrics.clone(),- self.reservation.clone(),+ reservation,)});@@ -401,7 +398,7 @@ impl CrossJoinStream {cx: &mut std::task::Context<'_>,) -> std::task::Poll<Option<Result<RecordBatch>>> {let build_timer = self.join_metrics.build_time.timer();- let left_data = match ready!(self.left_fut.get(cx)) {+ let (left_data, _) = match ready!(self.left_fut.get(cx)) {Ok(left_data) => left_data,Err(e) => return Poll::Ready(Some(Err(e))),};diff --git a/datafusion/core/src/physical_plan/joins/nested_loop_join.rs b/datafusion/core/src/physical_plan/joins/nested_loop_join.rsindex e04e86d0d3..64afcc478b 100644--- a/datafusion/core/src/physical_plan/joins/nested_loop_join.rs+++ b/datafusion/core/src/physical_plan/joins/nested_loop_join.rs@@ -39,6 +39,7 @@ use arrow::datatypes::{Schema, SchemaRef};use arrow::record_batch::RecordBatch;use arrow::util::bit_util;use datafusion_common::{DataFusionError, Statistics};+use datafusion_execution::memory_pool::MemoryReservation;use datafusion_expr::JoinType;use datafusion_physical_expr::{EquivalenceProperties, PhysicalSortExpr};use futures::{ready, Stream, StreamExt, TryStreamExt};@@ -49,13 +50,11 @@ use std::task::Poll;use crate::error::Result;use crate::execution::context::TaskContext;-use crate::execution::memory_pool::{- MemoryConsumer, SharedMemoryReservation, SharedOptionalMemoryReservation, TryGrow,-};+use crate::execution::memory_pool::MemoryConsumer;use crate::physical_plan::coalesce_batches::concat_batches;/// Data of the inner table side-type JoinLeftData = RecordBatch;+type JoinLeftData = (RecordBatch, MemoryReservation);/// NestedLoopJoinExec executes partitions in parallel./// One input will be collected to a single partition, call it inner-table.@@ -91,8 +90,6 @@ pub struct NestedLoopJoinExec {inner_table: OnceAsync<JoinLeftData>,/// Information of index and left / right placement of columnscolumn_indices: Vec<ColumnIndex>,- /// Operator-level memory reservation for left data- reservation: SharedOptionalMemoryReservation,/// Execution metricsmetrics: ExecutionPlanMetricsSet,}@@ -118,7 +115,6 @@ impl NestedLoopJoinExec {schema: Arc::new(schema),inner_table: Default::default(),column_indices,- reservation: Default::default(),metrics: Default::default(),})}@@ -202,14 +198,13 @@ impl ExecutionPlan for NestedLoopJoinExec {let join_metrics = BuildProbeJoinMetrics::new(partition, &self.metrics);// Initialization of operator-level reservation- self.reservation- .initialize("NestedLoopJoinExec", context.memory_pool());+ let operator_reservation =+ MemoryConsumer::new("NestedLoopJoinExec").register(context.memory_pool());- // Inititalization of stream-level reservation- let reservation = SharedMemoryReservation::from(+ // Initialization of stream-level reservation+ let stream_reservation =MemoryConsumer::new(format!("NestedLoopJoinStream[{partition}]"))- .register(context.memory_pool()),- );+ .register(context.memory_pool());let (outer_table, inner_table) = if left_is_build_side(self.join_type) {// left must be single partition@@ -219,7 +214,7 @@ impl ExecutionPlan for NestedLoopJoinExec {self.left.clone(),context.clone(),join_metrics.clone(),- Arc::new(self.reservation.clone()),+ stream_reservation,)});let outer_table = self.right.execute(partition, context)?;@@ -232,7 +227,7 @@ impl ExecutionPlan for NestedLoopJoinExec {self.right.clone(),context.clone(),join_metrics.clone(),- Arc::new(self.reservation.clone()),+ stream_reservation,)});let outer_table = self.left.execute(partition, context)?;@@ -249,7 +244,7 @@ impl ExecutionPlan for NestedLoopJoinExec {visited_left_side: None,column_indices: self.column_indices.clone(),join_metrics,- reservation,+ reservation: operator_reservation,}))}@@ -314,12 +309,12 @@ async fn load_specified_partition_of_input(input: Arc<dyn ExecutionPlan>,context: Arc<TaskContext>,join_metrics: BuildProbeJoinMetrics,- reservation: Arc<dyn TryGrow>,+ reservation: MemoryReservation,) -> Result<JoinLeftData> {let stream = input.execute(partition, context)?;// Load all batches and count the rows- let (batches, num_rows, _, _) = stream+ let (batches, num_rows, _, reservation) = stream.try_fold((Vec::new(), 0usize, join_metrics, reservation),|mut acc, batch| async {@@ -341,7 +336,7 @@ async fn load_specified_partition_of_input(let merged_batch = concat_batches(&input.schema(), &batches, num_rows)?;- Ok(merged_batch)+ Ok((merged_batch, reservation))}// BuildLeft means the left relation is the single patrition side.@@ -375,13 +370,13 @@ struct NestedLoopJoinStream {/// Join execution metricsjoin_metrics: BuildProbeJoinMetrics,/// Memory reservation for visited_left_side- reservation: SharedMemoryReservation,+ reservation: MemoryReservation,}fn build_join_indices(left_index: usize,batch: &RecordBatch,- left_data: &JoinLeftData,+ left_data: &RecordBatch,filter: Option<&JoinFilter>,) -> Result<(UInt64Array, UInt32Array)> {// left indices: [left_index, left_index, ...., left_index]@@ -413,7 +408,7 @@ impl NestedLoopJoinStream {) -> Poll<Option<Result<RecordBatch>>> {// all left rowlet build_timer = self.join_metrics.build_time.timer();- let left_data = match ready!(self.inner_table.get(cx)) {+ let (left_data, _) = match ready!(self.inner_table.get(cx)) {Ok(data) => data,Err(e) => return Poll::Ready(Some(Err(e))),};@@ -516,7 +511,7 @@ impl NestedLoopJoinStream {) -> Poll<Option<Result<RecordBatch>>> {// all right rowlet build_timer = self.join_metrics.build_time.timer();- let right_data = match ready!(self.inner_table.get(cx)) {+ let (right_data, _) = match ready!(self.inner_table.get(cx)) {Ok(data) => data,Err(e) => return Poll::Ready(Some(Err(e))),};@@ -1168,7 +1163,7 @@ mod tests {err.to_string(),"External error: Resources exhausted: Failed to allocate additional");- assert_contains!(err.to_string(), "NestedLoopJoinExec");+ assert_contains!(err.to_string(), "NestedLoopJoinStream[0]");}Ok(())diff --git a/datafusion/core/tests/memory_limit.rs b/datafusion/core/tests/memory_limit.rsindex ae68b49e79..197a459085 100644--- a/datafusion/core/tests/memory_limit.rs+++ b/datafusion/core/tests/memory_limit.rs@@ -130,7 +130,7 @@ async fn join_by_expression() {"select t1.* from t t1 JOIN t t2 ON t1.service != t2.service",vec!["Resources exhausted: Failed to allocate additional",- "NestedLoopJoinExec",+ "NestedLoopJoinStream[0]",],1_000,)diff --git a/datafusion/execution/src/memory_pool/mod.rs b/datafusion/execution/src/memory_pool/mod.rsindex 066cec9fb1..31117dda4f 100644--- a/datafusion/execution/src/memory_pool/mod.rs+++ b/datafusion/execution/src/memory_pool/mod.rs@@ -17,8 +17,7 @@//! Manages all available memory during query execution-use datafusion_common::{DataFusionError, Result};-use parking_lot::Mutex;+use datafusion_common::Result;use std::sync::Arc;mod pool;@@ -175,64 +174,6 @@ impl Drop for MemoryReservation {}}-pub trait TryGrow: Send + Sync + std::fmt::Debug {- fn try_grow(&self, capacity: usize) -> Result<()>;-}--/// Cloneable reference to [`MemoryReservation`] instance with interior mutability support-#[derive(Clone, Debug)]-pub struct SharedMemoryReservation(Arc<Mutex<MemoryReservation>>);--impl From<MemoryReservation> for SharedMemoryReservation {- /// Creates new [`SharedMemoryReservation`] from [`MemoryReservation`]- fn from(reservation: MemoryReservation) -> Self {- Self(Arc::new(Mutex::new(reservation)))- }-}--impl TryGrow for SharedMemoryReservation {- /// Try to increase the size of this reservation by `capacity` bytes- fn try_grow(&self, capacity: usize) -> Result<()> {- self.0.lock().try_grow(capacity)- }-}--/// Cloneable reference to [`MemoryReservation`] instance with interior mutability support.-/// Doesn't require [`MemoryReservation`] while creation, and can be initialized later.-#[derive(Clone, Debug)]-pub struct SharedOptionalMemoryReservation(Arc<Mutex<Option<MemoryReservation>>>);--impl SharedOptionalMemoryReservation {- /// Initialize inner [`MemoryReservation`] if `None`, otherwise -- do nothing- pub fn initialize(&self, name: impl Into<String>, pool: &Arc<dyn MemoryPool>) {- let mut locked = self.0.lock();- if locked.is_none() {- *locked = Some(MemoryConsumer::new(name).register(pool));- };- }-}--impl TryGrow for SharedOptionalMemoryReservation {- /// Try to increase the size of this reservation by `capacity` bytes- fn try_grow(&self, capacity: usize) -> Result<()> {- self.0- .lock()- .as_mut()- .ok_or_else(|| {- DataFusionError::Internal(- "inner memory reservation not initialized".to_string(),- )- })?- .try_grow(capacity)- }-}--impl Default for SharedOptionalMemoryReservation {- fn default() -> Self {- Self(Arc::new(Mutex::new(None)))- }-}-const TB: u64 = 1 << 40;const GB: u64 = 1 << 30;const MB: u64 = 1 << 20;@@ -289,63 +230,4 @@ mod tests {a2.try_grow(25).unwrap();assert_eq!(pool.reserved(), 25);}-- #[test]- fn test_shared_memory_reservation() {- let pool = Arc::new(GreedyMemoryPool::new(50)) as _;- let a1 = SharedMemoryReservation::from(MemoryConsumer::new("a1").register(&pool));- let a2 = a1.clone();-- // Reserve from a1- a1.try_grow(10).unwrap();- assert_eq!(pool.reserved(), 10);-- // Drop a1 - normally reservation calls `free` on drop.- // Ensure that reservation still alive in a2- drop(a1);- assert_eq!(pool.reserved(), 10);-- // Ensure that after a2 dropped, memory gets back to the pool- drop(a2);- assert_eq!(pool.reserved(), 0);- }-- #[test]- fn test_optional_shared_memory_reservation() {- let pool = Arc::new(GreedyMemoryPool::new(50)) as _;- let a1 = SharedOptionalMemoryReservation::default();-- // try_grow on empty inner reservation- let err = a1.try_grow(10).unwrap_err();- assert_eq!(- err.to_string(),- "Internal error: inner memory reservation not initialized. \- This was likely caused by a bug in DataFusion's code and we \- would welcome that you file an bug report in our issue tracker"- );-- // multiple initializations- a1.initialize("a1", &pool);- a1.initialize("a2", &pool);- {- let locked = a1.0.lock();- let name = locked.as_ref().unwrap().consumer.name();- assert_eq!(name, "a1");- }-- let a2 = a1.clone();-- // Reserve from a1- a1.try_grow(10).unwrap();- assert_eq!(pool.reserved(), 10);-- // Drop a1 - normally reservation calls `free` on drop.- // Ensure that reservation still alive in a2- drop(a1);- assert_eq!(pool.reserved(), 10);-- // Ensure that after a2 dropped, memory gets back to the pool- drop(a2);- assert_eq!(pool.reserved(), 0);- }}