Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -347,13 +349,13 @@ pub(super) struct BufferedBatch {
pub null_joined: Vec<usize>,
/// 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
Expand Down Expand Up @@ -386,22 +388,7 @@ impl BufferedBatch {
) -> Result<Self> {
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::<usize>()
+ size_of::<Range<usize>>()
+ size_of::<usize>();
let (size_estimation, join_arrays_mem) = Self::memory_sizes(&batch, &join_arrays);

let num_rows = batch.num_rows();
Ok(BufferedBatch {
Expand All @@ -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::<usize>();
let size_estimation = join_arrays_mem
+ counter.count_batch(batch)
+ batch.num_rows().next_power_of_two() * size_of::<usize>()
+ size_of::<Range<usize>>()
+ size_of::<usize>();
(size_estimation, join_arrays_mem)
}
}

// TODO: Spill join arrays (https://github.com/apache/datafusion/pull/17429)
Expand Down Expand Up @@ -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::<Column>() {
*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
Expand Down
144 changes: 119 additions & 25 deletions datafusion/physical-plan/src/joins/sort_merge_join/tests.rs

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the new test cover a computed join key and the spill/read-back path, where the key array is actually unshared? When a batch spills, does the reservation still avoid double-counting buffers shared with the key arrays?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, added a test which covers a computed key and the spill/read-back path. On spill the batch is dropped, so only the key arrays stay in memory and they’re counted once.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The size_estimation / 2 runs in buffered_batch_reservation_column_and_computed_key don't reach the read-back change. restore_spilled_batches sets the reservation from the cached size_estimation, so those runs pass with the re-evaluation removed and repeat the unlimited runs. No reservation metric can see that line, because it changes which buffers the keys point at, not how much is reserved. A test would have to look at retained buffers instead, for example Buffer::strong_count on the pre-spill key buffer (an untested idea).

Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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,
Expand Down Expand Up @@ -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]);
Expand All @@ -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),
)
Expand Down Expand Up @@ -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::<usize>()
+ size_of::<std::ops::Range<usize>>()
+ size_of::<usize>()
}

/// 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
Expand All @@ -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::<usize>()
+ size_of::<std::ops::Range<usize>>()
+ size_of::<usize>();
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).
Expand Down Expand Up @@ -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<usize> {
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::<usize>(), 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
Expand All @@ -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.
Expand Down Expand Up @@ -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]);
Expand All @@ -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),
)
Expand Down Expand Up @@ -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::<usize>()
+ size_of::<std::ops::Range<usize>>()
+ size_of::<usize>();
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;
Expand Down Expand Up @@ -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::<usize>()
+ size_of::<std::ops::Range<usize>>()
+ size_of::<usize>();
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;
Expand Down Expand Up @@ -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![(
Expand All @@ -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()?;

Expand Down
2 changes: 1 addition & 1 deletion datafusion/sqllogictest/test_files/explain_analyze.slt
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down