diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs b/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs index 185529ed07d6d..8a0630c401853 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs @@ -17,6 +17,7 @@ use std::mem::{size_of, take}; use std::ops::Range; use std::sync::Arc; +use crate::expressions::Column; use crate::joins::sort_merge_join::filter::{ FilterMetadata, filter_record_batch_by_join_type, get_corrected_filter_mask, get_filter_columns, needs_deferred_filtering, @@ -39,6 +40,7 @@ use arrow::datatypes::{Schema, SchemaRef}; use arrow::record_batch::RecordBatchOptions; use datafusion_common::cast::{as_boolean_array, as_uint64_array}; use datafusion_common::instant::Instant; +use datafusion_common::utils::memory::RecordBatchMemoryCounter; use datafusion_common::{ DataFusionError, JoinSide, JoinType, NullEquality, Result, exec_err, internal_datafusion_err, internal_err, @@ -347,13 +349,13 @@ pub(super) struct BufferedBatch { pub null_joined: Vec, /// Size estimation used for reserving / releasing memory pub size_estimation: usize, - /// Memory footprint of `join_arrays` cached at construction time. + /// Unique buffer bytes retained by `join_arrays`. /// Used during spill to track the residual memory that remains after /// the main batch is written to disk. pub join_arrays_mem: usize, /// Actual amount tracked in the memory reservation for this batch. /// - /// - `InMemory`: equals `size_estimation` (full batch + join_arrays + metadata) + /// - `InMemory`: equals `size_estimation` (full batch + unshared join_arrays + metadata) /// - `Spilled`: equals `join_arrays_mem` (join key arrays stay in memory) /// /// Invariant: `free_reservation()` shrinks by exactly this amount, so we never @@ -386,22 +388,7 @@ impl BufferedBatch { ) -> Result { let join_arrays = join_arrays(&batch, on_column)?; - // Estimation is calculated as - // inner batch size - // + join keys size - // + worst case null_joined (as vector capacity * element size) - // + Range size - // + size of this estimation - let join_arrays_mem: usize = join_arrays - .iter() - .map(|arr| arr.get_array_memory_size()) - .sum(); - - let size_estimation = batch.get_array_memory_size() - + join_arrays_mem - + batch.num_rows().next_power_of_two() * size_of::() - + size_of::>() - + size_of::(); + let (size_estimation, join_arrays_mem) = Self::memory_sizes(&batch, &join_arrays); let num_rows = batch.num_rows(); Ok(BufferedBatch { @@ -416,6 +403,21 @@ impl BufferedBatch { num_rows, }) } + + fn memory_sizes(batch: &RecordBatch, join_arrays: &[ArrayRef]) -> (usize, usize) { + // Only the keys remain resident while the batch is spilled. + let mut counter = RecordBatchMemoryCounter::new(); + let join_arrays_mem = join_arrays + .iter() + .map(|key| counter.count_array(key.as_ref())) + .sum::(); + let size_estimation = join_arrays_mem + + counter.count_batch(batch) + + batch.num_rows().next_power_of_two() * size_of::() + + size_of::>() + + size_of::(); + (size_estimation, join_arrays_mem) + } } // TODO: Spill join arrays (https://github.com/apache/datafusion/pull/17429) @@ -1299,13 +1301,26 @@ impl MaterializingSortMergeJoinStream { match spill_stream.next().await.transpose()? { Some(batch) => { - // Transition the batch back to InMemory + // Computed keys have already been evaluated for this batch. + // Column keys can share the restored batch's allocations again. + for (key, expr) in + bb.join_arrays.iter_mut().zip(&self.on_buffered) + { + if let Some(column) = expr.downcast_ref::() { + *key = Arc::clone(batch.column(column.index())); + } + } + // Arrow's comparator closures retain their input buffers. + self.streamed_buffered_cmp = None; + self.buffered_equality_cmp = None; + (bb.size_estimation, bb.join_arrays_mem) = + BufferedBatch::memory_sizes(&batch, &bb.join_arrays); bb.batch = BufferedBatchState::InMemory(batch); self.spilled_batch_count -= 1; - // The batch is back in memory, so we must account for its size. - let newly_allocated = - bb.size_estimation.saturating_sub(bb.reserved_amount); - self.reservation.grow(newly_allocated); + self.reservation.resize( + self.reservation.size() - bb.reserved_amount + + bb.size_estimation, + ); bb.reserved_amount = bb.size_estimation; self.join_metrics diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs index 03eeccd0e07b2..6c4bdd126bac1 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -33,7 +33,7 @@ use crate::{ }; use arrow::array::{ ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, DictionaryArray, - FixedSizeBinaryArray, Int32Array, RecordBatch, UInt64Array, + FixedSizeBinaryArray, Int32Array, RecordBatch, StringArray, UInt64Array, }; use arrow::compute::{BatchCoalescer, SortOptions, filter_record_batch}; use arrow::datatypes::{DataType, Field, Int32Type, Schema}; @@ -42,6 +42,7 @@ use arrow_schema::SchemaRef; use bytes::Bytes; use datafusion_common::JoinType::*; use datafusion_common::instant::Instant; +use datafusion_common::utils::memory::get_record_batch_memory_size; use datafusion_common::{ DataFusionError, JoinType, NullEquality, Result, ScalarValue, assert_batches_eq, assert_contains, @@ -3780,6 +3781,7 @@ async fn overallocation_multi_batch_spill() -> Result<()> { ); let right_batch_3 = build_table_i32(("a2", &vec![40]), ("b2", &vec![1]), ("c2", &vec![90])); + let memory_limit = column_key_batch_size(&right_batch_1); let left = build_table_from_batches(vec![left_batch_1, left_batch_2, left_batch_3]); let right = build_table_from_batches(vec![right_batch_1, right_batch_2, right_batch_3]); @@ -3797,7 +3799,7 @@ async fn overallocation_multi_batch_spill() -> Result<()> { // Enable DiskManager to allow spilling let runtime = RuntimeEnvBuilder::new() - .with_memory_limit(500, 1.0) + .with_memory_limit(memory_limit, 1.0) .with_disk_manager_builder( DiskManagerBuilder::default().with_mode(DiskManagerMode::OsTmpDirectory), ) @@ -3873,6 +3875,13 @@ async fn overallocation_multi_batch_spill() -> Result<()> { Ok(()) } +fn column_key_batch_size(batch: &RecordBatch) -> usize { + get_record_batch_memory_size(batch) + + batch.num_rows().next_power_of_two() * size_of::() + + size_of::>() + + size_of::() +} + /// Verifies that `peak_mem_used` reflects join_arrays memory on the spill path. /// /// Uses a memory limit smaller than a single batch's `size_estimation` so that @@ -3889,12 +3898,8 @@ async fn spill_join_arrays_memory_accounting() -> Result<()> { ("b1", &vec![1, 1]), ("c1", &vec![4, 5]), ); - let size_estimation = left_batch.get_array_memory_size() - + Int32Array::from(vec![1, 1]).get_array_memory_size() - + 2usize.next_power_of_two() * size_of::() - + size_of::>() - + size_of::(); - let join_arrays_mem = Int32Array::from(vec![1, 1]).get_array_memory_size(); + let size_estimation = column_key_batch_size(&left_batch); + let join_arrays_mem = Int32Array::from(vec![1, 1]).get_buffer_memory_size(); // Memory limit: too small for a full batch, large enough for join_arrays. // Every batch hits the Err arm → spills → grow(join_arrays_mem). @@ -3990,6 +3995,105 @@ async fn spill_join_arrays_memory_accounting() -> Result<()> { Ok(()) } +#[tokio::test] +async fn buffered_batch_reservation_column_and_computed_key() -> Result<()> { + let values = vec![1, 2, 3, 4]; + let batch = build_table_i32(("a", &values), ("b", &values), ("c", &values)); + let column: PhysicalExprRef = Arc::new(Column::new("b", 1)); + let computed: PhysicalExprRef = Arc::new(BinaryExpr::new( + Arc::clone(&column), + Operator::Plus, + Arc::new(Literal::new(ScalarValue::Int32(Some(1)))), + )); + let computed_mem = computed + .evaluate(&batch)? + .into_array(batch.num_rows())? + .get_buffer_memory_size(); + let peak = async |key: PhysicalExprRef| -> Result { + let join = join( + build_table_from_batches(vec![batch.clone()]), + build_table_from_batches(vec![batch.clone()]), + vec![(Arc::clone(&key), key)], + Inner, + )?; + common::collect(join.execute(0, Arc::new(TaskContext::default()))?).await?; + Ok(join + .metrics() + .unwrap() + .sum_by_name("peak_mem_used") + .unwrap() + .as_usize()) + }; + assert_eq!(peak(computed).await?, peak(column).await? + computed_mem); + Ok(()) +} + +#[tokio::test] +async fn spill_two_join_keys_share_buffered_column() -> Result<()> { + let key = "x".repeat(8192); + let array: ArrayRef = Arc::new(StringArray::from(vec![key.as_str()])); + let left_key: ArrayRef = Arc::new(StringArray::from(vec!["other"])); + let left = build_table_from_batches(vec![build_batch_two_cols( + ("a", Arc::clone(&left_key)), + ("b", left_key), + )?]); + let expected = array.get_buffer_memory_size(); + let right = + build_table_from_batches(vec![RecordBatch::try_from_iter([("c", array)])?]); + let on: JoinOn = vec![ + (Arc::new(Column::new("a", 0)), Arc::new(Column::new("c", 0))), + (Arc::new(Column::new("b", 1)), Arc::new(Column::new("c", 0))), + ]; + let runtime = RuntimeEnvBuilder::new() + .with_memory_limit(1, 1.0) + .build_arc()?; + let join = join(left, right, on, Inner)?; + let result = common::collect( + join.execute(0, Arc::new(TaskContext::default().with_runtime(runtime)))?, + ) + .await?; + assert_eq!(result.iter().map(RecordBatch::num_rows).sum::(), 0); + let metrics = join.metrics().unwrap(); + assert_eq!(metrics.spill_count(), Some(1)); + assert_eq!( + metrics.sum_by_name("peak_mem_used").unwrap().as_usize(), + expected + ); + Ok(()) +} + +#[tokio::test] +async fn spill_read_back_releases_original_column_key_buffer() -> Result<()> { + let keys = Int32Array::from(vec![1; 8]); + let original_buffer = keys.values().inner().clone(); + let right = RecordBatch::try_from_iter([("r", Arc::new(keys) as ArrayRef)])?; + let left = RecordBatch::try_from_iter([( + "l", + Arc::new(Int32Array::from(vec![1])) as ArrayRef, + )])?; + let join = join( + build_table_from_batches(vec![left]), + build_table_from_batches(vec![right]), + vec![(Arc::new(Column::new("l", 0)), Arc::new(Column::new("r", 0)))], + Inner, + )?; + let runtime = RuntimeEnvBuilder::new() + .with_memory_limit(1, 1.0) + .build_arc()?; + let ctx = TaskContext::default() + .with_runtime(runtime) + .with_session_config(SessionConfig::new().with_batch_size(2)); + let mut stream = join.execute(0, Arc::new(ctx))?; + let metrics = join.metrics().unwrap(); + drop(join); + + // Check while the join still needs the buffered group for its remaining output. + assert_eq!(stream.next().await.unwrap()?.num_rows(), 2); + assert_eq!(metrics.spill_count(), Some(1)); + assert_eq!(original_buffer.strong_count(), 1); + Ok(()) +} + /// Test the no-headroom scenario: pool is so tight that even /// join_arrays_mem exceeds the pool limit. With force-grow, the /// reservation still tracks the join_arrays unconditionally so the @@ -3998,7 +4102,7 @@ async fn spill_join_arrays_memory_accounting() -> Result<()> { async fn spill_join_arrays_no_headroom() -> Result<()> { use arrow::array::Array; - let join_arrays_mem = Int32Array::from(vec![1, 1]).get_array_memory_size(); + let join_arrays_mem = Int32Array::from(vec![1, 1]).get_buffer_memory_size(); // Pool smaller than join_arrays_mem: try_grow(size_estimation) fails → spill. // Force-grow(join_arrays_mem) succeeds unconditionally → reserved_amount > 0. @@ -4238,6 +4342,7 @@ async fn spill_with_filter_multi_batch() -> Result<()> { ); let right_batch_3 = build_table_i32(("a2", &vec![40]), ("b2", &vec![1]), ("c2", &vec![90])); + let memory_limit = column_key_batch_size(&right_batch_1); let left = build_table_from_batches(vec![left_batch_1, left_batch_2, left_batch_3]); let right = build_table_from_batches(vec![right_batch_1, right_batch_2, right_batch_3]); @@ -4252,7 +4357,7 @@ async fn spill_with_filter_multi_batch() -> Result<()> { let join_types = [Inner, Left, Right, Full]; let runtime = RuntimeEnvBuilder::new() - .with_memory_limit(500, 1.0) + .with_memory_limit(memory_limit, 1.0) .with_disk_manager_builder( DiskManagerBuilder::default().with_mode(DiskManagerMode::OsTmpDirectory), ) @@ -7554,18 +7659,12 @@ async fn spill_filtered_boundary_loses_outer_rows() -> Result<()> { /// exit path — normal return or early `?` error. #[tokio::test] async fn spill_read_back_memory_accounting() -> Result<()> { - use arrow::array::Array; - let left_batch = build_table_i32( ("a1", &vec![0, 1]), ("b1", &vec![1, 1]), ("c1", &vec![4, 5]), ); - let size_estimation = left_batch.get_array_memory_size() - + Int32Array::from(vec![1, 1]).get_array_memory_size() - + 2usize.next_power_of_two() * size_of::() - + size_of::>() - + size_of::(); + let size_estimation = column_key_batch_size(&left_batch); // Memory limit too small for a full batch — forces spilling. let memory_limit = size_estimation / 2; @@ -7666,18 +7765,12 @@ async fn spill_read_back_memory_accounting() -> Result<()> { /// (via `new_empty()`) tracks the transient memory and releases it on drop. #[tokio::test] async fn spill_read_back_single_source() -> Result<()> { - use arrow::array::Array; - let left_batch = build_table_i32( ("a1", &vec![0, 1]), ("b1", &vec![1, 1]), ("c1", &vec![4, 5]), ); - let size_estimation = left_batch.get_array_memory_size() - + Int32Array::from(vec![1, 1]).get_array_memory_size() - + 2usize.next_power_of_two() * size_of::() - + size_of::>() - + size_of::(); + let size_estimation = column_key_batch_size(&left_batch); // Memory limit too small for a full batch — forces spilling. let memory_limit = size_estimation / 2; @@ -7916,6 +8009,7 @@ async fn materializing_spill_pending_stream() -> Result<()> { ("b2", &vec![1, 1]), ("c2", &vec![70, 80]), ); + let memory_limit = column_key_batch_size(&right_batch_1); let left = build_table_from_batches(vec![left_batch_1, left_batch_2]); let right = build_table_from_batches(vec![right_batch_1, right_batch_2]); let on = vec![( @@ -7925,7 +8019,7 @@ async fn materializing_spill_pending_stream() -> Result<()> { let sort_options = vec![SortOptions::default(); on.len()]; let runtime = RuntimeEnvBuilder::new() - .with_memory_limit(500, 1.0) + .with_memory_limit(memory_limit, 1.0) .with_disk_manager_builder(pending_disk_manager_builder()) .build_arc()?; diff --git a/datafusion/sqllogictest/test_files/explain_analyze.slt b/datafusion/sqllogictest/test_files/explain_analyze.slt index ad695af1300c7..c6b96a46c4474 100644 --- a/datafusion/sqllogictest/test_files/explain_analyze.slt +++ b/datafusion/sqllogictest/test_files/explain_analyze.slt @@ -442,7 +442,7 @@ JOIN ea_smj_t2 ON ea_smj_t1.a = ea_smj_t2.a AND ea_smj_t2.b * 50 <= ea_smj_t1.b; ---- Plan with Metrics -01)SortMergeJoinExec: join_type=Inner, on=[(a@0, a@0)], filter=CAST(b@1 AS Int64) * 50 <= CAST(b@0 AS Int64), metrics=[output_bytes=320.0 KB, spilled_bytes=0.0 B, peak_mem_used=432.0 B] +01)SortMergeJoinExec: join_type=Inner, on=[(a@0, a@0)], filter=CAST(b@1 AS Int64) * 50 <= CAST(b@0 AS Int64), metrics=[output_bytes=320.0 KB, spilled_bytes=0.0 B, peak_mem_used=80.0 B] 02)--SortExec: expr=[a@0 ASC], preserve_partitioning=[false], metrics=[output_bytes=60.0 B, spilled_bytes=0.0 B] 03)----DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] 04)--SortExec: expr=[a@0 ASC], preserve_partitioning=[false], metrics=[output_bytes=40.0 B, spilled_bytes=0.0 B]