From 64f93ad257de3845eeccd398146e393b32bb980b Mon Sep 17 00:00:00 2001 From: comphead Date: Tue, 1 Dec 2026 12:31:25 -0800 Subject: [PATCH 1/3] bench: add sort-merge join cases for an n:1 join and a selective Left join `inner_10to1` joins 10 streamed rows to each buffered row, as a fact table joins a dimension on its key. `left_1to1000_selective_filtered` runs the inputs and filter of `inner_1to1000_selective_filtered` as a Left join. --- .../physical-plan/benches/sort_merge_join.rs | 37 ++++++++++++++++--- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/datafusion/physical-plan/benches/sort_merge_join.rs b/datafusion/physical-plan/benches/sort_merge_join.rs index 6d888e5fd3d54..0d4540dba8cf0 100644 --- a/datafusion/physical-plan/benches/sort_merge_join.rs +++ b/datafusion/physical-plan/benches/sort_merge_join.rs @@ -196,6 +196,21 @@ fn bench_smj(c: &mut Criterion) { }); } + // N:1 Inner Join — 100K left, 10K right, 10K distinct keys + // Each buffered row matches the 10 streamed rows of its key, as when a fact + // table joins a dimension table on its primary key. + { + let left_batches = build_sorted_batches(100_000, 10_000, &s); + let right_batches = build_sorted_batches(10_000, 10_000, &s); + group.bench_function(BenchmarkId::new("inner_10to1", 100_000), |b| { + b.iter(|| { + let left = make_exec(&left_batches, &s); + let right = make_exec(&right_batches, &s); + do_join(left, right, datafusion_common::JoinType::Inner, &rt) + }) + }); + } + // 1:10 Inner Join — 100K left, 100K right, 10K distinct keys { let n = 100_000; @@ -337,22 +352,32 @@ fn bench_smj(c: &mut Criterion) { let keys = 20; let left_batches = build_sorted_batches(keys * 100, keys, &s); let right_batches = build_sorted_batches(keys * 1000, keys, &s); - group.bench_function( - BenchmarkId::new("inner_1to1000_selective_filtered", keys * 1000), - |b| { + // The same join as a Left join, which also emits the first streamed row + // of each key, whose pairs all fail, joined to NULLs. + for (name, join_type) in [ + ( + "inner_1to1000_selective_filtered", + datafusion_common::JoinType::Inner, + ), + ( + "left_1to1000_selective_filtered", + datafusion_common::JoinType::Left, + ), + ] { + group.bench_function(BenchmarkId::new(name, keys * 1000), |b| { b.iter(|| { let left = make_exec(&left_batches, &s); let right = make_exec(&right_batches, &s); do_join_with_filter( left, right, - datafusion_common::JoinType::Inner, + join_type, Some(data_filter(Operator::Gt)), &rt, ) }) - }, - ); + }); + } } // Left Join — 100K each, ~5% unmatched on left From 0a4ba31543c01418b49f396374520eb276bb47b0 Mon Sep 17 00:00:00 2001 From: comphead Date: Tue, 1 Dec 2026 12:32:07 -0800 Subject: [PATCH 2/3] perf: keep sort-merge join pairs as runs and filter outer join pairs first A streamed row and the run of buffered rows it matches are now recorded as one `PairRun`, in a vector that the freezes reuse, instead of a pair of `u64` indices per match in chunks allocated for each buffered batch. At the freeze a side whose rows form a range is sliced as before, long runs of buffered rows are copied as ranges, and the streamed row of a long run is repeated for primitive columns. Short runs are still gathered row by row. Left, Right and Full joins with a filter now evaluate it before materializing pairs, like Inner joins. They keep the pairs that pass and the first pair of each streamed row whose pairs all fail, which the deferred filter null-joins as before. --- .../sort_merge_join/materializing_stream.rs | 1503 +++++++++++------ .../src/joins/sort_merge_join/tests.rs | 103 +- 2 files changed, 1036 insertions(+), 570 deletions(-) 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..50ce96fff2529 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 @@ -12,7 +12,6 @@ use std::cmp::Ordering; use std::collections::VecDeque; use std::fmt::Debug; -use std::iter::repeat_n; use std::mem::{size_of, take}; use std::ops::Range; use std::sync::Arc; @@ -31,11 +30,12 @@ use crate::stream::{EmptyRecordBatchStream, ObservedStream, RecordBatchStreamAda use crate::{PhysicalExpr, SendableRecordBatchStream}; use arrow::array::{types::UInt64Type, *}; +use arrow::buffer::NullBuffer; use arrow::compute::{ self, BatchCoalescer, FilterBuilder, FilterPredicate, SortOptions, concat_batches, filter_record_batch, interleave, }; -use arrow::datatypes::{Schema, SchemaRef}; +use arrow::datatypes::{DataType, Schema, SchemaRef}; use arrow::record_batch::RecordBatchOptions; use datafusion_common::cast::{as_boolean_array, as_uint64_array}; use datafusion_common::instant::Instant; @@ -50,27 +50,277 @@ use datafusion_physical_expr_common::physical_expr::PhysicalExprRef; use futures::StreamExt; -/// The matched pairs of one [`StreamedJoinedChunk`], with the indices finished -/// into arrays. -struct MatchedChunk { - /// Index of the batch in `buffered_data` that the buffered rows come from - buffered_batch_idx: usize, - /// The streamed row of each pair - streamed_indices: UInt64Array, - /// The buffered row of each pair - buffered_indices: UInt64Array, +/// A streamed row paired with `len` consecutive rows of one buffered batch, +/// from `buffered_row` on. A streamed row that no buffered row matches makes a +/// single null-joined pair, which has no `buffered_batch`. +/// +/// Pairs are recorded as runs and expanded only at the freeze, where a run of +/// buffered rows is copied as a range rather than gathered row by row. +#[derive(Clone, Copy, Debug)] +pub(super) struct PairRun { + /// The streamed row + streamed_row: usize, + /// Index in `buffered_data` of the batch that the buffered rows come from + buffered_batch: Option, + /// The first buffered row, 0 for a null-joined pair + buffered_row: usize, + /// The number of pairs + len: usize, +} + +impl PairRun { + /// Where a run that continues this one starts. Null-joined pairs continue + /// each other. + fn buffered_end(&self) -> usize { + match self.buffered_batch { + Some(_) => self.buffered_row + self.len, + None => 0, + } + } +} + +/// Runs of fewer pairs than this on average are gathered row by row, since +/// copying a range of buffered rows, or repeating a streamed row, costs more per +/// run than gathering its rows. Measured on joins of `Int64` columns, copying +/// breaks even at runs of 12 rows, and earlier with a string column. +const MIN_COPIED_RUN_LEN: usize = 12; + +/// What a freeze needs to know about its runs, found in one pass. +struct RunsSummary { + /// The number of ranges of buffered rows, merging runs that continue each + /// other (see [`buffered_ranges`]) + num_ranges: usize, + /// The least and the greatest index of a buffered batch that a run reads + batches: Option<(usize, usize)>, + /// Whether a pair has no buffered row + nulls: bool, + /// Whether the streamed rows form a range, one per pair + streamed_range: bool, } -impl MatchedChunk { - fn len(&self) -> usize { - self.streamed_indices.len() +impl RunsSummary { + fn new(runs: &[PairRun], num_pairs: usize) -> Self { + let first_row = runs[0].streamed_row; + let mut summary = Self { + num_ranges: 0, + batches: None, + nulls: false, + streamed_range: runs.len() == num_pairs, + }; + // Where the last range ends, as a batch (`usize::MAX` for null rows) and a + // row, starting at a position that no run continues. + let mut range_end = (usize::MAX, usize::MAX); + let (mut lo, mut hi) = (usize::MAX, 0); + for (i, run) in runs.iter().enumerate() { + summary.streamed_range &= run.streamed_row == first_row + i; + let batch = run.buffered_batch.unwrap_or(usize::MAX); + summary.num_ranges += usize::from(range_end != (batch, run.buffered_row)); + range_end = (batch, run.buffered_end()); + if batch == usize::MAX { + summary.nulls = true; + } else { + lo = lo.min(batch); + hi = hi.max(batch); + } + } + summary.batches = (lo <= hi).then_some((lo, hi)); + summary } } +/// Where the streamed rows of a freeze's pairs are. +enum StreamedRows { + /// A range of rows, one per pair, whose columns are slices + Range(Range), + /// Rows repeated for runs of pairs, each a `(row, count)`, `num_rows` in all + Repeated { + repeats: Vec<(usize, usize)>, + num_rows: usize, + }, + /// The row of each pair + Indices(UInt64Array), +} + +impl StreamedRows { + fn new(runs: &[PairRun], num_pairs: usize, summary: &RunsSummary) -> Self { + if summary.streamed_range { + let first = runs[0].streamed_row; + return Self::Range(first..first + num_pairs); + } + if num_pairs >= runs.len() * MIN_COPIED_RUN_LEN { + let mut repeats: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for run in runs { + match repeats.last_mut() { + Some((row, count)) if *row == run.streamed_row => *count += run.len, + _ => repeats.push((run.streamed_row, run.len)), + } + } + return Self::repeated(repeats, num_pairs); + } + let indices: Vec = if runs.len() == num_pairs { + runs.iter().map(|run| run.streamed_row as u64).collect() + } else { + let mut indices = Vec::with_capacity(num_pairs); + for run in runs { + indices.resize(indices.len() + run.len, run.streamed_row as u64); + } + indices + }; + Self::Indices(UInt64Array::new(indices.into(), None)) + } + + /// The rows of `repeats`, which hold `num_rows` rows, repeated, or gathered + /// row by row when the repeats are short. + fn repeated(repeats: Vec<(usize, usize)>, num_rows: usize) -> Self { + let rows = Self::Repeated { repeats, num_rows }; + match &rows { + Self::Repeated { repeats, .. } + if num_rows < repeats.len() * MIN_COPIED_RUN_LEN => + { + Self::Indices(rows.indices()) + } + _ => rows, + } + } + + fn is_range(&self) -> bool { + matches!(self, Self::Range(_)) + } + + /// The rows of the pairs at which `kept` is set. `predicate` is built from + /// `kept`. + fn filter(self, predicate: &FilterPredicate, kept: &BooleanArray) -> Result { + let indices = match self { + Self::Range(range) => range_indices(range), + Self::Repeated { repeats, .. } => { + let kept = kept.values(); + let mut start = 0; + let mut kept_repeats = Vec::with_capacity(repeats.len()); + for (row, count) in repeats { + let kept_count = kept + .inner() + .count_set_bits_offset(kept.offset() + start, count); + if kept_count > 0 { + kept_repeats.push((row, kept_count)); + } + start += count; + } + return Ok(Self::repeated(kept_repeats, predicate.count())); + } + Self::Indices(indices) => indices, + }; + Ok(Self::Indices( + as_uint64_array(&predicate.filter(&indices)?)?.clone(), + )) + } + + /// The row of each pair, for the deferred filter's metadata + fn indices(&self) -> UInt64Array { + match self { + Self::Range(range) => range_indices(range.clone()), + Self::Repeated { repeats, num_rows } => { + let mut indices = Vec::with_capacity(*num_rows); + for &(row, count) in repeats { + indices.resize(indices.len() + count, row as u64); + } + UInt64Array::new(indices.into(), None) + } + Self::Indices(indices) => indices.clone(), + } + } + + /// The `columns` of `batch` at the rows. + fn columns(&self, batch: &RecordBatch, columns: &[usize]) -> Result> { + let arrays = columns.iter().map(|&c| batch.column(c)); + match self { + Self::Range(range) => { + Ok(arrays.map(|a| a.slice(range.start, range.len())).collect()) + } + Self::Repeated { repeats, num_rows } => { + // Gathered for the columns that cannot be repeated directly + let mut indices = None; + arrays + .map(|a| { + match repeat_primitive_rows(a.as_ref(), repeats, *num_rows) { + Some(repeated) => Ok(repeated), + None => { + let indices = + indices.get_or_insert_with(|| self.indices()); + Ok(compute::take(a.as_ref(), indices, None)?) + } + } + }) + .collect() + } + Self::Indices(indices) => arrays + .map(|a| Ok(compute::take(a.as_ref(), indices, None)?)) + .collect(), + } + } +} + +/// The rows of `array` each repeated, as `(row, count)` runs that hold +/// `num_rows` rows, or `None` unless `array` is a primitive array. +fn repeat_primitive_rows( + array: &dyn Array, + repeats: &[(usize, usize)], + num_rows: usize, +) -> Option { + fn repeat( + array: &PrimitiveArray, + repeats: &[(usize, usize)], + num_rows: usize, + ) -> ArrayRef { + let values = array.values(); + let mut repeated = Vec::with_capacity(num_rows); + for &(row, count) in repeats { + repeated.resize(repeated.len() + count, values[row]); + } + let nulls = array.nulls().filter(|n| n.null_count() > 0).map(|nulls| { + let mut validity = BooleanBufferBuilder::new(num_rows); + for &(row, count) in repeats { + validity.append_n(count, nulls.is_valid(row)); + } + NullBuffer::new(validity.finish()) + }); + Arc::new( + PrimitiveArray::::new(repeated.into(), nulls) + .with_data_type(array.data_type().clone()), + ) + } + downcast_primitive_array!( + array => Some(repeat(array, repeats, num_rows)), + _ => None + ) +} + +/// The indices of the rows of `range`. +fn range_indices(range: Range) -> UInt64Array { + UInt64Array::from_iter_values(range.start as u64..range.end as u64) +} + +/// Rows of the buffered batches that a freeze copies as a range. A range +/// without a source is null rows. +#[derive(Clone, Copy)] +struct CopiedRange { + source: Option, + start: usize, + len: usize, +} + /// Where the buffered rows of a freeze's pairs are (see /// [`MaterializingSortMergeJoinStream::buffered_rows`]). enum BufferedRows<'a> { - /// The rows of one buffered batch at these indices + /// A range of rows of one buffered batch, whose columns are slices + Range(&'a RecordBatch, Range), + /// Ranges of rows of the `batches`, copied in turn + Ranges { + batches: Vec<&'a RecordBatch>, + ranges: Vec, + num_rows: usize, + }, + /// The rows of one buffered batch at these indices, null where a pair has no + /// buffered row Batch(&'a RecordBatch, UInt64Array), /// Rows of several buffered batches, each a `(source, row)` pair for /// `interleave`. When `nulls` is set, source 0 is a null row and the batches @@ -80,14 +330,105 @@ enum BufferedRows<'a> { nulls: bool, indices: Vec<(usize, usize)>, }, + /// Null rows of the buffered schema + Nulls(&'a Schema, usize), } impl BufferedRows<'_> { + fn is_range(&self) -> bool { + matches!(self, Self::Range(..)) + } + + /// The rows of the pairs at which `kept` is set. `predicate` is built from + /// `kept`. + fn filter(self, predicate: &FilterPredicate, kept: &BooleanArray) -> Result { + let num_kept = predicate.count(); + Ok(match self { + Self::Range(batch, range) => Self::Batch( + batch, + as_uint64_array(&predicate.filter(&range_indices(range))?)?.clone(), + ), + Self::Ranges { + batches, ranges, .. + } => { + let kept_ranges = filter_ranges(&ranges, kept); + let nulls = kept_ranges.iter().any(|r| r.source.is_none()); + ranges_or_gathered(batches, kept_ranges, nulls, num_kept) + } + Self::Batch(batch, indices) => Self::Batch( + batch, + as_uint64_array(&predicate.filter(&indices)?)?.clone(), + ), + Self::Interleaved { + batches, + nulls, + indices, + } => { + // Copy runs of kept pairs, which is cheap when most are kept. + let mut kept_indices = Vec::with_capacity(num_kept); + for (start, end) in kept.values().set_slices() { + kept_indices.extend_from_slice(&indices[start..end]); + } + Self::Interleaved { + batches, + nulls, + indices: kept_indices, + } + } + Self::Nulls(schema, _) => Self::Nulls(schema, num_kept), + }) + } + /// The `columns` of the rows. fn columns(&self, columns: &[usize]) -> Result> { let (batches, nulls, indices) = match self { + Self::Range(batch, range) => { + return Ok(columns + .iter() + .map(|&c| batch.column(c).slice(range.start, range.len())) + .collect()); + } + Self::Ranges { + batches, + ranges, + num_rows, + } => { + // Copying the ranges of several batches would concatenate their + // dictionaries, which `interleave` merges instead. + let mut gathered = None; + return columns + .iter() + .map(|&c| { + if batches.len() > 1 + && matches!( + batches[0].schema_ref().field(c).data_type(), + DataType::Dictionary(..) + ) + { + let rows = gathered.get_or_insert_with(|| { + let nulls = ranges.iter().any(|r| r.source.is_none()); + gather_ranges( + batches.clone(), + ranges.iter().copied(), + nulls, + *num_rows, + ) + }); + Ok(rows.columns(&[c])?.remove(0)) + } else { + copy_ranges(batches, c, ranges, *num_rows) + } + }) + .collect(); + } Self::Batch(batch, indices) => { - return materialize_columns(batch, indices, columns); + return columns + .iter() + .map(|&c| Ok(compute::take(batch.column(c), indices, None)?)) + .collect(); + } + Self::Nulls(schema, num_rows) => { + return Ok(create_unmatched_columns(schema, columns, *num_rows)); } Self::Interleaved { batches, @@ -113,45 +454,191 @@ impl BufferedRows<'_> { } Ok(arrays) } +} - /// The rows at which `passed` is set. `predicate` is built from `passed`. - fn filter(self, predicate: &FilterPredicate, passed: &BooleanArray) -> Result { - Ok(match self { - Self::Batch(batch, indices) => Self::Batch( - batch, - as_uint64_array(&predicate.filter(&indices)?)?.clone(), - ), - Self::Interleaved { - batches, - nulls, - indices, - } if predicate.count() < indices.len() => { - // Copy runs of passing pairs, which is cheap when most pass. - let mut kept = Vec::with_capacity(predicate.count()); - for (start, end) in passed.values().set_slices() { - kept.extend_from_slice(&indices[start..end]); - } - Self::Interleaved { - batches, - nulls, - indices: kept, - } +/// Copies `ranges` of the `column` of `batches` into one array of `num_rows`. +fn copy_ranges( + batches: &[&RecordBatch], + column: usize, + ranges: &[CopiedRange], + num_rows: usize, +) -> Result { + let data: Vec = + batches.iter().map(|b| b.column(column).to_data()).collect(); + let nulls = ranges.iter().any(|r| r.source.is_none()); + let mut copied = MutableArrayData::try_new(data.iter().collect(), nulls, num_rows)?; + for range in ranges { + match range.source { + Some(source) => { + copied.try_extend(source, range.start, range.start + range.len)? } - all_passed => all_passed, - }) + None => copied.try_extend_nulls(range.len)?, + } + } + Ok(make_array(copied.freeze())) +} + +/// The rows of `ranges` at which `mask` is set, as ranges. +fn filter_ranges(ranges: &[CopiedRange], mask: &BooleanArray) -> Vec { + let mut kept = Vec::new(); + let mut ranges = ranges.iter(); + let (mut range, mut range_start) = (ranges.next(), 0); + for (start, end) in mask.values().set_slices() { + let mut start = start; + while let Some(r) = range { + let range_end = range_start + r.len; + if range_end <= start { + (range, range_start) = (ranges.next(), range_end); + continue; + } + kept.push(CopiedRange { + source: r.source, + start: r.start + (start - range_start), + len: end.min(range_end) - start, + }); + if end <= range_end { + break; + } + start = range_end; + (range, range_start) = (ranges.next(), range_end); + } + } + kept +} + +/// `num_rows` rows of `batches`, in `ranges` whose sources index `batches`: +/// copied as ranges when they are long, and otherwise gathered row by row. +fn ranges_or_gathered( + batches: Vec<&RecordBatch>, + ranges: Vec, + nulls: bool, + num_rows: usize, +) -> BufferedRows<'_> { + if num_rows >= ranges.len() * MIN_COPIED_RUN_LEN { + return BufferedRows::Ranges { + batches, + ranges, + num_rows, + }; + } + gather_ranges(batches, ranges.iter().copied(), nulls, num_rows) +} + +/// `num_rows` rows of `batches`, in `ranges` whose sources index `batches`, +/// gathered row by row. `nulls` tells whether a range has no source. +fn gather_ranges( + batches: Vec<&RecordBatch>, + ranges: impl ExactSizeIterator + Clone, + nulls: bool, + num_rows: usize, +) -> BufferedRows<'_> { + if let [batch] = batches[..] { + let indices: Vec = if ranges.len() == num_rows { + // One row per range, as in a 1:1 or n:1 join + ranges.clone().map(|range| range.start as u64).collect() + } else { + let mut indices = Vec::with_capacity(num_rows); + for range in ranges.clone() { + indices.extend(range.start as u64..(range.start + range.len) as u64); + } + indices + }; + let validity = nulls.then(|| { + let mut validity = BooleanBufferBuilder::new(num_rows); + for range in ranges { + validity.append_n(range.len, range.source.is_some()); + } + NullBuffer::new(validity.finish()) + }); + return BufferedRows::Batch(batch, UInt64Array::new(indices.into(), validity)); + } + // A null-row sentinel at source index 0 handles rows without a source, only + // when there are some: `interleave` walks a null buffer for *every* output + // row as soon as any input is nullable. + let offset = usize::from(nulls); + let mut indices = Vec::with_capacity(num_rows); + for range in ranges { + match range.source { + Some(source) => indices.extend( + (range.start..range.start + range.len).map(|row| (source + offset, row)), + ), + None => indices.resize(indices.len() + range.len, (0, 0)), + } + } + BufferedRows::Interleaved { + batches, + nulls, + indices, + } +} + +/// The buffered rows of `runs` as ranges, merging runs that continue each +/// other. A range's source is the index of its buffered batch. +fn buffered_ranges(runs: &[PairRun]) -> impl Iterator + '_ { + let mut runs = runs.iter().peekable(); + std::iter::from_fn(move || { + let first = runs.next()?; + let mut range = CopiedRange { + source: first.buffered_batch, + start: first.buffered_row, + len: first.len, + }; + let mut end = first.buffered_end(); + while let Some(next) = runs + .next_if(|run| run.buffered_batch == range.source && run.buffered_row == end) + { + range.len += next.len; + end = next.buffered_end(); + } + Some(range) + }) +} + +/// `passed`, plus the first pair of each streamed row of `runs` whose pairs all +/// failed. +fn passed_or_first_of_row(runs: &[PairRun], passed: &BooleanArray) -> BooleanArray { + let values = passed.values(); + let mut kept: Option = None; + let (mut start, mut i) = (0, 0); + while i < runs.len() { + let row = runs[i].streamed_row; + let mut end = start; + while i < runs.len() && runs[i].streamed_row == row { + end += runs[i].len; + i += 1; + } + let none_passed = if end - start == 1 { + !values.value(start) + } else { + values + .inner() + .count_set_bits_offset(values.offset() + start, end - start) + == 0 + }; + if none_passed { + kept.get_or_insert_with(|| { + let mut kept = BooleanBufferBuilder::new(values.len()); + kept.append_buffer(values); + kept + }) + .set_bit(start, true); + } + start = end; + } + match kept { + Some(mut kept) => BooleanArray::new(kept.finish(), None), + None => passed.clone(), } } -/// Represents a chunk of joined data from streamed and buffered side -pub(super) struct StreamedJoinedChunk { - /// Index of batch in buffered_data - buffered_batch_idx: Option, - /// Streamed indices, which are never null - streamed_indices: Vec, - /// Buffered indices. The slot of a null-joined pair holds 0. - buffered_indices: Vec, - /// Validity of `buffered_indices`, null where the pair is null-joined - buffered_nulls: NullBufferBuilder, +/// What a freeze stages for output. +struct FrozenPairs { + batch: RecordBatch, + /// For the deferred filter: the streamed row of each output row, and whether + /// its pair passed the filter + metadata: Option<(UInt64Array, BooleanArray)>, + /// Whether each pair of the freeze passed the filter + passed: Option, } /// Represents a record batch from streamed input. @@ -165,24 +652,28 @@ pub(super) struct StreamedBatch { /// The join key arrays of streamed batch which are used to compare with buffered batches /// and to produce output. They are produced by evaluating `on` expressions. pub join_arrays: Vec, - /// Chunks of indices from buffered side (may be nulls) joined to streamed - pub output_indices: Vec, - /// Total number of output rows across all chunks in `output_indices` + /// The pairs not frozen yet, in output order + pub runs: Vec, + /// Total number of pairs in `runs` pub num_output_rows: usize, - /// Index of currently scanned batch from buffered data - pub buffered_batch_idx: Option, } impl StreamedBatch { - fn try_new(batch: RecordBatch, on_column: &[Arc]) -> Result { + /// The streamed `batch`, which records its pairs in `runs`, an empty vector + /// whose capacity is reused. + fn try_new( + batch: RecordBatch, + on_column: &[Arc], + runs: Vec, + ) -> Result { + debug_assert!(runs.is_empty(), "pairs left unfrozen"); let join_arrays = join_arrays(&batch, on_column)?; Ok(StreamedBatch { batch, idx: 0, join_arrays, - output_indices: vec![], + runs, num_output_rows: 0, - buffered_batch_idx: None, }) } @@ -191,9 +682,8 @@ impl StreamedBatch { batch: RecordBatch::new_empty(schema), idx: 0, join_arrays: vec![], - output_indices: vec![], + runs: vec![], num_output_rows: 0, - buffered_batch_idx: None, } } @@ -202,115 +692,34 @@ impl StreamedBatch { self.num_output_rows } - /// Appends a pair of the current streamed index and a null buffered index, for a - /// streamed row that no buffered row matches. - fn append_null_joined_pair( - &mut self, - buffered_batch_idx: Option, - batch_size: usize, - ) { - let streamed_idx = self.idx as u64; - let current_chunk = self.chunk_for(buffered_batch_idx, batch_size); - current_chunk.streamed_indices.push(streamed_idx); - current_chunk.buffered_indices.push(0); - current_chunk.buffered_nulls.append_null(); + /// Appends a null-joined pair for the current streamed row, which no + /// buffered row matches. + fn append_null_joined_pair(&mut self) { + self.runs.push(PairRun { + streamed_row: self.idx, + buffered_batch: None, + buffered_row: 0, + len: 1, + }); self.num_output_rows += 1; } - /// Appends a pair of the current streamed index and each of the `len` rows from - /// `buffered_start` on in the buffered batch with `buffered_batch_idx` index. The - /// indices are appended in bulk, which matters when a streamed row matches many - /// buffered rows. + /// Appends the pairs of the current streamed row with each of the `len` + /// rows from `buffered_row` on in the buffered batch at `buffered_batch`. fn append_output_pairs( &mut self, - buffered_batch_idx: usize, - buffered_start: usize, - len: usize, - batch_size: usize, - ) { - debug_assert!( - len > 0 && self.num_output_rows + len <= batch_size, - "appending {len} pairs to {} with batch_size {batch_size}", - self.num_output_rows - ); - match len { - // A single match, as in a one-to-one join, is cheaper to append directly. - 1 => { - let streamed_idx = self.idx as u64; - let current_chunk = self.chunk_for(Some(buffered_batch_idx), batch_size); - current_chunk.streamed_indices.push(streamed_idx); - current_chunk.buffered_indices.push(buffered_start as u64); - current_chunk.buffered_nulls.append_non_null(); - self.num_output_rows += 1; - } - _ => self.append_output_range( - buffered_batch_idx, - buffered_start, - len, - batch_size, - ), - } - } - - /// The bulk half of [`Self::append_output_pairs`], kept out of line so that the - /// one-row case, which one-to-one joins take for every row, does not pay for its - /// setup. - #[inline(never)] - fn append_output_range( - &mut self, - buffered_batch_idx: usize, - buffered_start: usize, + buffered_batch: usize, + buffered_row: usize, len: usize, - batch_size: usize, ) { - let streamed_idx = self.idx as u64; - let current_chunk = self.chunk_for(Some(buffered_batch_idx), batch_size); - current_chunk - .streamed_indices - .extend(repeat_n(streamed_idx, len)); - let start = buffered_start as u64; - current_chunk - .buffered_indices - .extend(start..start + len as u64); - current_chunk.buffered_nulls.append_n_non_nulls(len); - self.num_output_rows += len; - } - - /// Returns the chunk that pairs for `buffered_batch_idx` go to, starting a new one - /// if there is no chunk yet or the current chunk is for another buffered batch. - #[inline(always)] - fn chunk_for( - &mut self, - buffered_batch_idx: Option, - batch_size: usize, - ) -> &mut StreamedJoinedChunk { - if self.output_indices.is_empty() || self.buffered_batch_idx != buffered_batch_idx - { - self.start_chunk(buffered_batch_idx, batch_size); - } - self.output_indices.last_mut().unwrap() - } - - /// Starts the chunk for `buffered_batch_idx`. Kept out of line because a chunk - /// usually takes many pairs, so the check in [`Self::chunk_for`] stays small. - #[cold] - #[inline(never)] - fn start_chunk(&mut self, buffered_batch_idx: Option, batch_size: usize) { - // The capacity is the remaining space to reach batch_size. - // This should always be >= 1 since we only call this when num_output_rows < batch_size. - debug_assert!( - batch_size > self.num_output_rows, - "batch_size ({batch_size}) must be > num_output_rows ({})", - self.num_output_rows - ); - let capacity = batch_size - self.num_output_rows; - self.output_indices.push(StreamedJoinedChunk { - buffered_batch_idx, - streamed_indices: Vec::with_capacity(capacity), - buffered_indices: Vec::with_capacity(capacity), - buffered_nulls: NullBufferBuilder::new(capacity), + debug_assert!(len > 0, "appending an empty run"); + self.runs.push(PairRun { + streamed_row: self.idx, + buffered_batch: Some(buffered_batch), + buffered_row, + len, }); - self.buffered_batch_idx = buffered_batch_idx; + self.num_output_rows += len; } } @@ -475,14 +884,14 @@ pub(super) struct MaterializingSortMergeJoinStream { pub streamed_gathered_columns: Vec, pub buffered_gathered_columns: Vec, /// The streamed and buffered columns that the join filter reads, each in the - /// filter's order. Empty unless this is an Inner join with a filter (see - /// [`Self::freeze_inner_filtered`]). + /// filter's order (see [`Self::materialize_pairs`]). pub streamed_filter_columns: Vec, pub buffered_filter_columns: Vec, - /// Whether this Inner join filters the pairs of a freeze before it - /// materializes them (see [`Self::freeze_inner_filtered`]). + /// Whether this join filters the pairs of a freeze before it materializes + /// them (see [`Self::materialize_pairs`]). An outer join always does, which + /// also spares the deferred filter the pairs that fail. /// - /// Filtering first gathers the filter's columns for every pair, filters them + /// For an Inner join, filtering first gathers the filter's columns for every pair, filters them /// and the pairs' index arrays, and gathers the `u` emitted columns that the /// filter does not read for the share `p` of pairs that pass. The other way /// gathers all of these columns for every pair and copies the share `p` of @@ -750,23 +1159,22 @@ impl MaterializingSortMergeJoinStream { semi/anti/mark joins use BitwiseSortMergeJoinStream" ); let join_time = join_metrics.join_time(); - let buffered_side = if join_type == JoinType::Right { - JoinSide::Left + let (streamed_side, buffered_side) = if join_type == JoinType::Right { + (JoinSide::Right, JoinSide::Left) } else { - JoinSide::Right + (JoinSide::Left, JoinSide::Right) }; let deferred_filtering = needs_deferred_filtering(filter.as_ref(), join_type); - let filter_columns = |side| match &filter { - Some(f) if join_type == JoinType::Inner => f - .column_indices() + let filter_columns = |side| { + filter .iter() + .flat_map(|f| f.column_indices()) .filter(|c| c.side == side) .map(|c| c.index) - .collect(), - _ => vec![], + .collect::>() }; - let streamed_filter_columns = filter_columns(JoinSide::Left); - let buffered_filter_columns = filter_columns(JoinSide::Right); + let streamed_filter_columns = filter_columns(streamed_side); + let buffered_filter_columns = filter_columns(buffered_side); let mut streamed_gathered_columns = streamed_columns.clone(); let mut buffered_gathered_columns = buffered_columns.clone(); let filter = filter.map(|f| { @@ -799,11 +1207,11 @@ impl MaterializingSortMergeJoinStream { let unread = |emitted: &[usize], read: &[usize]| { emitted.iter().filter(|c| !read.contains(c)).count() }; - let filter_first = join_type == JoinType::Inner - && filter.is_some() - && unread(&streamed_columns, &streamed_filter_columns) - + unread(&buffered_columns, &buffered_filter_columns) - >= 2; + let filter_first = filter.is_some() + && (join_type != JoinType::Inner + || unread(&streamed_columns, &streamed_filter_columns) + + unread(&buffered_columns, &buffered_filter_columns) + >= 2); let filter_schema = if deferred_filtering && let Some(f) = &filter { let mut fields = Vec::with_capacity(f.schema().fields().len()); for (column_index, field) in @@ -980,7 +1388,6 @@ impl MaterializingSortMergeJoinStream { self.buffered_data.scanning_batch_idx, rows.start, len, - self.batch_size, ); self.buffered_data.scanning_advance_by(len); room -= len; @@ -1001,13 +1408,7 @@ impl MaterializingSortMergeJoinStream { self.join_type, JoinType::Left | JoinType::Right | JoinType::Full ) { - let scanning_batch_idx = if self.buffered_data.scanning_finished() { - None - } else { - Some(self.buffered_data.scanning_batch_idx) - }; - self.streamed_batch - .append_null_joined_pair(scanning_batch_idx, self.batch_size); + self.streamed_batch.append_null_joined_pair(); } self.buffered_data.scanning_reset(); } @@ -1262,8 +1663,10 @@ impl MaterializingSortMergeJoinStream { return needed; } // We need all batches that matched with streamed rows - for chunk in &self.streamed_batch.output_indices { - if let Some(idx) = chunk.buffered_batch_idx { + for run in &self.streamed_batch.runs { + if let Some(idx) = run.buffered_batch + && needed.last() != Some(&idx) + { needed.push(idx); } } @@ -1362,8 +1765,9 @@ impl MaterializingSortMergeJoinStream { self.freeze_streamed()?; self.join_metrics.input_batches().add(1); self.join_metrics.input_rows().add(batch.num_rows()); + let runs = take(&mut self.streamed_batch.runs); self.streamed_batch = - StreamedBatch::try_new(batch, &self.on_streamed)?; + StreamedBatch::try_new(batch, &self.on_streamed, runs)?; self.rebuild_streamed_buffered_cmp()?; // Every incoming streamed batch gets a unique id. self.streamed_batch_counter += 1; @@ -1760,242 +2164,137 @@ impl MaterializingSortMergeJoinStream { Ok(()) } - // Produces and stages record batch for all output indices found - // for current streamed batch and clears staged output indices. - // - // Null-joined chunks (no buffered match) are pushed immediately. - // Matched chunks are collected and processed together in - // freeze_streamed_matched() to amortize filter evaluation overhead. + /// Materializes the pairs of the streamed batch that are not frozen yet and + /// stages them for output. fn freeze_streamed(&mut self) -> Result<()> { - let mut matched_chunks: Vec = - Vec::with_capacity(self.streamed_batch.output_indices.len()); - let mut total_matched_rows: usize = 0; - - for chunk in self.streamed_batch.output_indices.iter_mut() { - let left_indices = - UInt64Array::try_new(take(&mut chunk.streamed_indices).into(), None)?; - if left_indices.is_empty() { - continue; - } - let right_indices = UInt64Array::try_new( - take(&mut chunk.buffered_indices).into(), - chunk.buffered_nulls.finish(), - )?; - - if chunk.buffered_batch_idx.is_none() { - let left_columns = materialize_columns( - &self.streamed_batch.batch, - &left_indices, - &self.streamed_columns, - )?; - let right_columns = create_unmatched_columns( - &self.buffered_schema, - &self.buffered_columns, - left_indices.len(), - ); - - let columns = if self.join_type != JoinType::Right { - [left_columns, right_columns].concat() - } else { - [right_columns, left_columns].concat() - }; - let batch = new_batch(&self.schema, columns, left_indices.len())?; - - // Null-joined rows (no buffered match) need no filter correction, - // but must flow through the same pipeline as matched rows to - // preserve output ordering. Use null metadata as a sentinel so - // get_corrected_filter_mask() passes them through unchanged. - if self.deferred_filtering { - self.joined_record_batches - .push_batch_with_null_metadata(batch, self.join_type); - } else { - self.joined_record_batches - .push_batch_without_metadata(batch); - } - continue; - } - - total_matched_rows += left_indices.len(); - matched_chunks.push(MatchedChunk { - buffered_batch_idx: chunk.buffered_batch_idx.unwrap(), - streamed_indices: left_indices, - buffered_indices: right_indices, - }); - } - - if !matched_chunks.is_empty() { - self.freeze_streamed_matched(&matched_chunks, total_matched_rows)?; - } - - self.streamed_batch.output_indices.clear(); - self.streamed_batch.num_output_rows = 0; - Ok(()) - } - - /// Materializes columns, evaluates the join filter, and pushes output - /// for all matched chunks in a single batch. This avoids per-chunk - /// RecordBatch construction and filter evaluation, which dominates - /// cost when keys are near-unique (1 row per chunk). - fn freeze_streamed_matched( - &mut self, - matched_chunks: &[MatchedChunk], - total_matched_rows: usize, - ) -> Result<()> { - debug_assert!( - !matched_chunks.is_empty(), - "caller guards this with an is_empty check before calling" - ); - debug_assert!( - matched_chunks.iter().all(|chunk| { - chunk.streamed_indices.len() == chunk.buffered_indices.len() - && chunk.buffered_batch_idx < self.buffered_data.batches.len() - }), - "left/right indices are built in pairs from the same streamed×buffered cross, \ - and batch_idx comes from iterating buffered_data.batches" - ); - debug_assert_eq!( - matched_chunks.iter().map(MatchedChunk::len).sum::(), - total_matched_rows, - "total_matched_rows is accumulated from the same chunks in freeze_streamed" - ); - - let combined_left_indices = - concat_indices(matched_chunks.iter().map(|c| &c.streamed_indices))?; - if self.freeze_inner_filtered( - matched_chunks, - total_matched_rows, - &combined_left_indices, - )? { + if self.streamed_batch.runs.is_empty() { return Ok(()); } - - let mut left_columns = materialize_columns( - &self.streamed_batch.batch, - &combined_left_indices, - &self.streamed_gathered_columns, - )?; - - let mut right_columns = if self.buffered_gathered_columns.is_empty() { - vec![] - } else { - self.buffered_rows(matched_chunks, total_matched_rows)? - .columns(&self.buffered_gathered_columns)? - }; - - // `get_filter_columns` takes arrays in join-side order. `left_columns` - // / `right_columns` here are streamed / buffered, and for a Right join - // the streamed side is the join's right input, hence the swap. - let filter_columns = if self.join_type == JoinType::Right { - get_filter_columns(self.filter.as_ref(), &right_columns, &left_columns)? - } else { - get_filter_columns(self.filter.as_ref(), &left_columns, &right_columns)? - }; - left_columns.truncate(self.streamed_columns.len()); - right_columns.truncate(self.buffered_columns.len()); - - let columns = if self.join_type != JoinType::Right { - [left_columns, right_columns].concat() - } else { - [right_columns, left_columns].concat() - }; - let output_batch = new_batch(&self.schema, columns, total_matched_rows)?; - - // A filter that reads no columns (e.g. a bound parameter or a volatile - // function) still has to be evaluated, so key on the filter itself. - if let Some(f) = &self.filter { - let schema = self.filter_schema.as_ref().unwrap_or_else(|| f.schema()); - let mask = - evaluate_join_filter(f, schema, filter_columns, total_matched_rows)?; - + let mut runs = take(&mut self.streamed_batch.runs); + let num_pairs = take(&mut self.streamed_batch.num_output_rows); + let frozen = self.freeze_runs(&runs, num_pairs); + // Keep the vector, whose capacity the next pairs reuse. + runs.clear(); + self.streamed_batch.runs = runs; + frozen + } + + /// Materializes the `num_pairs` pairs of `runs`, evaluates the join filter on + /// them, and stages the result for output. + fn freeze_runs(&mut self, runs: &[PairRun], num_pairs: usize) -> Result<()> { + let summary = RunsSummary::new(runs, num_pairs); + if summary.batches.is_none() { + // Streamed rows that no buffered row matches. They need no filter + // correction, but go through the deferred pipeline when there is one, + // which keeps the output order. + let streamed_columns = StreamedRows::new(runs, num_pairs, &summary) + .columns(&self.streamed_batch.batch, &self.streamed_columns)?; + let buffered_columns = create_unmatched_columns( + &self.buffered_schema, + &self.buffered_columns, + num_pairs, + ); + let batch = new_batch( + &self.schema, + self.join_columns(streamed_columns, buffered_columns), + num_pairs, + )?; if self.deferred_filtering { - self.joined_record_batches.push_batch_with_filter_metadata( - output_batch, - &combined_left_indices, - &mask, - self.streamed_batch_counter, - self.join_type, - ); + self.joined_record_batches + .push_batch_with_null_metadata(batch, self.join_type); } else { - let filtered_batch = filter_record_batch(&output_batch, &mask)?; self.joined_record_batches - .push_batch_without_metadata(filtered_batch); + .push_batch_without_metadata(batch); } + return Ok(()); + } - // Track which buffered rows had all filter matches fail, - // so full join can emit them as null-joined later. - if self.join_type == JoinType::Full { - let mut offset = 0usize; - for chunk in matched_chunks { - let right = &chunk.buffered_indices; - let chunk_len = right.len(); - let buffered_batch = - &mut self.buffered_data.batches[chunk.buffered_batch_idx]; - - for i in 0..chunk_len { - if right.is_null(i) { - continue; - } - let idx = right.value(i) as usize; - match buffered_batch.join_filter_status[idx] { - FilterState::SomePassed => {} - _ if mask.value(offset + i) => { - buffered_batch.join_filter_status[idx] = - FilterState::SomePassed; - } - _ => { - buffered_batch.join_filter_status[idx] = - FilterState::AllFailed; - } + let frozen = self.materialize_pairs(runs, num_pairs, &summary)?; + // Track which buffered rows had all filter matches fail, so full join can + // emit them as null-joined later. + if self.join_type == JoinType::Full + && let Some(passed) = &frozen.passed + { + let mut offset = 0; + for run in runs { + if let Some(batch) = run.buffered_batch { + let status = &mut self.buffered_data.batches[batch] + .join_filter_status[run.buffered_row..run.buffered_row + run.len]; + for (i, state) in status.iter_mut().enumerate() { + if *state != FilterState::SomePassed { + *state = if passed.value(offset + i) { + FilterState::SomePassed + } else { + FilterState::AllFailed + }; } } - offset += chunk_len; } - debug_assert_eq!( - offset, total_matched_rows, - "offset must advance through every chunk exactly once" - ); + offset += run.len; } - } else { - self.joined_record_batches - .push_batch_without_metadata(output_batch); } - + match frozen.metadata { + Some((streamed_rows, passed)) => { + self.joined_record_batches.push_batch_with_filter_metadata( + frozen.batch, + &streamed_rows, + &passed, + self.streamed_batch_counter, + self.join_type, + ) + } + None if frozen.batch.num_rows() > 0 => self + .joined_record_batches + .push_batch_without_metadata(frozen.batch), + None => {} + } Ok(()) } - /// Freezes the matched pairs of an Inner join with a filter, and returns - /// whether it did. The filter runs on just the columns it reads, and only the - /// pairs that pass are materialized, which saves most of the freeze when the - /// filter rejects most pairs of a many-to-many join. Outer joins keep a - /// rejected pair for the deferred pipeline, which may null-join its row. Only - /// an Inner join filters here, so its streamed side is the left input. + /// Materializes the `num_pairs` pairs of `runs`, of which some have a + /// buffered row, and evaluates the join filter on them. /// - /// Returns false, leaving the caller to materialize the batch whole and filter - /// it, when the join does not filter first (see [`Self::filter_first`]), or - /// when both sides' indices span ranges, as in a 1:1 join, so that the columns - /// materialize as slices. - fn freeze_inner_filtered( - &mut self, - matched_chunks: &[MatchedChunk], - total_matched_rows: usize, - streamed_indices: &UInt64Array, - ) -> Result { - let (true, Some(filter)) = (self.filter_first, &self.filter) else { - return Ok(false); + /// When the join filters first (see [`Self::filter_first`]), the filter runs + /// on just the columns it reads, and only the pairs that pass are + /// materialized. That saves most of the freeze when the filter rejects most + /// pairs of a many-to-many join. An outer join also keeps the first pair of + /// each streamed row whose pairs all fail, which the deferred filter + /// null-joins unless another freeze passes one of the row's pairs. + /// + /// Otherwise, and when both sides' rows form ranges, as in a 1:1 join, so + /// that the columns materialize as slices, it materializes every pair and + /// then filters them. + fn materialize_pairs( + &self, + runs: &[PairRun], + num_pairs: usize, + summary: &RunsSummary, + ) -> Result { + let streamed_rows = StreamedRows::new(runs, num_pairs, summary); + let buffered_rows = self.buffered_rows(runs, num_pairs, summary)?; + let filter = match &self.filter { + // An outer join keeps a pair of each streamed row, so filtering first + // saves nothing when every row has one pair. + Some(filter) + if self.filter_first + && !(streamed_rows.is_range() && buffered_rows.is_range()) + && (!self.deferred_filtering || num_pairs > runs.len()) => + { + filter + } + filter => { + return self.materialize_all_pairs( + filter.as_ref(), + &streamed_rows, + &buffered_rows, + num_pairs, + ); + } }; - let buffered_rows = self.buffered_rows(matched_chunks, total_matched_rows)?; - if let BufferedRows::Batch(_, buffered_indices) = &buffered_rows - && spans_range(streamed_indices) - && spans_range(buffered_indices) - { - return Ok(false); - } - let streamed_filter_arrays = materialize_columns( - &self.streamed_batch.batch, - streamed_indices, - &self.streamed_filter_columns, - )?; + let streamed_batch = &self.streamed_batch.batch; + let streamed_filter_arrays = + streamed_rows.columns(streamed_batch, &self.streamed_filter_columns)?; let buffered_filter_arrays = buffered_rows.columns(&self.buffered_filter_columns)?; let mut streamed_arrays = streamed_filter_arrays.iter().cloned(); @@ -2003,117 +2302,220 @@ impl MaterializingSortMergeJoinStream { let columns = filter .column_indices() .iter() - .map(|column_index| match column_index.side { - JoinSide::Left => streamed_arrays.next().ok_or_else(|| { - internal_datafusion_err!("missing streamed filter column") - }), - JoinSide::Right => buffered_arrays.next().ok_or_else(|| { - internal_datafusion_err!("missing buffered filter column") - }), - JoinSide::None => internal_err!("Unexpected JoinSide::None in filter"), + .map(|column_index| { + if column_index.side == self.streamed_side() { + streamed_arrays.next().ok_or_else(|| { + internal_datafusion_err!("missing streamed filter column") + }) + } else { + buffered_arrays.next().ok_or_else(|| { + internal_datafusion_err!("missing buffered filter column") + }) + } }) .collect::>>()?; - let passed = - evaluate_join_filter(filter, filter.schema(), columns, total_matched_rows)?; - let kept_rows = passed.true_count(); - if kept_rows == 0 { - return Ok(true); + let schema = self + .filter_schema + .as_ref() + .unwrap_or_else(|| filter.schema()); + let passed = evaluate_join_filter(filter, schema, columns, num_pairs)?; + let kept = if self.deferred_filtering { + passed_or_first_of_row(runs, &passed) + } else { + passed.clone() + }; + let num_kept = kept.true_count(); + if num_kept == 0 { + return Ok(FrozenPairs { + batch: RecordBatch::new_empty(Arc::clone(&self.schema)), + metadata: None, + passed: Some(passed), + }); } - // Filter the pairs once, and gather the columns that the filter did not - // read for the pairs that passed. - let predicate = FilterBuilder::new(&passed).optimize().build(); + // Filter the filter's columns once, and gather the other emitted columns + // for the pairs that are kept. + let predicate = FilterBuilder::new(&kept).optimize().build(); + let all_kept = num_kept == num_pairs; + let kept_streamed = if all_kept { + streamed_rows + } else { + streamed_rows.filter(&predicate, &kept)? + }; let streamed_columns = output_columns( &self.streamed_columns, &self.streamed_filter_columns, &streamed_filter_arrays, &predicate, - |others| { - let kept = as_uint64_array(&predicate.filter(streamed_indices)?)?.clone(); - materialize_columns(&self.streamed_batch.batch, &kept, others) - }, + |others| kept_streamed.columns(streamed_batch, others), )?; let buffered_columns = output_columns( &self.buffered_columns, &self.buffered_filter_columns, &buffered_filter_arrays, &predicate, - |others| buffered_rows.filter(&predicate, &passed)?.columns(others), + |others| { + if all_kept { + buffered_rows.columns(others) + } else { + buffered_rows.filter(&predicate, &kept)?.columns(others) + } + }, )?; - let output_batch = new_batch( + let batch = new_batch( &self.schema, - [streamed_columns, buffered_columns].concat(), - kept_rows, + self.join_columns(streamed_columns, buffered_columns), + num_kept, )?; - self.joined_record_batches - .push_batch_without_metadata(output_batch); - Ok(true) + let metadata = if self.deferred_filtering { + let passed = predicate.filter(&passed)?; + Some((kept_streamed.indices(), as_boolean_array(&passed)?.clone())) + } else { + None + }; + Ok(FrozenPairs { + batch, + metadata, + passed: Some(passed), + }) + } + + /// Materializes every pair, then evaluates `filter`, if any, on them. + fn materialize_all_pairs( + &self, + filter: Option<&JoinFilter>, + streamed_rows: &StreamedRows, + buffered_rows: &BufferedRows, + num_pairs: usize, + ) -> Result { + let mut streamed_columns = streamed_rows + .columns(&self.streamed_batch.batch, &self.streamed_gathered_columns)?; + let mut buffered_columns = + buffered_rows.columns(&self.buffered_gathered_columns)?; + + // `get_filter_columns` takes arrays in join-side order. For a Right join + // the streamed side is the join's right input, hence the swap. + let filter_columns = if self.join_type == JoinType::Right { + get_filter_columns(filter, &buffered_columns, &streamed_columns)? + } else { + get_filter_columns(filter, &streamed_columns, &buffered_columns)? + }; + streamed_columns.truncate(self.streamed_columns.len()); + buffered_columns.truncate(self.buffered_columns.len()); + let batch = new_batch( + &self.schema, + self.join_columns(streamed_columns, buffered_columns), + num_pairs, + )?; + + // A filter that reads no columns (e.g. a bound parameter or a volatile + // function) still has to be evaluated, so key on the filter itself. + let Some(filter) = filter else { + return Ok(FrozenPairs { + batch, + metadata: None, + passed: None, + }); + }; + let schema = self + .filter_schema + .as_ref() + .unwrap_or_else(|| filter.schema()); + let passed = evaluate_join_filter(filter, schema, filter_columns, num_pairs)?; + Ok(if self.deferred_filtering { + FrozenPairs { + batch, + metadata: Some((streamed_rows.indices(), passed.clone())), + passed: Some(passed), + } + } else { + FrozenPairs { + batch: filter_record_batch(&batch, &passed)?, + metadata: None, + passed: Some(passed), + } + }) + } + + /// The side of the join's filter that the streamed input is on. + fn streamed_side(&self) -> JoinSide { + if self.join_type == JoinType::Right { + JoinSide::Right + } else { + JoinSide::Left + } } - /// Where the buffered rows of all matched chunks are: one buffered batch with - /// the chunks' indices concatenated, or several batches with a source and a - /// row for `interleave` per pair. A null-row sentinel at source index 0 - /// handles null right indices (unmatched streamed rows). + /// The output columns, given the streamed and the buffered ones. + fn join_columns( + &self, + streamed_columns: Vec, + buffered_columns: Vec, + ) -> Vec { + if self.join_type == JoinType::Right { + [buffered_columns, streamed_columns].concat() + } else { + [streamed_columns, buffered_columns].concat() + } + } + + /// Where the buffered rows of `runs`, which hold `num_pairs` pairs, are: a + /// range of one batch, ranges of several batches when the runs are long, + /// and otherwise a row per pair, of one batch or, with a source for + /// `interleave`, of several. Nulls stand for pairs without a buffered row. fn buffered_rows( &self, - matched_chunks: &[MatchedChunk], - total_matched_rows: usize, + runs: &[PairRun], + num_pairs: usize, + summary: &RunsSummary, ) -> Result> { - let first_batch_idx = matched_chunks[0].buffered_batch_idx; - let single_source = matched_chunks - .iter() - .all(|c| c.buffered_batch_idx == first_batch_idx); - - if single_source { - return Ok(BufferedRows::Batch( - self.buffered_data.batches[first_batch_idx].in_memory()?, - concat_indices(matched_chunks.iter().map(|c| &c.buffered_indices))?, + let RunsSummary { + num_ranges, + batches: Some((min_batch_idx, max_batch_idx)), + nulls, + .. + } = *summary + else { + return Ok(BufferedRows::Nulls(&self.buffered_schema, num_pairs)); + }; + if num_ranges == 1 { + let start = runs[0].buffered_row; + return Ok(BufferedRows::Range( + self.buffered_data.batches[min_batch_idx].in_memory()?, + start..start + num_pairs, )); } - // Multiple source batches: map each buffered_batch_idx to a - // contiguous source index. A null sentinel array is prepended as - // source 0 only when some right index is actually null (an - // unmatched streamed row inside an otherwise matched chunk); - // `interleave` walks a null buffer for *every* output row as soon as - // any input is nullable, so an always-present sentinel would tax the - // common all-matched case. - let needs_null_sentinel = matched_chunks - .iter() - .any(|c| c.buffered_indices.null_count() > 0); - let source_offset = usize::from(needs_null_sentinel); - - // Map each distinct `buffered_batch_idx` to a contiguous source - // index for `interleave`. The keys are not opaque: they are - // positions in `self.buffered_data.batches`, so the key space is - // dense and bounded by the deque length. A direct-addressed table - // over `min..=max` resolves every chunk in O(1), with no hashing and - // no key comparison. + // Map each distinct buffered batch to a contiguous source index for + // `interleave` or the copied ranges. The keys are not opaque: they are + // positions in `self.buffered_data.batches`, so the key space is dense + // and bounded by the deque length. A direct-addressed table over + // `min..=max` resolves every run in O(1), with no hashing and no key + // comparison. // // The keys a freeze sees are usually a contiguous run, since // `scanning_advance_by` walks the deque in order. The exception is a - // freeze that straddles a `scanning_reset`: its window wraps (the - // tail of one streamed row's pass, then the head of the next) and - // leaves a gap, so the table is sized by the whole group rather than - // by the sources present. That costs O(group) for O(batch_size) of - // work -- but only once per pass, against the O(group) of useful - // work the rest of the pass does, so it stays O(1) amortized per - // pair. Measured over a 524288-batch group at `batch_size` 8192, - // a full pass costs 1.17 ms here against 11.25 ms for the hashmap. + // freeze that straddles a `scanning_reset`: its window wraps (the tail of + // one streamed row's pass, then the head of the next) and leaves a gap, + // so the table is sized by the whole group rather than by the sources + // present. That costs O(group) for O(batch_size) of work -- but only once + // per pass, against the O(group) of useful work the rest of the pass + // does, so it stays O(1) amortized per pair. Measured over a + // 524288-batch group at `batch_size` 8192, a full pass costs 1.17 ms + // here against 11.25 ms for a hashmap. // - // A linear `position()` scan over `source_batches` is not enough - // here, even though a freeze holds at most `batch_size` pairs. - // `pair_streamed_row_with_group` restarts the buffered scan at batch - // 0 for *every* streamed row of the key group (`scanning_reset`), so - // the chunk sequence cycles `0,1,..,S-1,0,1,..` and the chunk count - // is not bounded by the distinct-source count `S`. The scan is then - // O(chunks * S), and nothing bounds `S`: `SortMergeJoinExec` accepts - // arbitrary `ExecutionPlan` children, so one emitting tiny batches - // pushes `S` towards `batch_size`. + // A linear `position()` scan over `source_batches` is not enough here, + // even though a freeze holds at most `batch_size` pairs. + // `pair_streamed_row_with_group` restarts the buffered scan at batch 0 + // for *every* streamed row of the key group (`scanning_reset`), so the + // run sequence cycles `0,1,..,S-1,0,1,..` and the run count is not + // bounded by the distinct-source count `S`. The scan is then + // O(runs * S), and nothing bounds `S`: `SortMergeJoinExec` accepts + // arbitrary `ExecutionPlan` children, so one emitting tiny batches pushes + // `S` towards `batch_size`. // - // Measured over 8192 rows in 2048 chunks, against a - // `HashMap` built in one pass and read back in a - // second: + // Measured over 8192 rows in 2048 runs, against a + // `HashMap` built in one pass and read back in a second: // // distinct sources | hashmap | linear scan | direct table // -----------------+-----------+---------------+-------------- @@ -2124,24 +2526,20 @@ impl MaterializingSortMergeJoinStream { // 8192 | 293.3 us | 8347.6 us | 16.9 us // // The last row is the degenerate shape a one-row-per-batch child - // produces: 8192 chunks of a single row each, all from distinct - // buffered batches. 8.3 ms of index construction, in one freeze. + // produces: 8192 runs of a single row each, all from distinct buffered + // batches. 8.3 ms of index construction, in one freeze. // - // The table ties the scan where the scan is at its best (a handful - // of sources): both stay in L1 and neither hashes, whereas - // `std::collections::HashMap` uses SipHash-1-3 and pays several ns - // of serial latency before each probe begins. Unlike the scan, it - // stays flat. `source_batches` has to be built regardless - // (`source_data` is gathered from it), so the table is the only - // added state, and it is transient: sized to the span this freeze - // touches rather than held across freezes. - let (min_batch_idx, max_batch_idx) = matched_chunks - .iter() - .fold((usize::MAX, 0usize), |(lo, hi), c| { - (lo.min(c.buffered_batch_idx), hi.max(c.buffered_batch_idx)) - }); - // Every key indexes the live buffered deque -- this is what keeps - // the key space dense, and what makes `source_data` below safe. + // The table ties the scan where the scan is at its best (a handful of + // sources): both stay in L1 and neither hashes, whereas + // `std::collections::HashMap` uses SipHash-1-3 and pays several ns of + // serial latency before each probe begins. Unlike the scan, it stays + // flat. `source_batches` has to be built regardless (`source_data` is + // gathered from it), so the table is the only added state, and it is + // transient: sized to the span this freeze touches rather than held + // across freezes. + // + // Every key indexes the live buffered deque -- this is what keeps the key + // space dense, and what makes `source_data` below safe. debug_assert!( max_batch_idx < self.buffered_data.batches.len(), "buffered batch index {max_batch_idx} outside the buffered deque" @@ -2149,44 +2547,46 @@ impl MaterializingSortMergeJoinStream { // Sentinel for "no source index assigned to this buffered batch yet". const UNSEEN: usize = usize::MAX; let mut source_of_batch = vec![UNSEEN; max_batch_idx - min_batch_idx + 1]; - let mut source_batches: Vec = - Vec::with_capacity(matched_chunks.len().min(source_of_batch.len())); - let mut interleave_indices: Vec<(usize, usize)> = - Vec::with_capacity(total_matched_rows); - for chunk in matched_chunks.iter() { - let batch_idx = chunk.buffered_batch_idx; - let right = &chunk.buffered_indices; - let slot = &mut source_of_batch[batch_idx - min_batch_idx]; - if *slot == UNSEEN { - *slot = source_batches.len(); - source_batches.push(batch_idx); - } - let source = *slot + source_offset; - if right.null_count() == 0 { - // Hot path: no per-row null check, and `values()` avoids - // the bounds check `value(i)` would repeat. - interleave_indices - .extend(right.values().iter().map(|&idx| (source, idx as usize))); - } else { - for i in 0..right.len() { - if right.is_null(i) { - interleave_indices.push((0, 0)); - } else { - interleave_indices.push((source, right.value(i) as usize)); - } + let mut source_batches: Vec = vec![]; + if min_batch_idx == max_batch_idx { + source_of_batch[0] = 0; + source_batches.push(min_batch_idx); + } else { + for batch_idx in runs.iter().filter_map(|run| run.buffered_batch) { + let slot = &mut source_of_batch[batch_idx - min_batch_idx]; + if *slot == UNSEEN { + *slot = source_batches.len(); + source_batches.push(batch_idx); } } } - // Read each source batch once (spilled batches require disk I/O). - let source_data = source_batches + let batches = source_batches .iter() .map(|&idx| self.buffered_data.batches[idx].in_memory()) - .collect::>()?; - Ok(BufferedRows::Interleaved { - batches: source_data, - nulls: needs_null_sentinel, - indices: interleave_indices, + .collect::>>()?; + let source = |range: CopiedRange| CopiedRange { + source: range + .source + .map(|batch_idx| source_of_batch[batch_idx - min_batch_idx]), + ..range + }; + Ok(if num_pairs >= num_ranges * MIN_COPIED_RUN_LEN { + BufferedRows::Ranges { + batches, + ranges: buffered_ranges(runs).map(source).collect(), + num_rows: num_pairs, + } + } else { + // Gathering row by row needs no merged ranges. + let ranges = runs.iter().map(|run| { + source(CopiedRange { + source: run.buffered_batch, + start: run.buffered_row, + len: run.len, + }) + }); + gather_ranges(batches, ranges, nulls, num_pairs) }) } @@ -2370,12 +2770,16 @@ fn produce_buffered_null_batch( /// This allows replacing an O(n) `take` with an O(1) `slice`. #[inline] fn is_contiguous_range(indices: &UInt64Array) -> Option> { - if !spans_range(indices) { + if indices.is_empty() || indices.null_count() > 0 { return None; } let values = indices.values(); let start = values[0]; let len = values.len() as u64; + // Quick rejection: if last element doesn't match expected, not contiguous + if values[values.len() - 1] != start + len - 1 { + return None; + } // Verify every element is sequential (handles duplicates and gaps) for i in 1..values.len() { if values[i] != start + i as u64 { @@ -2385,16 +2789,6 @@ fn is_contiguous_range(indices: &UInt64Array) -> Option> { Some(start as usize..(start + len) as usize) } -/// Whether `indices` may form a range, judging by their ends only. A freeze uses -/// it to choose its path, and the path checks the range before it slices. -fn spans_range(indices: &UInt64Array) -> bool { - let values = indices.values(); - !values.is_empty() - && indices.null_count() == 0 - && values[values.len() - 1].checked_sub(values[0]) - == Some(values.len() as u64 - 1) -} - /// One side's emitted `columns` for the pairs that passed the filter. The /// filter's columns are already gathered for every pair in `filter_arrays`, so /// `predicate` filters them, and `gather` materializes the other columns. @@ -2427,17 +2821,6 @@ fn output_columns( .collect() } -/// Concatenates the index arrays of several chunks into one. -fn concat_indices<'a>( - indices: impl Iterator, -) -> Result { - let arrays: Vec<&dyn Array> = indices.map(|a| a as &dyn Array).collect(); - match arrays.as_slice() { - [single] => Ok(as_uint64_array(*single)?.clone()), - _ => Ok(as_uint64_array(&compute::concat(&arrays)?)?.clone()), - } -} - /// Evaluates `filter` over `num_rows` pairs whose `columns` follow the filter's /// intermediate `schema`, and returns which pairs pass. A NULL result does not /// pass, as in SQL. 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..38932bcc31edb 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -33,10 +33,10 @@ use crate::{ }; use arrow::array::{ ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, DictionaryArray, - FixedSizeBinaryArray, Int32Array, RecordBatch, UInt64Array, + FixedSizeBinaryArray, Int8Array, Int32Array, RecordBatch, StringArray, UInt64Array, }; use arrow::compute::{BatchCoalescer, SortOptions, filter_record_batch}; -use arrow::datatypes::{DataType, Field, Int32Type, Schema}; +use arrow::datatypes::{DataType, Field, Int8Type, Int32Type, Schema}; use arrow_ord::sort::SortColumn; use arrow_schema::SchemaRef; use bytes::Bytes; @@ -5395,9 +5395,9 @@ async fn join_filtered_with_multiple_buffered_batches() -> Result<()> { /// `pair_streamed_row_with_group` walks the group from buffered batch 0 for /// *every* streamed row (`scanning_reset`), and freezes whenever `batch_size` /// pairs have accumulated -- which happens mid-scan when `batch_size` is not a -/// multiple of the group size. So one `freeze_streamed()` can see chunks whose -/// `buffered_batch_idx` wraps (`.. 4, 5, 0, 1 ..`) or never reaches 0 at all, -/// rather than a single ascending run. `buffered_rows` maps those +/// multiple of the group size. So one `freeze_streamed()` can see runs whose +/// `buffered_batch` wraps (`.. 4, 5, 0, 1 ..`) or never reaches 0 at all, +/// rather than a single ascending sequence. `buffered_rows` maps those /// indices to `interleave` source slots, so it must not assume either. /// /// 6 one-row buffered batches x 2 streamed rows at `batch_size` 5 produces @@ -5537,12 +5537,95 @@ async fn join_inner_group_spans_buffered_and_output_batches() -> Result<()> { Ok(()) } +/// Runs of buffered rows that continue each other are copied as one range, but +/// only within one buffered batch. Key 1's group starts at row 32 of one +/// buffered batch and ends at row 32 of the next, so the first streamed row's +/// run in the second batch ends at the row where the second streamed row's run +/// starts in the first batch. +#[tokio::test] +async fn join_runs_continue_only_within_a_buffered_batch() -> Result<()> { + let left = build_table( + ("a1", &vec![1, 1]), + ("b1", &vec![0, 0]), + ("c1", &vec![10, 11]), + ); + let batch = |first_key: i32, first_c2: i32| { + build_table_i32( + ("a2", &(0..64).map(|i| first_key + i / 32).collect()), + ("b2", &vec![0; 64]), + ("c2", &(first_c2..first_c2 + 64).collect()), + ) + }; + let right = build_table_from_batches(vec![batch(0, 0), batch(1, 64)]); + let on = vec![( + Arc::new(Column::new_with_schema("a1", &left.schema())?) as _, + Arc::new(Column::new_with_schema("a2", &right.schema())?) as _, + )]; + let (_, batches) = join_collect(left, right, on, Inner).await?; + let output = arrow::compute::concat_batches(&batches[0].schema(), &batches)?; + let c2 = output + .column(5) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + c2.values().to_vec(), + (32..96).chain(32..96).collect::>() + ); + Ok(()) +} + +/// A dictionary column copied from several buffered batches would concatenate +/// their dictionaries, here 200 values for `Int8` keys, so it is gathered with +/// `interleave`, which merges them. +#[tokio::test] +async fn join_dictionary_column_of_several_buffered_batches() -> Result<()> { + let left = build_table( + ("a1", &vec![1, 1]), + ("b1", &vec![0, 0]), + ("c1", &vec![10, 11]), + ); + let right_schema = Arc::new(Schema::new(vec![ + Field::new("a2", DataType::Int32, false), + Field::new_dictionary("d2", DataType::Int8, DataType::Utf8, false), + ])); + let batch = |name: &str| { + let values: Vec = (0..100).map(|i| format!("{name}{i}")).collect(); + let dictionary = DictionaryArray::::try_new( + Int8Array::from_iter_values(0..64), + Arc::new(StringArray::from(values)), + )?; + RecordBatch::try_new( + Arc::clone(&right_schema), + vec![ + Arc::new(Int32Array::from(vec![1; 64])), + Arc::new(dictionary), + ], + ) + }; + let right = build_table_from_batches(vec![batch("x")?, batch("y")?]); + let on = vec![( + Arc::new(Column::new_with_schema("a1", &left.schema())?) as _, + Arc::new(Column::new_with_schema("a2", &right.schema())?) as _, + )]; + let (_, batches) = join_collect(left, right, on, Inner).await?; + let output = arrow::compute::concat_batches(&batches[0].schema(), &batches)?; + let d2 = arrow::compute::cast(output.column(4), &DataType::Utf8)?; + let d2 = d2.as_any().downcast_ref::().unwrap(); + let expected: Vec = ["x", "y", "x", "y"] + .iter() + .flat_map(|name| (0..64).map(move |i| format!("{name}{i}"))) + .collect(); + assert_eq!(d2.iter().flatten().collect::>(), expected); + Ok(()) +} + /// A wrapped multi-source freeze that also carries a null buffered index. /// /// `buffered_rows` has two independent offsets in play on the /// interleave path: `batch_idx - min_batch_idx` addresses the source table, -/// and `+ source_offset` shifts past the null sentinel that occupies -/// `interleave` slot 0. Only their combination is interesting, and the two +/// and `+ offset` in `gather_ranges` shifts past the null sentinel that +/// occupies `interleave` slot 0. Only their combination is interesting, and the two /// halves are awkward to get into the same freeze: `freeze_dequeuing_buffered` /// freezes before popping consumed batches, so a null-joined streamed row /// normally lands in its own single-source freeze. @@ -5551,11 +5634,11 @@ async fn join_inner_group_spans_buffered_and_output_batches() -> Result<()> { /// a key group spanning several batches, with two streamed rows matching that /// group so the scan wraps: /// -/// chunk sequence [0, 1, 2, 0, 1, 2], chunk 0 carrying the null +/// run sequence [null, 0, 1, 2, 0, 1, 2] /// /// Streamed key 5 finds no buffered match, so `null_join_streamed_row` appends -/// a null pair at scan position 0; the two streamed 10s then each re-walk -/// batches 0..2 (`scanning_reset`), wrapping inside the same freeze. +/// a null-joined pair; the two streamed 10s then each re-walk batches 0..2 +/// (`scanning_reset`), wrapping inside the same freeze. #[tokio::test] async fn join_wrapped_multi_source_freeze_with_null_buffered_index() -> Result<()> { let left_schema = Arc::new(Schema::new(vec![ From 9602b34e8d55f570d66d2a26ded470d3d0e1a365 Mon Sep 17 00:00:00 2001 From: comphead Date: Tue, 1 Dec 2026 12:34:04 -0800 Subject: [PATCH 3/3] perf: drop unused buffered columns of a sort-merge join on arrival Buffered batches kept every input column while they waited for their key group, and spilled them all. Once its join keys are computed, a buffered batch now keeps only the columns that the join emits or its filter reads, so its reservation and spill files no longer include, for example, a join key that the projection drops. --- .../sort_merge_join/materializing_stream.rs | 54 ++++++++++++++++--- .../src/joins/sort_merge_join/tests.rs | 36 +++++++++---- .../physical-plan/src/spill/spill_manager.rs | 6 +++ 3 files changed, 79 insertions(+), 17 deletions(-) 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 50ce96fff2529..8e4f42c2c1632 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 @@ -788,12 +788,19 @@ impl BufferedBatch { } } + /// The buffered `batch`, reduced to the columns of `projection`, if any, + /// once its join keys are computed. fn try_new( batch: RecordBatch, range: Range, on_column: &[PhysicalExprRef], + projection: Option<&[usize]>, ) -> Result { let join_arrays = join_arrays(&batch, on_column)?; + let batch = match projection { + Some(projection) => batch.project(projection)?, + None => batch, + }; // Estimation is calculated as // inner batch size @@ -887,6 +894,9 @@ pub(super) struct MaterializingSortMergeJoinStream { /// filter's order (see [`Self::materialize_pairs`]). pub streamed_filter_columns: Vec, pub buffered_filter_columns: Vec, + /// The buffered input's columns that buffered batches keep, when they drop + /// some. The buffered column indices above address the kept columns. + pub buffered_projection: Option>, /// Whether this join filters the pairs of a freeze before it materializes /// them (see [`Self::materialize_pairs`]). An outer join always does, which /// also spares the deferred filter the pairs that fail. @@ -1133,7 +1143,7 @@ impl MaterializingSortMergeJoinStream { pub fn try_new( schema: SchemaRef, streamed_columns: Vec, - buffered_columns: Vec, + mut buffered_columns: Vec, sort_options: Vec, null_equality: NullEquality, streamed: SendableRecordBatchStream, @@ -1145,11 +1155,11 @@ impl MaterializingSortMergeJoinStream { batch_size: usize, join_metrics: SortMergeJoinMetrics, reservation: MemoryReservation, - spill_manager: SpillManager, + mut spill_manager: SpillManager, runtime_env: Arc, ) -> Result { let streamed_schema = streamed.schema(); - let buffered_schema = buffered.schema(); + let mut buffered_schema = buffered.schema(); debug_assert!( matches!( join_type, @@ -1174,7 +1184,7 @@ impl MaterializingSortMergeJoinStream { .collect::>() }; let streamed_filter_columns = filter_columns(streamed_side); - let buffered_filter_columns = filter_columns(buffered_side); + let mut buffered_filter_columns = filter_columns(buffered_side); let mut streamed_gathered_columns = streamed_columns.clone(); let mut buffered_gathered_columns = buffered_columns.clone(); let filter = filter.map(|f| { @@ -1212,6 +1222,25 @@ impl MaterializingSortMergeJoinStream { || unread(&streamed_columns, &streamed_filter_columns) + unread(&buffered_columns, &buffered_filter_columns) >= 2); + // Buffered batches keep only the gathered columns, in their order, once + // their join keys are computed, so the columns are renumbered. + let buffered_projection = (!buffered_gathered_columns + .iter() + .copied() + .eq(0..buffered_schema.fields().len())) + .then(|| { + let projection = take(&mut buffered_gathered_columns); + let position = |c: &usize| projection.iter().position(|p| p == c).unwrap(); + buffered_filter_columns = + buffered_filter_columns.iter().map(position).collect(); + buffered_columns = (0..buffered_columns.len()).collect(); + buffered_gathered_columns = (0..projection.len()).collect(); + projection + }); + if let Some(projection) = &buffered_projection { + buffered_schema = Arc::new(buffered_schema.project(projection)?); + spill_manager = spill_manager.with_schema(Arc::clone(&buffered_schema)); + } let filter_schema = if deferred_filtering && let Some(f) = &filter { let mut fields = Vec::with_capacity(f.schema().fields().len()); for (column_index, field) in @@ -1253,6 +1282,7 @@ impl MaterializingSortMergeJoinStream { buffered_gathered_columns, streamed_filter_columns, buffered_filter_columns, + buffered_projection, filter_first, filter, joined_record_batches: JoinedRecordBatches { @@ -1961,8 +1991,12 @@ impl MaterializingSortMergeJoinStream { self.join_metrics.input_rows().add(batch.num_rows()); if batch.num_rows() > 0 { - let buffered_batch = - BufferedBatch::try_new(batch, 0..1, &self.on_buffered)?; + let buffered_batch = BufferedBatch::try_new( + batch, + 0..1, + &self.on_buffered, + self.buffered_projection.as_deref(), + )?; self.allocate_reservation(buffered_batch)?; self.streamed_buffered_cmp = None; return Ok(true); @@ -2016,8 +2050,12 @@ impl MaterializingSortMergeJoinStream { self.join_metrics.input_batches().add(1); self.join_metrics.input_rows().add(batch.num_rows()); if batch.num_rows() > 0 { - let buffered_batch = - BufferedBatch::try_new(batch, 0..0, &self.on_buffered)?; + let buffered_batch = BufferedBatch::try_new( + batch, + 0..0, + &self.on_buffered, + self.buffered_projection.as_deref(), + )?; self.allocate_reservation(buffered_batch)?; self.buffered_equality_cmp = None; } 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 38932bcc31edb..c7e369697c539 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -8567,6 +8567,8 @@ fn early_filtering_inputs() /// join without it followed by the projection, for every join type that /// materializes pairs, with and without a filter, and for projections that /// reorder the columns, repeat one, drop the filter's columns, or keep none. +/// The projections drop the buffered key, so the buffered batches that spill +/// are reduced to the columns that the join emits or the filter reads. #[tokio::test] async fn join_with_projection_matches_projected_join() -> Result<()> { let ((left_batches, left_schema), (right_batches, right_schema)) = @@ -8578,6 +8580,12 @@ async fn join_with_projection_matches_projected_join() -> Result<()> { ]; // Columns of the join schema `a1, b1, c1, a2, b2, c2` let projections: [&[usize]; 4] = [&[5, 1], &[2, 2, 4], &[0, 3], &[]]; + let spilling = RuntimeEnvBuilder::new() + .with_memory_limit(100, 1.0) + .with_disk_manager_builder( + DiskManagerBuilder::default().with_mode(DiskManagerMode::OsTmpDirectory), + ) + .build_arc()?; for join_type in [Inner, Left, Right, Full] { for filter in &filters { let join = SortMergeJoinExec::try_new( @@ -8605,17 +8613,27 @@ async fn join_with_projection_matches_projected_join() -> Result<()> { ], "which sides of the {join_type} join emit rows without a match" ); + let spilling_ctx = Arc::new( + TaskContext::default() + .with_session_config( + SessionConfig::new().with_batch_size(batch_size), + ) + .with_runtime(Arc::clone(&spilling)), + ); for projection in projections { let projected = join.with_projection(Some(projection.to_vec()))?; - let output = - common::collect(projected.execute(0, Arc::clone(&task_ctx))?) - .await?; - assert_eq!( - arrow::compute::concat_batches(&projected.schema(), &output)?, - unprojected.project(projection)?, - "{join_type} join, filter {filter:?}, projection {projection:?}, \ - batch_size {batch_size}" - ); + for ctx in [&task_ctx, &spilling_ctx] { + let output = + common::collect(projected.execute(0, Arc::clone(ctx))?) + .await?; + assert_eq!( + arrow::compute::concat_batches(&projected.schema(), &output)?, + unprojected.project(projection)?, + "{join_type} join, filter {filter:?}, projection \ + {projection:?}, batch_size {batch_size}" + ); + } + assert!(projected.metrics().unwrap().spill_count().unwrap() > 0); } } } diff --git a/datafusion/physical-plan/src/spill/spill_manager.rs b/datafusion/physical-plan/src/spill/spill_manager.rs index 57e819b1408c4..652c6e0130046 100644 --- a/datafusion/physical-plan/src/spill/spill_manager.rs +++ b/datafusion/physical-plan/src/spill/spill_manager.rs @@ -58,6 +58,12 @@ impl SpillManager { self } + /// Returns this manager for batches of `schema` instead. + pub(crate) fn with_schema(mut self, schema: SchemaRef) -> Self { + self.schema = schema; + self + } + /// Returns the schema for batches managed by this SpillManager pub fn schema(&self) -> &SchemaRef { &self.schema