From 64f93ad257de3845eeccd398146e393b32bb980b Mon Sep 17 00:00:00 2001 From: comphead Date: Tue, 1 Dec 2026 12:31:25 -0800 Subject: [PATCH 01/10] 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 02/10] 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 03/10] 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 From b255dd53f3ba54044a40ae340b4315a03dee39f0 Mon Sep 17 00:00:00 2001 From: comphead Date: Wed, 2 Dec 2026 09:36:56 -0800 Subject: [PATCH 04/10] perf: copy primitive and byte ranges of a sort-merge join directly A freeze that copies runs of buffered rows built a `MutableArrayData` for each column, which converted the column of every source batch with `to_data()` and boxed an extend closure for each. With 64-row buffered batches, that setup took about 6% of the CPU in a Linux profile. Primitive and byte arrays now copy their value ranges and validity directly. Other types keep `MutableArrayData`. --- .../sort_merge_join/materializing_stream.rs | 146 ++++++++++++++++-- .../src/joins/sort_merge_join/tests.rs | 59 +++++++ 2 files changed, 195 insertions(+), 10 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 8e4f42c2c1632..a275b81bbf533 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 @@ -29,12 +29,16 @@ use crate::spill::spill_manager::SpillManager; use crate::stream::{EmptyRecordBatchStream, ObservedStream, RecordBatchStreamAdapter}; use crate::{PhysicalExpr, SendableRecordBatchStream}; -use arrow::array::{types::UInt64Type, *}; -use arrow::buffer::NullBuffer; +use arrow::array::types::{ + BinaryType, ByteArrayType, LargeBinaryType, LargeUtf8Type, UInt64Type, Utf8Type, +}; +use arrow::array::*; +use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; use arrow::compute::{ self, BatchCoalescer, FilterBuilder, FilterPredicate, SortOptions, concat_batches, filter_record_batch, interleave, }; +use arrow::datatypes::ArrowNativeType; use arrow::datatypes::{DataType, Schema, SchemaRef}; use arrow::record_batch::RecordBatchOptions; use datafusion_common::cast::{as_boolean_array, as_uint64_array}; @@ -457,25 +461,147 @@ impl BufferedRows<'_> { } /// Copies `ranges` of the `column` of `batches` into one array of `num_rows`. +/// Primitive and byte arrays are copied from their buffers, and other types +/// with `MutableArrayData`. 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)?; + let arrays: Vec<&ArrayRef> = batches.iter().map(|b| b.column(column)).collect(); + let array = arrays[0]; + downcast_primitive_array!( + array => Ok(copy_primitive_ranges(array, &arrays, ranges, num_rows)), + DataType::Utf8 => copy_byte_ranges::(&arrays, ranges, num_rows), + DataType::LargeUtf8 => copy_byte_ranges::(&arrays, ranges, num_rows), + DataType::Binary => copy_byte_ranges::(&arrays, ranges, num_rows), + DataType::LargeBinary => { + copy_byte_ranges::(&arrays, ranges, num_rows) + } + _ => { + let data: Vec = arrays.iter().map(|a| a.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)? + } + None => copied.try_extend_nulls(range.len)?, + } + } + Ok(make_array(copied.freeze())) + } + ) +} + +/// [`copy_ranges`] for the primitive `arrays`, of which `first` is the first. +fn copy_primitive_ranges( + first: &PrimitiveArray, + arrays: &[&ArrayRef], + ranges: &[CopiedRange], + num_rows: usize, +) -> ArrayRef { + let arrays: Vec<&PrimitiveArray> = + arrays.iter().map(|a| a.as_primitive::()).collect(); + let mut values = Vec::with_capacity(num_rows); for range in ranges { match range.source { - Some(source) => { - copied.try_extend(source, range.start, range.start + range.len)? + Some(source) => values.extend_from_slice( + &arrays[source].values()[range.start..range.start + range.len], + ), + None => values.resize(values.len() + range.len, T::Native::default()), + } + } + let nulls: Vec<_> = arrays.iter().map(|a| a.nulls()).collect(); + Arc::new( + PrimitiveArray::::new( + values.into(), + copy_range_nulls(&nulls, ranges, num_rows), + ) + .with_data_type(first.data_type().clone()), + ) +} + +/// [`copy_ranges`] for the byte `arrays`, which copies whole values and rebases +/// their offsets. +fn copy_byte_ranges( + arrays: &[&ArrayRef], + ranges: &[CopiedRange], + num_rows: usize, +) -> Result { + let arrays: Vec<&GenericByteArray> = + arrays.iter().map(|a| a.as_bytes::()).collect(); + let value_offsets = |range: &CopiedRange| { + range.source.map(|source| { + &arrays[source].value_offsets()[range.start..=range.start + range.len] + }) + }; + let num_bytes: usize = ranges + .iter() + .filter_map(value_offsets) + .map(|offsets| (offsets[offsets.len() - 1] - offsets[0]).as_usize()) + .sum(); + if T::Offset::from_usize(num_bytes).is_none() { + return exec_err!("{num_bytes} bytes overflow the offsets of {}", T::DATA_TYPE); + } + let mut values: Vec = Vec::with_capacity(num_bytes); + let mut offsets: Vec = Vec::with_capacity(num_rows + 1); + offsets.push(T::Offset::default()); + let mut end = T::Offset::default(); + for range in ranges { + match (range.source, value_offsets(range)) { + (Some(source), Some(source_offsets)) => { + let base = source_offsets[0]; + offsets.extend(source_offsets[1..].iter().map(|&o| end + (o - base))); + let last = source_offsets[range.len]; + values.extend_from_slice( + &arrays[source].value_data()[base.as_usize()..last.as_usize()], + ); + end += last - base; + } + _ => offsets.resize(offsets.len() + range.len, end), + } + } + let nulls: Vec<_> = arrays.iter().map(|a| a.nulls()).collect(); + let nulls = copy_range_nulls(&nulls, ranges, num_rows); + // SAFETY: the offsets start at 0 and grow by the length of each copied + // value, up to `num_bytes`, which fits the offset type. The values are whole + // values of arrays of the same type, so they are valid (e.g. UTF-8). + let offsets = unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) }; + Ok(Arc::new(unsafe { + GenericByteArray::::new_unchecked(offsets, values.into(), nulls) + })) +} + +/// The validity of the rows of `ranges` from sources with the validity `nulls`, +/// in which a range without a source is null, or `None` if every row is valid. +fn copy_range_nulls( + nulls: &[Option<&NullBuffer>], + ranges: &[CopiedRange], + num_rows: usize, +) -> Option { + let source_nulls = |range: &CopiedRange| range.source.map(|s| nulls[s]); + if ranges.iter().all(|range| { + source_nulls(range).is_some_and(|n| n.is_none_or(|n| n.null_count() == 0)) + }) { + return None; + } + let mut validity = BooleanBufferBuilder::new(num_rows); + for range in ranges { + match source_nulls(range) { + None => validity.append_n(range.len, false), + Some(None) => validity.append_n(range.len, true), + Some(Some(source)) => { + let bits = source.inner(); + let start = bits.offset() + range.start; + validity.append_packed_range(start..start + range.len, bits.values()); } - None => copied.try_extend_nulls(range.len)?, } } - Ok(make_array(copied.freeze())) + Some(NullBuffer::new(validity.finish())) } /// The rows of `ranges` at which `mask` is set, as ranges. 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 c7e369697c539..2c621c9303a3f 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -34,6 +34,7 @@ use crate::{ use arrow::array::{ ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, DictionaryArray, FixedSizeBinaryArray, Int8Array, Int32Array, RecordBatch, StringArray, UInt64Array, + new_null_array, }; use arrow::compute::{BatchCoalescer, SortOptions, filter_record_batch}; use arrow::datatypes::{DataType, Field, Int8Type, Int32Type, Schema}; @@ -5575,6 +5576,64 @@ async fn join_runs_continue_only_within_a_buffered_batch() -> Result<()> { Ok(()) } +/// Long runs of buffered rows are copied as ranges. Here they come from two +/// buffered batches, with a null-joined pair between them and nulls in the +/// copied columns: integers and strings, which have their own copies, and +/// booleans, which `MutableArrayData` copies. +#[tokio::test] +async fn join_left_copies_runs_of_several_batches() -> Result<()> { + let left = build_table( + ("a1", &vec![1, 2, 3]), + ("b1", &vec![0, 0, 0]), + ("c1", &vec![10, 20, 30]), + ); + let right_schema = Arc::new(Schema::new(vec![ + Field::new("a2", DataType::Int32, false), + Field::new("b2", DataType::Int32, true), + Field::new("c2", DataType::Utf8, true), + Field::new("d2", DataType::Boolean, true), + ])); + // Key 1 has rows 0 to 39 of the first batch, and key 3 its rows 40 to 59 + // and rows 0 to 19 of the second. + let batch = |keys: Vec, first: i32| { + let rows = first..first + keys.len() as i32; + RecordBatch::try_new( + Arc::clone(&right_schema), + vec![ + Arc::new(Int32Array::from(keys)), + Arc::new(Int32Array::from_iter( + rows.clone().map(|i| (i % 5 != 4).then_some(i)), + )), + Arc::new(StringArray::from_iter( + rows.clone().map(|i| (i % 7 != 6).then(|| format!("r{i}"))), + )), + Arc::new(BooleanArray::from_iter( + rows.map(|i| (i % 11 != 10).then_some(i % 3 == 0)), + )), + ], + ) + }; + let first = batch([vec![1; 40], vec![3; 20]].concat(), 0)?; + let second = batch([vec![3; 20], vec![4; 5]].concat(), 60)?; + let right = build_table_from_batches(vec![first.clone(), second.clone()]); + 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, Left).await?; + let output = arrow::compute::concat_batches(&batches[0].schema(), &batches)?; + for column in [1, 2, 3] { + let expected = arrow::compute::concat(&[ + first.column(column).slice(0, 40).as_ref(), + new_null_array(first.column(column).data_type(), 1).as_ref(), + first.column(column).slice(40, 20).as_ref(), + second.column(column).slice(0, 20).as_ref(), + ])?; + assert_eq!(output.column(3 + column), &expected, "column {column}"); + } + 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. From 66bc8316b2b1b0b8f2d5074bbec49ba136b7ebe1 Mon Sep 17 00:00:00 2001 From: comphead Date: Fri, 4 Dec 2026 09:40:57 -0800 Subject: [PATCH 05/10] refactor: simplify sort-merge join pair runs after review - Skip loading buffered batches when the join reads no buffered column. - Share one `PairRun::continues` rule between the summary and the ranges. - Copy ranges of primitive and byte columns and gather the other columns, instead of a separate `MutableArrayData` path and dictionary check. - Repeat streamed rows by the number of streamed rows, not runs, and build their indices once. - Remap the filter's buffered columns from the remapped filter. - Reuse `SortMergeJoinExec::probe_side`, add `filter_indices` and `filter_columns`, and fold the dictionary test into the runs test. --- .../sort_merge_join/materializing_stream.rs | 623 +++++++++--------- .../src/joins/sort_merge_join/tests.rs | 90 +-- 2 files changed, 356 insertions(+), 357 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 a275b81bbf533..2ef3e1bc2939a 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 @@ -9,6 +9,7 @@ //! *streamed* side and the *buffered* side), compares join keys, and //! produces joined `RecordBatch`es. +use std::cell::OnceCell; use std::cmp::Ordering; use std::collections::VecDeque; use std::fmt::Debug; @@ -16,6 +17,7 @@ use std::mem::{size_of, take}; use std::ops::Range; use std::sync::Arc; +use crate::joins::SortMergeJoinExec; use crate::joins::sort_merge_join::filter::{ FilterMetadata, filter_record_batch_by_join_type, get_corrected_filter_mask, get_filter_columns, needs_deferred_filtering, @@ -33,7 +35,7 @@ use arrow::array::types::{ BinaryType, ByteArrayType, LargeBinaryType, LargeUtf8Type, UInt64Type, Utf8Type, }; use arrow::array::*; -use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow::buffer::{BooleanBuffer, NullBuffer, OffsetBuffer, ScalarBuffer}; use arrow::compute::{ self, BatchCoalescer, FilterBuilder, FilterPredicate, SortOptions, concat_batches, filter_record_batch, interleave, @@ -56,29 +58,38 @@ use futures::StreamExt; /// 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`. +/// single null-joined pair, without a 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, + /// Index in `buffered_data` of the batch that the buffered rows come from, + /// `None` for a null-joined pair + buffered_batch_idx: 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, + /// Whether the buffered rows of this run follow those of `previous` in the + /// same buffered batch. Null-joined pairs follow each other. + fn continues(&self, previous: &PairRun) -> bool { + let previous_end = match previous.buffered_batch_idx { + Some(_) => previous.buffered_row + previous.len, None => 0, + }; + self.buffered_batch_idx == previous.buffered_batch_idx + && self.buffered_row == previous_end + } + + /// The buffered rows of the run, whose source is their batch's index + fn buffered_range(&self) -> BufferedRange { + BufferedRange { + source: self.buffered_batch_idx, + start: self.buffered_row, + len: self.len, } } } @@ -91,11 +102,15 @@ const MIN_COPIED_RUN_LEN: usize = 12; /// What a freeze needs to know about its runs, found in one pass. struct RunsSummary { + num_pairs: usize, /// The number of ranges of buffered rows, merging runs that continue each - /// other (see [`buffered_ranges`]) + /// other (see [`PairRun::continues`]) num_ranges: usize, + /// The number of streamed rows, counting a row again when another comes + /// between its runs + num_streamed_rows: usize, /// The least and the greatest index of a buffered batch that a run reads - batches: Option<(usize, usize)>, + batch_bounds: Option<(usize, usize)>, /// Whether a pair has no buffered row nulls: bool, /// Whether the streamed rows form a range, one per pair @@ -106,28 +121,30 @@ impl RunsSummary { fn new(runs: &[PairRun], num_pairs: usize) -> Self { let first_row = runs[0].streamed_row; let mut summary = Self { + num_pairs, num_ranges: 0, - batches: None, + num_streamed_rows: 0, + batch_bounds: 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); + let mut previous: Option<&PairRun> = None; 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.num_ranges += usize::from(previous.is_none_or(|p| !run.continues(p))); + summary.num_streamed_rows += + usize::from(previous.is_none_or(|p| p.streamed_row != run.streamed_row)); + match run.buffered_batch_idx { + Some(batch_idx) => { + lo = lo.min(batch_idx); + hi = hi.max(batch_idx); + } + None => summary.nulls = true, } + previous = Some(run); } - summary.batches = (lo <= hi).then_some((lo, hi)); + summary.batch_bounds = (lo <= hi).then_some((lo, hi)); summary } } @@ -136,23 +153,29 @@ impl RunsSummary { 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 + /// Rows repeated for runs of pairs, each a `(row, count)`, `num_rows` in + /// all. `indices` holds the row of each pair once a column needs it. Repeated { repeats: Vec<(usize, usize)>, num_rows: usize, + indices: OnceCell, }, /// The row of each pair Indices(UInt64Array), } impl StreamedRows { - fn new(runs: &[PairRun], num_pairs: usize, summary: &RunsSummary) -> Self { + fn new(runs: &[PairRun], summary: &RunsSummary) -> Self { + let num_pairs = summary.num_pairs; 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()); + // Runs of one streamed row, as when its key group spans buffered + // batches, repeat it together. + if num_pairs >= summary.num_streamed_rows * MIN_COPIED_RUN_LEN { + let mut repeats: Vec<(usize, usize)> = + Vec::with_capacity(summary.num_streamed_rows); for run in runs { match repeats.last_mut() { Some((row, count)) if *row == run.streamed_row => *count += run.len, @@ -173,24 +196,14 @@ impl StreamedRows { 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, + Self::Repeated { + repeats, + num_rows, + indices: OnceCell::new(), } } - 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 { @@ -209,26 +222,37 @@ impl StreamedRows { } start += count; } - return Ok(Self::repeated(kept_repeats, predicate.count())); + let num_rows = predicate.count(); + let long = num_rows >= kept_repeats.len() * MIN_COPIED_RUN_LEN; + let rows = Self::repeated(kept_repeats, num_rows); + return Ok(if long { + rows + } else { + Self::Indices(rows.indices()) + }); } Self::Indices(indices) => indices, }; - Ok(Self::Indices( - as_uint64_array(&predicate.filter(&indices)?)?.clone(), - )) + Ok(Self::Indices(filter_indices(predicate, &indices)?)) } - /// The row of each pair, for the deferred filter's metadata + /// The row of each pair 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::Repeated { + repeats, + num_rows, + indices, + } => indices + .get_or_init(|| { + 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) + }) + .clone(), Self::Indices(indices) => indices.clone(), } } @@ -240,22 +264,16 @@ impl StreamedRows { 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::Repeated { + repeats, num_rows, .. + } => arrays + .map( + |a| match repeat_primitive_rows(a.as_ref(), repeats, *num_rows) { + Some(repeated) => Ok(repeated), + None => Ok(compute::take(a.as_ref(), &self.indices(), None)?), + }, + ) + .collect(), Self::Indices(indices) => arrays .map(|a| Ok(compute::take(a.as_ref(), indices, None)?)) .collect(), @@ -303,10 +321,18 @@ 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. +/// The `indices` that `predicate` keeps. +fn filter_indices( + predicate: &FilterPredicate, + indices: &UInt64Array, +) -> Result { + Ok(as_uint64_array(&predicate.filter(indices)?)?.clone()) +} + +/// Rows of the buffered batches that a freeze copies as a range or gathers. A +/// range without a source is null rows. #[derive(Clone, Copy)] -struct CopiedRange { +struct BufferedRange { source: Option, start: usize, len: usize, @@ -317,10 +343,12 @@ struct CopiedRange { enum BufferedRows<'a> { /// 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 of rows of the `batches`, copied in turn. `nulls` tells whether a + /// range has no source. Ranges { batches: Vec<&'a RecordBatch>, - ranges: Vec, + ranges: Vec, + nulls: bool, num_rows: usize, }, /// The rows of one buffered batch at these indices, null where a pair has no @@ -334,35 +362,29 @@ enum BufferedRows<'a> { nulls: bool, indices: Vec<(usize, usize)>, }, - /// Null rows of the buffered schema + /// Null rows of the buffered schema, which also stand for rows whose + /// buffered columns the join does not read 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::Range(batch, range) => { + Self::Batch(batch, filter_indices(predicate, &range_indices(range))?) + } Self::Ranges { batches, ranges, .. } => { - let kept_ranges = filter_ranges(&ranges, kept); - let nulls = kept_ranges.iter().any(|r| r.source.is_none()); + let (kept_ranges, nulls) = filter_ranges(&ranges, kept); ranges_or_gathered(batches, kept_ranges, nulls, num_kept) } - Self::Batch(batch, indices) => Self::Batch( - batch, - as_uint64_array(&predicate.filter(&indices)?)?.clone(), - ), + Self::Batch(batch, indices) => { + Self::Batch(batch, filter_indices(predicate, &indices)?) + } Self::Interleaved { batches, nulls, @@ -395,34 +417,31 @@ impl BufferedRows<'_> { Self::Ranges { batches, ranges, + nulls, num_rows, } => { - // Copying the ranges of several batches would concatenate their - // dictionaries, which `interleave` merges instead. + // Columns of the types without a copy are gathered, from rows + // built once for all of them. For dictionaries `interleave` also + // merges what copying would concatenate. 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) - } - }) + .map( + |&c| match copy_ranges(batches, c, ranges, *nulls, *num_rows)? { + Some(copied) => Ok(copied), + None => { + let rows = gathered.get_or_insert_with(|| { + gather_ranges( + batches.clone(), + ranges.iter().copied(), + *nulls, + *num_rows, + ) + }); + Ok(rows.columns(&[c])?.remove(0)) + } + }, + ) .collect(); } Self::Batch(batch, indices) => { @@ -460,48 +479,40 @@ impl BufferedRows<'_> { } } -/// Copies `ranges` of the `column` of `batches` into one array of `num_rows`. -/// Primitive and byte arrays are copied from their buffers, and other types -/// with `MutableArrayData`. +/// Copies `ranges` of the `column` of `batches` into one array of `num_rows`, +/// or returns `None` unless the column holds primitive or byte values. `nulls` +/// tells whether a range has no source. fn copy_ranges( batches: &[&RecordBatch], column: usize, - ranges: &[CopiedRange], + ranges: &[BufferedRange], + nulls: bool, num_rows: usize, -) -> Result { +) -> Result> { let arrays: Vec<&ArrayRef> = batches.iter().map(|b| b.column(column)).collect(); let array = arrays[0]; - downcast_primitive_array!( - array => Ok(copy_primitive_ranges(array, &arrays, ranges, num_rows)), - DataType::Utf8 => copy_byte_ranges::(&arrays, ranges, num_rows), - DataType::LargeUtf8 => copy_byte_ranges::(&arrays, ranges, num_rows), - DataType::Binary => copy_byte_ranges::(&arrays, ranges, num_rows), + Ok(Some(downcast_primitive_array!( + array => copy_primitive_ranges(array, &arrays, ranges, nulls, num_rows), + DataType::Utf8 => copy_byte_ranges::(&arrays, ranges, nulls, num_rows)?, + DataType::LargeUtf8 => { + copy_byte_ranges::(&arrays, ranges, nulls, num_rows)? + } + DataType::Binary => { + copy_byte_ranges::(&arrays, ranges, nulls, num_rows)? + } DataType::LargeBinary => { - copy_byte_ranges::(&arrays, ranges, num_rows) - } - _ => { - let data: Vec = arrays.iter().map(|a| a.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)? - } - None => copied.try_extend_nulls(range.len)?, - } - } - Ok(make_array(copied.freeze())) + copy_byte_ranges::(&arrays, ranges, nulls, num_rows)? } - ) + _ => return Ok(None), + ))) } /// [`copy_ranges`] for the primitive `arrays`, of which `first` is the first. fn copy_primitive_ranges( first: &PrimitiveArray, arrays: &[&ArrayRef], - ranges: &[CopiedRange], + ranges: &[BufferedRange], + nulls: bool, num_rows: usize, ) -> ArrayRef { let arrays: Vec<&PrimitiveArray> = @@ -515,13 +526,11 @@ fn copy_primitive_ranges( None => values.resize(values.len() + range.len, T::Native::default()), } } - let nulls: Vec<_> = arrays.iter().map(|a| a.nulls()).collect(); + let source_nulls: Vec<_> = arrays.iter().map(|a| a.nulls()).collect(); + let nulls = copy_range_nulls(&source_nulls, ranges, nulls, num_rows); Arc::new( - PrimitiveArray::::new( - values.into(), - copy_range_nulls(&nulls, ranges, num_rows), - ) - .with_data_type(first.data_type().clone()), + PrimitiveArray::::new(values.into(), nulls) + .with_data_type(first.data_type().clone()), ) } @@ -529,12 +538,13 @@ fn copy_primitive_ranges( /// their offsets. fn copy_byte_ranges( arrays: &[&ArrayRef], - ranges: &[CopiedRange], + ranges: &[BufferedRange], + nulls: bool, num_rows: usize, ) -> Result { let arrays: Vec<&GenericByteArray> = arrays.iter().map(|a| a.as_bytes::()).collect(); - let value_offsets = |range: &CopiedRange| { + let value_offsets = |range: &BufferedRange| { range.source.map(|source| { &arrays[source].value_offsets()[range.start..=range.start + range.len] }) @@ -565,8 +575,8 @@ fn copy_byte_ranges( _ => offsets.resize(offsets.len() + range.len, end), } } - let nulls: Vec<_> = arrays.iter().map(|a| a.nulls()).collect(); - let nulls = copy_range_nulls(&nulls, ranges, num_rows); + let source_nulls: Vec<_> = arrays.iter().map(|a| a.nulls()).collect(); + let nulls = copy_range_nulls(&source_nulls, ranges, nulls, num_rows); // SAFETY: the offsets start at 0 and grow by the length of each copied // value, up to `num_bytes`, which fits the offset type. The values are whole // values of arrays of the same type, so they are valid (e.g. UTF-8). @@ -576,22 +586,25 @@ fn copy_byte_ranges( })) } -/// The validity of the rows of `ranges` from sources with the validity `nulls`, -/// in which a range without a source is null, or `None` if every row is valid. +/// The validity of the rows of `ranges` from sources with the validity +/// `source_nulls`, or `None` if every row is valid. `nulls` tells whether a +/// range has no source, and so is null. fn copy_range_nulls( - nulls: &[Option<&NullBuffer>], - ranges: &[CopiedRange], + source_nulls: &[Option<&NullBuffer>], + ranges: &[BufferedRange], + nulls: bool, num_rows: usize, ) -> Option { - let source_nulls = |range: &CopiedRange| range.source.map(|s| nulls[s]); - if ranges.iter().all(|range| { - source_nulls(range).is_some_and(|n| n.is_none_or(|n| n.null_count() == 0)) - }) { + if !nulls + && source_nulls + .iter() + .all(|n| n.is_none_or(|n| n.null_count() == 0)) + { return None; } let mut validity = BooleanBufferBuilder::new(num_rows); for range in ranges { - match source_nulls(range) { + match range.source.map(|s| source_nulls[s]) { None => validity.append_n(range.len, false), Some(None) => validity.append_n(range.len, true), Some(Some(source)) => { @@ -604,9 +617,14 @@ fn copy_range_nulls( Some(NullBuffer::new(validity.finish())) } -/// The rows of `ranges` at which `mask` is set, as ranges. -fn filter_ranges(ranges: &[CopiedRange], mask: &BooleanArray) -> Vec { - let mut kept = Vec::new(); +/// The rows of `ranges` at which `mask` is set, as ranges, and whether one of +/// them has no source. +fn filter_ranges( + ranges: &[BufferedRange], + mask: &BooleanArray, +) -> (Vec, bool) { + let mut kept = Vec::with_capacity(ranges.len()); + let mut nulls = false; let mut ranges = ranges.iter(); let (mut range, mut range_start) = (ranges.next(), 0); for (start, end) in mask.values().set_slices() { @@ -617,10 +635,11 @@ fn filter_ranges(ranges: &[CopiedRange], mask: &BooleanArray) -> Vec Vec, - ranges: Vec, + ranges: Vec, nulls: bool, num_rows: usize, ) -> BufferedRows<'_> { @@ -644,6 +664,7 @@ fn ranges_or_gathered( return BufferedRows::Ranges { batches, ranges, + nulls, num_rows, }; } @@ -654,13 +675,14 @@ fn ranges_or_gathered( /// gathered row by row. `nulls` tells whether a range has no source. fn gather_ranges( batches: Vec<&RecordBatch>, - ranges: impl ExactSizeIterator + Clone, + 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 + // One row per range, as in a 1:1 or n:1 join + let single_rows = ranges.len() == num_rows; + let indices: Vec = if single_rows { ranges.clone().map(|range| range.start as u64).collect() } else { let mut indices = Vec::with_capacity(num_rows); @@ -670,11 +692,18 @@ fn gather_ranges( 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()) + let mut ranges = ranges; + NullBuffer::new(if single_rows { + BooleanBuffer::collect_bool(num_rows, |_| { + ranges.next().is_some_and(|range| range.source.is_some()) + }) + } else { + let mut validity = BooleanBufferBuilder::new(num_rows); + for range in ranges { + validity.append_n(range.len, range.source.is_some()); + } + validity.finish() + }) }); return BufferedRows::Batch(batch, UInt64Array::new(indices.into(), validity)); } @@ -700,21 +729,14 @@ fn gather_ranges( /// 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 + '_ { +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) - { + let mut last = runs.next()?; + let mut range = last.buffered_range(); + while let Some(next) = runs.next_if(|run| run.continues(last)) { range.len += next.len; - end = next.buffered_end(); + last = next; } Some(range) }) @@ -785,20 +807,13 @@ pub(super) struct StreamedBatch { } impl StreamedBatch { - /// 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"); + fn try_new(batch: RecordBatch, on_column: &[Arc]) -> Result { let join_arrays = join_arrays(&batch, on_column)?; Ok(StreamedBatch { batch, idx: 0, join_arrays, - runs, + runs: vec![], num_output_rows: 0, }) } @@ -823,7 +838,7 @@ impl StreamedBatch { fn append_null_joined_pair(&mut self) { self.runs.push(PairRun { streamed_row: self.idx, - buffered_batch: None, + buffered_batch_idx: None, buffered_row: 0, len: 1, }); @@ -831,17 +846,17 @@ impl StreamedBatch { } /// 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`. + /// rows from `buffered_row` on in the buffered batch at `buffered_batch_idx`. fn append_output_pairs( &mut self, - buffered_batch: usize, + buffered_batch_idx: usize, buffered_row: usize, len: usize, ) { debug_assert!(len > 0, "appending an empty run"); self.runs.push(PairRun { streamed_row: self.idx, - buffered_batch: Some(buffered_batch), + buffered_batch_idx: Some(buffered_batch_idx), buffered_row, len, }); @@ -1295,22 +1310,11 @@ impl MaterializingSortMergeJoinStream { semi/anti/mark joins use BitwiseSortMergeJoinStream" ); let join_time = join_metrics.join_time(); - let (streamed_side, buffered_side) = if join_type == JoinType::Right { - (JoinSide::Right, JoinSide::Left) - } else { - (JoinSide::Left, JoinSide::Right) - }; + let streamed_side = SortMergeJoinExec::probe_side(&join_type); + let buffered_side = streamed_side.negate(); let deferred_filtering = needs_deferred_filtering(filter.as_ref(), join_type); - let filter_columns = |side| { - filter - .iter() - .flat_map(|f| f.column_indices()) - .filter(|c| c.side == side) - .map(|c| c.index) - .collect::>() - }; - let streamed_filter_columns = filter_columns(streamed_side); - let mut buffered_filter_columns = filter_columns(buffered_side); + let streamed_filter_columns = filter_columns(filter.as_ref(), streamed_side); + let mut buffered_filter_columns = filter_columns(filter.as_ref(), buffered_side); let mut streamed_gathered_columns = streamed_columns.clone(); let mut buffered_gathered_columns = buffered_columns.clone(); let filter = filter.map(|f| { @@ -1349,23 +1353,24 @@ impl MaterializingSortMergeJoinStream { + 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 + // their join keys are computed. The buffered columns are then numbered by + // their position among them, as the filter already numbers its own. + let mut buffered_projection = None; + if !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)?); + .eq(0..buffered_schema.fields().len()) + { + buffered_schema = + Arc::new(buffered_schema.project(&buffered_gathered_columns)?); spill_manager = spill_manager.with_schema(Arc::clone(&buffered_schema)); + buffered_filter_columns = filter_columns(filter.as_ref(), buffered_side); + buffered_columns = (0..buffered_columns.len()).collect(); + let num_gathered = buffered_gathered_columns.len(); + buffered_projection = Some(std::mem::replace( + &mut buffered_gathered_columns, + (0..num_gathered).collect(), + )); } let filter_schema = if deferred_filtering && let Some(f) = &filter { let mut fields = Vec::with_capacity(f.schema().fields().len()); @@ -1820,7 +1825,7 @@ impl MaterializingSortMergeJoinStream { } // We need all batches that matched with streamed rows for run in &self.streamed_batch.runs { - if let Some(idx) = run.buffered_batch + if let Some(idx) = run.buffered_batch_idx && needed.last() != Some(&idx) { needed.push(idx); @@ -1921,9 +1926,13 @@ impl MaterializingSortMergeJoinStream { self.freeze_streamed()?; self.join_metrics.input_batches().add(1); self.join_metrics.input_rows().add(batch.num_rows()); + // The runs, which the freeze emptied, keep their capacity. let runs = take(&mut self.streamed_batch.runs); - self.streamed_batch = - StreamedBatch::try_new(batch, &self.on_streamed, runs)?; + debug_assert!(runs.is_empty(), "pairs left unfrozen"); + self.streamed_batch = StreamedBatch { + runs, + ..StreamedBatch::try_new(batch, &self.on_streamed)? + }; self.rebuild_streamed_buffered_cmp()?; // Every incoming streamed batch gets a unique id. self.streamed_batch_counter += 1; @@ -2347,11 +2356,11 @@ impl MaterializingSortMergeJoinStream { /// 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() { + if summary.batch_bounds.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) + let streamed_columns = StreamedRows::new(runs, &summary) .columns(&self.streamed_batch.batch, &self.streamed_columns)?; let buffered_columns = create_unmatched_columns( &self.buffered_schema, @@ -2373,7 +2382,7 @@ impl MaterializingSortMergeJoinStream { return Ok(()); } - let frozen = self.materialize_pairs(runs, num_pairs, &summary)?; + let frozen = self.materialize_pairs(runs, &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 @@ -2381,7 +2390,7 @@ impl MaterializingSortMergeJoinStream { { let mut offset = 0; for run in runs { - if let Some(batch) = run.buffered_batch { + if let Some(batch) = run.buffered_batch_idx { 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() { @@ -2407,16 +2416,15 @@ impl MaterializingSortMergeJoinStream { self.join_type, ) } - None if frozen.batch.num_rows() > 0 => self + None => self .joined_record_batches .push_batch_without_metadata(frozen.batch), - None => {} } Ok(()) } - /// Materializes the `num_pairs` pairs of `runs`, of which some have a - /// buffered row, and evaluates the join filter on them. + /// Materializes the pairs of `runs`, of which some have a buffered row, and + /// evaluates the join filter on them. /// /// 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 @@ -2431,24 +2439,28 @@ impl MaterializingSortMergeJoinStream { 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 num_pairs = summary.num_pairs; + let streamed_rows = StreamedRows::new(runs, summary); + let buffered_rows = self.buffered_rows(runs, 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. + // Filtering first saves nothing when neither side gathers, and an + // outer join, which keeps a pair of each streamed row, saves nothing + // either when every row has one pair. Some(filter) if self.filter_first - && !(streamed_rows.is_range() && buffered_rows.is_range()) + && !(matches!(streamed_rows, StreamedRows::Range(_)) + && matches!( + buffered_rows, + BufferedRows::Range(..) | BufferedRows::Nulls(..) + )) && (!self.deferred_filtering || num_pairs > runs.len()) => { filter } - filter => { + _ => { return self.materialize_all_pairs( - filter.as_ref(), &streamed_rows, &buffered_rows, num_pairs, @@ -2463,26 +2475,28 @@ impl MaterializingSortMergeJoinStream { buffered_rows.columns(&self.buffered_filter_columns)?; let mut streamed_arrays = streamed_filter_arrays.iter().cloned(); let mut buffered_arrays = buffered_filter_arrays.iter().cloned(); + let streamed_side = self.streamed_side(); let columns = filter .column_indices() .iter() - .map(|column_index| { - if column_index.side == self.streamed_side() { + .map(|column_index| match column_index.side { + JoinSide::None => internal_err!("Unexpected JoinSide::None in filter"), + side if side == 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") - }) } + _ => buffered_arrays.next().ok_or_else(|| { + internal_datafusion_err!("missing buffered filter column") + }), }) .collect::>>()?; - let schema = self - .filter_schema - .as_ref() - .unwrap_or_else(|| filter.schema()); - let passed = evaluate_join_filter(filter, schema, columns, num_pairs)?; + let passed = evaluate_join_filter( + filter, + self.filter_schema.as_ref(), + columns, + num_pairs, + )?; let kept = if self.deferred_filtering { passed_or_first_of_row(runs, &passed) } else { @@ -2544,10 +2558,9 @@ impl MaterializingSortMergeJoinStream { }) } - /// Materializes every pair, then evaluates `filter`, if any, on them. + /// Materializes every pair, then evaluates the join filter, if any, on them. fn materialize_all_pairs( &self, - filter: Option<&JoinFilter>, streamed_rows: &StreamedRows, buffered_rows: &BufferedRows, num_pairs: usize, @@ -2559,6 +2572,7 @@ impl MaterializingSortMergeJoinStream { // `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 = self.filter.as_ref(); let filter_columns = if self.join_type == JoinType::Right { get_filter_columns(filter, &buffered_columns, &streamed_columns)? } else { @@ -2581,11 +2595,12 @@ impl MaterializingSortMergeJoinStream { 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)?; + let passed = evaluate_join_filter( + filter, + self.filter_schema.as_ref(), + filter_columns, + num_pairs, + )?; Ok(if self.deferred_filtering { FrozenPairs { batch, @@ -2603,11 +2618,7 @@ impl MaterializingSortMergeJoinStream { /// 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 - } + SortMergeJoinExec::probe_side(&self.join_type) } /// The output columns, given the streamed and the buffered ones. @@ -2623,25 +2634,30 @@ impl MaterializingSortMergeJoinStream { } } - /// 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. + /// Where the buffered rows of `runs` 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, runs: &[PairRun], - num_pairs: usize, summary: &RunsSummary, ) -> Result> { let RunsSummary { + num_pairs, num_ranges, - batches: Some((min_batch_idx, max_batch_idx)), + batch_bounds, nulls, .. - } = *summary - else { + } = *summary; + // Nothing to gather when no pair has a buffered row or the join reads no + // buffered column + let Some((min_batch_idx, max_batch_idx)) = batch_bounds else { return Ok(BufferedRows::Nulls(&self.buffered_schema, num_pairs)); }; + if self.buffered_gathered_columns.is_empty() { + return Ok(BufferedRows::Nulls(&self.buffered_schema, num_pairs)); + } if num_ranges == 1 { let start = runs[0].buffered_row; return Ok(BufferedRows::Range( @@ -2711,12 +2727,13 @@ 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![]; + let mut source_batches: Vec = + Vec::with_capacity(runs.len().min(source_of_batch.len())); 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) { + for batch_idx in runs.iter().filter_map(|run| run.buffered_batch_idx) { let slot = &mut source_of_batch[batch_idx - min_batch_idx]; if *slot == UNSEEN { *slot = source_batches.len(); @@ -2725,32 +2742,29 @@ impl MaterializingSortMergeJoinStream { } } // Read each source batch once (spilled batches require disk I/O). - let batches = source_batches + let source_data = source_batches .iter() .map(|&idx| self.buffered_data.batches[idx].in_memory()) .collect::>>()?; - let source = |range: CopiedRange| CopiedRange { + let source = |range: BufferedRange| BufferedRange { 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 { + let mut ranges = Vec::with_capacity(num_ranges); + ranges.extend(buffered_ranges(runs).map(source)); BufferedRows::Ranges { - batches, - ranges: buffered_ranges(runs).map(source).collect(), + batches: source_data, + ranges, + nulls, 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) + let ranges = runs.iter().map(|run| source(run.buffered_range())); + gather_ranges(source_data, ranges, nulls, num_pairs) }) } @@ -2985,17 +2999,28 @@ fn output_columns( .collect() } +/// The columns of `side` that `filter` reads, in its order. +fn filter_columns(filter: Option<&JoinFilter>, side: JoinSide) -> Vec { + filter + .iter() + .flat_map(|f| f.column_indices()) + .filter(|c| c.side == side) + .map(|c| c.index) + .collect() +} + /// 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. +/// intermediate schema, or `filter_schema` if given, and returns which pairs +/// pass. A NULL result does not pass, as in SQL. fn evaluate_join_filter( filter: &JoinFilter, - schema: &SchemaRef, + filter_schema: Option<&SchemaRef>, columns: Vec, num_rows: usize, ) -> Result { // A filter that reads no columns (e.g. a bound parameter or a volatile // function) still has to be evaluated, so the batch carries its row count. + let schema = filter_schema.unwrap_or_else(|| filter.schema()); let batch = new_batch(schema, columns, num_rows)?; let result = filter.expression().evaluate(&batch)?.into_array(num_rows)?; Ok(boolean_mask_from_filter(as_boolean_array(&result)?)) 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 2c621c9303a3f..0fe76228d2640 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -5542,7 +5542,9 @@ async fn join_inner_group_spans_buffered_and_output_batches() -> Result<()> { /// 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. +/// starts in the first batch. The dictionary column is gathered with +/// `interleave`, since copying would concatenate the batches' dictionaries, here +/// 200 values for `Int8` keys. #[tokio::test] async fn join_runs_continue_only_within_a_buffered_batch() -> Result<()> { let left = build_table( @@ -5550,14 +5552,29 @@ async fn join_runs_continue_only_within_a_buffered_batch() -> Result<()> { ("b1", &vec![0, 0]), ("c1", &vec![10, 11]), ); + let right_schema = Arc::new(Schema::new(vec![ + Field::new("a2", DataType::Int32, false), + Field::new("c2", DataType::Int32, false), + Field::new_dictionary("d2", DataType::Int8, DataType::Utf8, false), + ])); + // Row `i` has `c2 = first_c2 + i` and `d2 = "v{c2}"`. 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 values = (first_c2..first_c2 + 100).map(|i| format!("v{i}")); + RecordBatch::try_new( + Arc::clone(&right_schema), + vec![ + Arc::new(Int32Array::from_iter_values( + (0..64).map(|i| first_key + i / 32), + )), + Arc::new(Int32Array::from_iter_values(first_c2..first_c2 + 64)), + Arc::new(DictionaryArray::::try_new( + Int8Array::from_iter_values(0..64), + Arc::new(StringArray::from_iter_values(values)), + )?), + ], ) }; - let right = build_table_from_batches(vec![batch(0, 0), batch(1, 64)]); + 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 _, @@ -5565,21 +5582,23 @@ async fn join_runs_continue_only_within_a_buffered_batch() -> Result<()> { let (_, batches) = join_collect(left, right, on, Inner).await?; let output = arrow::compute::concat_batches(&batches[0].schema(), &batches)?; let c2 = output - .column(5) + .column(4) .as_any() .downcast_ref::() .unwrap(); - assert_eq!( - c2.values().to_vec(), - (32..96).chain(32..96).collect::>() - ); + let expected: Vec = (32..96).chain(32..96).collect(); + assert_eq!(c2.values().to_vec(), expected); + let d2 = arrow::compute::cast(output.column(5), &DataType::Utf8)?; + let d2 = d2.as_any().downcast_ref::().unwrap(); + let expected: Vec = expected.iter().map(|i| format!("v{i}")).collect(); + assert_eq!(d2.iter().flatten().collect::>(), expected); Ok(()) } /// Long runs of buffered rows are copied as ranges. Here they come from two /// buffered batches, with a null-joined pair between them and nulls in the -/// copied columns: integers and strings, which have their own copies, and -/// booleans, which `MutableArrayData` copies. +/// columns: integers and strings, which are copied, and booleans, which are +/// gathered. #[tokio::test] async fn join_left_copies_runs_of_several_batches() -> Result<()> { let left = build_table( @@ -5634,51 +5653,6 @@ async fn join_left_copies_runs_of_several_batches() -> Result<()> { 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 From d707adcf63df92c88e09f04e7a7ed995fae77f1f Mon Sep 17 00:00:00 2001 From: comphead Date: Fri, 4 Dec 2026 09:55:40 -0800 Subject: [PATCH 06/10] test: cover null-joined sort-merge join pairs in copied and filtered ranges `join_left_copies_runs_of_several_batches` now also checks the key column, which has no nulls of its own, and a new test keeps a null-joined pair that passes the filter in the same freeze as a filtered run. --- .../src/joins/sort_merge_join/tests.rs | 70 +++++++++++++++++-- 1 file changed, 66 insertions(+), 4 deletions(-) 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 0fe76228d2640..77e829a449325 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -64,6 +64,7 @@ use datafusion_execution::spill_file::{SpillFile, SpillWriter, TempFileFactory}; use datafusion_execution::{SendableRecordBatchStream, TaskContext}; use datafusion_expr::Operator; use datafusion_physical_expr::expressions::BinaryExpr; +use datafusion_physical_expr::expressions::IsNullExpr; use datafusion_physical_expr::expressions::Literal; use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr}; use datafusion_physical_expr_common::physical_expr::PhysicalExprRef; @@ -5596,9 +5597,9 @@ async fn join_runs_continue_only_within_a_buffered_batch() -> Result<()> { } /// Long runs of buffered rows are copied as ranges. Here they come from two -/// buffered batches, with a null-joined pair between them and nulls in the -/// columns: integers and strings, which are copied, and booleans, which are -/// gathered. +/// buffered batches, with a null-joined pair between them, into a key without +/// nulls and columns with nulls: integers and strings, which are copied, and +/// booleans, which are gathered. #[tokio::test] async fn join_left_copies_runs_of_several_batches() -> Result<()> { let left = build_table( @@ -5641,7 +5642,7 @@ async fn join_left_copies_runs_of_several_batches() -> Result<()> { )]; let (_, batches) = join_collect(left, right, on, Left).await?; let output = arrow::compute::concat_batches(&batches[0].schema(), &batches)?; - for column in [1, 2, 3] { + for column in 0..4 { let expected = arrow::compute::concat(&[ first.column(column).slice(0, 40).as_ref(), new_null_array(first.column(column).data_type(), 1).as_ref(), @@ -5653,6 +5654,67 @@ async fn join_left_copies_runs_of_several_batches() -> Result<()> { Ok(()) } +/// A null-joined pair that passes the filter keeps its NULL buffered values +/// when its freeze filters a run of buffered rows: the run of key 1 and the +/// pair of key 2, which key 3 keeps in one freeze. +#[tokio::test] +async fn join_left_keeps_nulls_of_passing_null_joined_pair() -> Result<()> { + let left = build_table( + ("a1", &vec![1, 2]), + ("b1", &vec![0, 0]), + ("c1", &vec![10, 20]), + ); + let right = build_table( + ("a2", &[vec![1; 24], vec![3]].concat()), + ("b2", &(0..25).collect()), + ("c2", &vec![0; 25]), + ); + let on = vec![( + Arc::new(Column::new_with_schema("a1", &left.schema())?) as _, + Arc::new(Column::new_with_schema("a2", &right.schema())?) as _, + )]; + // `a2 IS NULL OR b2 < 5` + let filter = JoinFilter::new( + Arc::new(BinaryExpr::new( + Arc::new(IsNullExpr::new(Arc::new(Column::new("a2", 0)))), + Operator::Or, + Arc::new(BinaryExpr::new( + Arc::new(Column::new("b2", 1)), + Operator::Lt, + Arc::new(Literal::new(ScalarValue::Int32(Some(5)))), + )), + )), + vec![ + ColumnIndex { + index: 0, + side: JoinSide::Right, + }, + ColumnIndex { + index: 1, + side: JoinSide::Right, + }, + ], + Arc::new(Schema::new(vec![ + Field::new("a2", DataType::Int32, true), + Field::new("b2", DataType::Int32, true), + ])), + ); + let (_, batches) = join_collect_with_filter(left, right, on, filter, Left).await?; + assert_snapshot!(batches_to_string(&batches), @r" + +----+----+----+----+----+----+ + | a1 | b1 | c1 | a2 | b2 | c2 | + +----+----+----+----+----+----+ + | 1 | 0 | 10 | 1 | 0 | 0 | + | 1 | 0 | 10 | 1 | 1 | 0 | + | 1 | 0 | 10 | 1 | 2 | 0 | + | 1 | 0 | 10 | 1 | 3 | 0 | + | 1 | 0 | 10 | 1 | 4 | 0 | + | 2 | 0 | 20 | | | | + +----+----+----+----+----+----+ + "); + Ok(()) +} + /// A wrapped multi-source freeze that also carries a null buffered index. /// /// `buffered_rows` has two independent offsets in play on the From d7fab8a53b9830ea423f39014f6009da6680a726 Mon Sep 17 00:00:00 2001 From: comphead Date: Fri, 4 Dec 2026 10:26:58 -0800 Subject: [PATCH 07/10] refactor: build sort-merge join gather validity in one loop One-row ranges had a `collect_bool` path that measured no faster than the builder loop (0.99x on `left_1to1_unmatched`), so the gather keeps one loop. --- .../sort_merge_join/materializing_stream.rs | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 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 2ef3e1bc2939a..e3c3048376f5f 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 @@ -35,7 +35,7 @@ use arrow::array::types::{ BinaryType, ByteArrayType, LargeBinaryType, LargeUtf8Type, UInt64Type, Utf8Type, }; use arrow::array::*; -use arrow::buffer::{BooleanBuffer, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; use arrow::compute::{ self, BatchCoalescer, FilterBuilder, FilterPredicate, SortOptions, concat_batches, filter_record_batch, interleave, @@ -680,9 +680,8 @@ fn gather_ranges( num_rows: usize, ) -> BufferedRows<'_> { if let [batch] = batches[..] { - // One row per range, as in a 1:1 or n:1 join - let single_rows = ranges.len() == num_rows; - let indices: Vec = if single_rows { + 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); @@ -692,18 +691,11 @@ fn gather_ranges( indices }; let validity = nulls.then(|| { - let mut ranges = ranges; - NullBuffer::new(if single_rows { - BooleanBuffer::collect_bool(num_rows, |_| { - ranges.next().is_some_and(|range| range.source.is_some()) - }) - } else { - let mut validity = BooleanBufferBuilder::new(num_rows); - for range in ranges { - validity.append_n(range.len, range.source.is_some()); - } - validity.finish() - }) + 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)); } From 72f4b1f53e672c8d72e6a83b64c0593fb0ba5735 Mon Sep 17 00:00:00 2001 From: comphead Date: Fri, 4 Dec 2026 14:23:24 -0800 Subject: [PATCH 08/10] perf: presize the ranges that a sort-merge join filter keeps `filter_ranges` reserved one kept range per input range, but a long run of buffered rows splits into a range for each slice of pairs that pass, so a selective filter grew the vector several times per freeze. In a Linux profile of TPC-DS q72 the regrowth took about 6% of the join's CPU. The capacity now bounds the slices by the pairs that pass and by one more than the pairs that fail, plus one per input range, without a pass over the mask. The benchmarks sort `data` within each key group, so their filters keep one slice per run and never regrow. On a variant of `inner_1to1000_selective_filtered` whose buffered `data` has no order within a key group, as q72's quantities have none, this is 3.5% faster. --- .../src/joins/sort_merge_join/materializing_stream.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 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 e3c3048376f5f..b30b8d8fed4e1 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 @@ -623,11 +623,17 @@ fn filter_ranges( ranges: &[BufferedRange], mask: &BooleanArray, ) -> (Vec, bool) { - let mut kept = Vec::with_capacity(ranges.len()); + // A slice of set bits makes a range, and one more at each boundary between + // ranges that it crosses. There are at most as many slices as set bits, and + // one more than unset bits. + let mask = mask.values(); + let num_set = mask.count_set_bits(); + let max_slices = num_set.min(mask.len() - num_set + 1); + let mut kept = Vec::with_capacity(max_slices + ranges.len()); let mut nulls = false; let mut ranges = ranges.iter(); let (mut range, mut range_start) = (ranges.next(), 0); - for (start, end) in mask.values().set_slices() { + for (start, end) in mask.set_slices() { let mut start = start; while let Some(r) = range { let range_end = range_start + r.len; From 62ff8d0cbd13743c6fa3616954953308d10f9a33 Mon Sep 17 00:00:00 2001 From: comphead Date: Fri, 4 Dec 2026 14:23:43 -0800 Subject: [PATCH 09/10] perf: materialize an Inner sort-merge join's kept pairs a batch at a time A filter-first freeze materialized the pairs that passed, often a few hundred out of `batch_size`, and the output coalescer then copied them again into its batch. When the freeze of an Inner join keeps no more pairs than the coalescer copies, it now records them as runs, and the stream materializes them in batches that complete the coalescer's partial batch, so that the coalescer passes the next ones on without copying them. Such a freeze also builds no filter predicate and filters neither the filter's columns nor the pairs' rows. Since the runs address the streamed batch and the buffered batches by position, they are materialized before the streamed batch changes, before a buffered batch is dequeued and at the end, in pieces that join the partial batch, so every batch but the last stays full. A new test checks a selective Inner join, with and without spilling, against the unfiltered join and the filter. Against the previous commit, on macOS, `inner_1to1000_selective_filtered`, which has the shape of TPC-DS q72, is 29% faster, `inner_1to100_filtered` 15%, `inner_1to10_filtered` 10% and `inner_1to1_filtered` 5%, and the variant with unordered buffered `data` 13%. The two Left cases, which do not take this path, are 4-5% slower: the new code changes the inlining, which leaves arrow's `BooleanBuilder::extend` in `FilterMetadata::append_filter_metadata` out of line. --- .../sort_merge_join/materializing_stream.rs | 206 +++++++++++++++++- .../src/joins/sort_merge_join/tests.rs | 103 +++++++++ 2 files changed, 298 insertions(+), 11 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 b30b8d8fed4e1..025a4bb47acdb 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 @@ -62,6 +62,7 @@ use futures::StreamExt; /// /// 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)] pub(super) struct PairRun { streamed_row: usize, /// Index in `buffered_data` of the batch that the buffered rows come from, @@ -94,6 +95,61 @@ impl PairRun { } } +/// The pairs of an Inner join that passed its filter and are not materialized +/// yet, in output order (see +/// [`MaterializingSortMergeJoinStream::materialize_kept_pairs`]). Their runs +/// address the current streamed batch and the buffered batches by position, so +/// they are materialized before either changes. +#[derive(Default)] +pub(super) struct KeptPairs { + runs: Vec, + /// Total number of pairs in `runs` + num_pairs: usize, +} + +impl KeptPairs { + /// Appends the pairs of `runs` at which `kept` is set, as runs split at the + /// pairs that are not kept. + fn append(&mut self, runs: &[PairRun], kept: &BooleanArray) { + let mut runs = runs.iter(); + let (mut run, mut run_start) = (runs.next(), 0); + for (start, end) in kept.values().set_slices() { + let mut start = start; + while let Some(r) = run { + let run_end = run_start + r.len; + if run_end <= start { + (run, run_start) = (runs.next(), run_end); + continue; + } + debug_assert!( + r.buffered_batch_idx.is_some(), + "Inner pairs have a buffered row" + ); + let kept_run = PairRun { + buffered_row: r.buffered_row + (start - run_start), + len: end.min(run_end) - start, + ..*r + }; + self.num_pairs += kept_run.len; + match self.runs.last_mut() { + Some(last) + if last.streamed_row == kept_run.streamed_row + && kept_run.continues(last) => + { + last.len += kept_run.len + } + _ => self.runs.push(kept_run), + } + if end <= run_end { + break; + } + start = run_end; + (run, run_start) = (runs.next(), run_end); + } + } + } +} + /// 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 @@ -787,6 +843,18 @@ struct FrozenPairs { passed: Option, } +/// What [`MaterializingSortMergeJoinStream::materialize_pairs`] makes of the +/// pairs of a freeze. +#[expect(clippy::large_enum_variant)] +enum Freeze { + /// The pairs, materialized to stage now + Frozen(FrozenPairs), + /// The pairs of an Inner join at which this is set passed its filter, too few + /// to make a batch that the output coalescer passes on uncopied (see + /// [`KeptPairs`]) + Kept(BooleanArray), +} + /// Represents a record batch from streamed input. /// /// Also stores information of matching rows from buffered batches. @@ -1093,6 +1161,9 @@ pub(super) struct MaterializingSortMergeJoinStream { // ======================================================================== /// Staging output array builders pub joined_record_batches: JoinedRecordBatches, + /// The pairs of an Inner join that passed the filter, waiting to fill a + /// batch + pub kept_pairs: KeptPairs, /// Output buffer. Currently used by filtering as it requires double buffering /// to avoid small/empty batches. Non-filtered joins output directly from /// `joined_record_batches.joined_batches` @@ -1418,6 +1489,7 @@ impl MaterializingSortMergeJoinStream { joined_batches: new_output_coalescer(Arc::clone(&schema), batch_size), filter_metadata: FilterMetadata::new(), }, + kept_pairs: KeptPairs::default(), output: new_output_coalescer(schema, batch_size), batch_size, join_type, @@ -1718,6 +1790,7 @@ impl MaterializingSortMergeJoinStream { // the inputs they came from. self.restore_spilled_batches_for_freeze().await?; self.freeze_all()?; + self.materialize_kept_pairs(true)?; self.release_inputs(); // Verify metadata alignment before final output @@ -1922,6 +1995,9 @@ impl MaterializingSortMergeJoinStream { Some(batch) => { if batch.num_rows() > 0 { self.freeze_streamed()?; + // Kept pairs address the streamed batch that this one + // replaces. + self.materialize_kept_pairs(true)?; self.join_metrics.input_batches().add(1); self.join_metrics.input_rows().add(batch.num_rows()); // The runs, which the freeze emptied, keep their capacity. @@ -2255,6 +2331,9 @@ impl MaterializingSortMergeJoinStream { // 2. freezes NULLs joined to dequeued buffered batch to "release" it fn freeze_dequeuing_buffered(&mut self) -> Result<()> { self.freeze_streamed()?; + // Kept pairs address the buffered batches by position, which the dequeue + // shifts. + self.materialize_kept_pairs(true)?; // Only freeze and produce the first batch in buffered_data as the batch is fully processed self.freeze_buffered(1)?; @@ -2380,7 +2459,15 @@ impl MaterializingSortMergeJoinStream { return Ok(()); } - let frozen = self.materialize_pairs(runs, &summary)?; + let frozen = match self.materialize_pairs(runs, &summary)? { + Freeze::Frozen(frozen) => frozen, + Freeze::Kept(kept) => { + self.kept_pairs.append(runs, &kept); + return self.materialize_kept_pairs(false); + } + }; + // Pairs kept by earlier freezes precede these in the output. + self.materialize_kept_pairs(true)?; // 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 @@ -2434,11 +2521,15 @@ impl MaterializingSortMergeJoinStream { /// 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. + /// + /// When an Inner join filters first and its filter passes too few pairs to + /// make a batch on their own, it returns them as kept instead, to be + /// materialized with the pairs of later freezes. fn materialize_pairs( &self, runs: &[PairRun], summary: &RunsSummary, - ) -> Result { + ) -> Result { let num_pairs = summary.num_pairs; let streamed_rows = StreamedRows::new(runs, summary); let buffered_rows = self.buffered_rows(runs, summary)?; @@ -2458,11 +2549,9 @@ impl MaterializingSortMergeJoinStream { filter } _ => { - return self.materialize_all_pairs( - &streamed_rows, - &buffered_rows, - num_pairs, - ); + return self + .materialize_all_pairs(&streamed_rows, &buffered_rows, num_pairs) + .map(Freeze::Frozen); } }; @@ -2501,12 +2590,23 @@ impl MaterializingSortMergeJoinStream { passed.clone() }; let num_kept = kept.true_count(); + // The output coalescer would copy a batch of so few pairs again (see + // `new_output_coalescer`). + if !self.deferred_filtering + && self + .joined_record_batches + .joined_batches + .biggest_coalesce_batch_size() + .is_none_or(|limit| num_kept <= limit) + { + return Ok(Freeze::Kept(kept)); + } if num_kept == 0 { - return Ok(FrozenPairs { + return Ok(Freeze::Frozen(FrozenPairs { batch: RecordBatch::new_empty(Arc::clone(&self.schema)), metadata: None, passed: Some(passed), - }); + })); } // Filter the filter's columns once, and gather the other emitted columns @@ -2549,11 +2649,95 @@ impl MaterializingSortMergeJoinStream { } else { None }; - Ok(FrozenPairs { + Ok(Freeze::Frozen(FrozenPairs { batch, metadata, passed: Some(passed), - }) + })) + } + + /// Materializes the kept pairs in batches that complete the output + /// coalescer's partial batch, so that it passes later batches on without + /// copying them. With `flush`, the pairs left over join the partial batch. + fn materialize_kept_pairs(&mut self, flush: bool) -> Result<()> { + // The most rows that the coalescer copies into its partial batch, where + // it would pass more on as a partial batch of their own + let limit = self + .joined_record_batches + .joined_batches + .biggest_coalesce_batch_size() + .unwrap_or(self.batch_size); + while self.kept_pairs.num_pairs > 0 { + let room = self.batch_size + - self + .joined_record_batches + .joined_batches + .get_buffered_rows(); + let num_pairs = if self.kept_pairs.num_pairs >= room { + room + } else if flush { + self.kept_pairs.num_pairs.min(limit) + } else { + return Ok(()); + }; + debug_assert!(num_pairs > 0, "empty batch of kept pairs"); + // The last run that the batch reads, cut to the pairs it reads + let (mut end, mut covered) = (0, 0); + let runs = &mut self.kept_pairs.runs; + while covered + runs[end].len < num_pairs { + covered += runs[end].len; + end += 1; + } + let last = runs[end]; + let read = num_pairs - covered; + runs[end].len = read; + let batch = + self.materialize_runs(&self.kept_pairs.runs[..=end], num_pairs)?; + let runs = &mut self.kept_pairs.runs; + if read < last.len { + runs[end] = PairRun { + buffered_row: last.buffered_row + read, + len: last.len - read, + ..last + }; + runs.drain(..end); + } else { + runs.drain(..=end); + } + self.kept_pairs.num_pairs -= num_pairs; + self.joined_record_batches + .push_batch_without_metadata(batch); + } + Ok(()) + } + + /// The emitted columns of the `num_pairs` pairs of `runs`, each of which has + /// a buffered row. + fn materialize_runs( + &self, + runs: &[PairRun], + num_pairs: usize, + ) -> Result { + let summary = RunsSummary::new(runs, num_pairs); + // A projection can leave a side without emitted columns, whose rows are + // then not needed. + let streamed_columns = if self.streamed_columns.is_empty() { + vec![] + } else { + StreamedRows::new(runs, &summary) + .columns(&self.streamed_batch.batch, &self.streamed_columns)? + }; + let buffered_columns = if self.buffered_columns.is_empty() { + vec![] + } else { + self.buffered_rows(runs, &summary)? + .columns(&self.buffered_columns)? + }; + new_batch( + &self.schema, + self.join_columns(streamed_columns, buffered_columns), + num_pairs, + ) } /// Materializes every pair, then evaluates the join filter, if any, on them. 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 77e829a449325..7f8b0a2dc8d6a 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/tests.rs @@ -8909,3 +8909,106 @@ async fn join_inner_early_filtering_matches_hash_join() -> Result<()> { } Ok(()) } + +/// An Inner join whose filter keeps few pairs, as TPC-DS q72's does, holds the +/// pairs that pass over several freezes and materializes them a batch at a time. +/// Every streamed row of a key meets the key's 150 buffered rows, which the +/// 64-row buffered batches split, and `c2 * 10 < c1` keeps about 5% of the +/// pairs. So the kept pairs span many freezes, and they are pending when a +/// 25-row streamed batch ends and when a key's buffered batches are dequeued. +/// The output must be the rows of the unfiltered join that pass the filter, in +/// the same order, also when the buffered batches spill, and every batch but the +/// last must be full. Below `batch_size` 32, a freeze can keep more pairs than +/// the output coalescer copies, which then pass it as a batch of their own. +#[tokio::test] +async fn join_inner_selective_filter_materializes_kept_pairs_in_batches() -> Result<()> { + let (left_batches, left_schema) = + early_filtering_batches(["a1", "b1", "c1"], 5, |_| 40, 3, 25); + let (right_batches, right_schema) = + early_filtering_batches(["a2", "b2", "c2"], 5, |_| 150, 4, 64); + let on = early_filtering_on(&left_schema, &right_schema)?; + let expression = Arc::new(BinaryExpr::new( + Arc::new(BinaryExpr::new( + Arc::new(Column::new("c2", 0)), + Operator::Multiply, + Arc::new(Literal::new(ScalarValue::Int32(Some(10)))), + )), + Operator::Lt, + Arc::new(Column::new("c1", 1)), + )); + let filter = early_filter(expression, &["c2", "c1"], &left_schema, &right_schema); + let join = |filter| { + SortMergeJoinExec::try_new( + build_table_from_batches(left_batches.clone()), + build_table_from_batches(right_batches.clone()), + on.clone(), + filter, + Inner, + vec![SortOptions::default()], + NullEquality::NullEqualsNothing, + ) + }; + let unfiltered = join(None)?; + let filtered = join(Some(filter))?; + let spilling = RuntimeEnvBuilder::new() + .with_memory_limit(100, 1.0) + .with_disk_manager_builder( + DiskManagerBuilder::default().with_mode(DiskManagerMode::OsTmpDirectory), + ) + .build_arc()?; + for (batch_size, full_batches) in [(5, false), (32, true), (300, true), (8192, true)] + { + let config = SessionConfig::new().with_batch_size(batch_size); + let task_ctx = + Arc::new(TaskContext::default().with_session_config(config.clone())); + let pairs = arrow::compute::concat_batches( + &unfiltered.schema(), + &common::collect(unfiltered.execute(0, Arc::clone(&task_ctx))?).await?, + )?; + // Columns of the join schema `a1, b1, c1, a2, b2, c2` + let column = |i: usize| { + pairs + .column(i) + .as_any() + .downcast_ref::() + .unwrap() + .clone() + }; + let passed: BooleanArray = column(2) + .iter() + .zip(column(5).iter()) + .map(|pair| Some(matches!(pair, (Some(c1), Some(c2)) if c2 * 10 < c1))) + .collect(); + let expected = filter_record_batch(&pairs, &passed)?; + let percent_kept = 100 * expected.num_rows() / pairs.num_rows(); + assert!( + (1..10).contains(&percent_kept), + "{percent_kept}% of pairs kept" + ); + + let spilling_ctx = Arc::new( + TaskContext::default() + .with_session_config(config) + .with_runtime(Arc::clone(&spilling)), + ); + for ctx in [&task_ctx, &spilling_ctx] { + let output = common::collect(filtered.execute(0, Arc::clone(ctx))?).await?; + if full_batches { + let (last, others) = output.split_last().unwrap(); + assert!( + others.iter().all(|b| b.num_rows() == batch_size) + && last.num_rows() <= batch_size, + "batch sizes {:?} with batch_size {batch_size}", + output.iter().map(|b| b.num_rows()).collect::>() + ); + } + assert_eq!( + arrow::compute::concat_batches(&filtered.schema(), &output)?, + expected, + "batch_size {batch_size}" + ); + } + assert!(filtered.metrics().unwrap().spill_count().unwrap() > 0); + } + Ok(()) +} From 0259a3863d8b10f12a797021ae959c9c9f4b0c05 Mon Sep 17 00:00:00 2001 From: comphead Date: Fri, 4 Dec 2026 14:29:50 -0800 Subject: [PATCH 10/10] perf: append a sort-merge join's filter metadata as arrays `FilterMetadata::append_filter_metadata` extended its builders from the arrays' iterators. Arrow's `BooleanBuilder::extend` collects the values into a `Vec>` and builds a `BooleanArray` from it to append. After the previous commit, which changed the inlining, building that array took 5% of `left_1to1000_selective_filtered` in a profile. `append_array` copies the arrays' buffers instead. Against the previous commit, on macOS, `left_1to100_filtered` is 14% faster and `left_1to1000_selective_filtered` 10%, so both are now faster than before the previous two commits, by 10% and 5%. The Inner cases do not change. --- datafusion/physical-plan/src/joins/sort_merge_join/filter.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/datafusion/physical-plan/src/joins/sort_merge_join/filter.rs b/datafusion/physical-plan/src/joins/sort_merge_join/filter.rs index 0c1143549cdf3..6744951396f43 100644 --- a/datafusion/physical-plan/src/joins/sort_merge_join/filter.rs +++ b/datafusion/physical-plan/src/joins/sort_merge_join/filter.rs @@ -84,8 +84,8 @@ impl FilterMetadata { "row_indices and filter_mask must have same length" ); - self.filter_mask.extend(filter_mask); - self.row_indices.extend(row_indices); + self.filter_mask.append_array(filter_mask); + self.row_indices.append_array(row_indices); self.batch_ids .resize(self.batch_ids.len() + row_indices.len(), batch_id); }