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 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); } 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..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 @@ -9,14 +9,15 @@ //! *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; -use std::iter::repeat_n; 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, @@ -30,12 +31,17 @@ use crate::spill::spill_manager::SpillManager; use crate::stream::{EmptyRecordBatchStream, ObservedStream, RecordBatchStreamAdapter}; use crate::{PhysicalExpr, SendableRecordBatchStream}; -use arrow::array::{types::UInt64Type, *}; +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::{Schema, SchemaRef}; +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}; use datafusion_common::instant::Instant; @@ -50,27 +56,359 @@ 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, 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)] +pub(super) struct PairRun { + streamed_row: usize, + /// 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, + len: usize, +} + +impl PairRun { + /// 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, + } + } +} + +/// 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 +/// 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 { + num_pairs: usize, + /// The number of ranges of buffered rows, merging runs that continue each + /// 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 + batch_bounds: 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_pairs, + num_ranges: 0, + num_streamed_rows: 0, + batch_bounds: None, + nulls: false, + streamed_range: runs.len() == num_pairs, + }; + 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; + 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.batch_bounds = (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. `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], 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); + } + // 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, + _ => 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)) + } + + fn repeated(repeats: Vec<(usize, usize)>, num_rows: usize) -> Self { + Self::Repeated { + repeats, + num_rows, + indices: OnceCell::new(), + } + } + + /// 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; + } + 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(filter_indices(predicate, &indices)?)) + } + + /// The row of each pair + fn indices(&self) -> UInt64Array { + match self { + Self::Range(range) => range_indices(range.clone()), + 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(), + } + } + + /// 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, .. + } => 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(), + } } } +/// 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) +} + +/// 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 BufferedRange { + 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. `nulls` tells whether a + /// range has no source. + Ranges { + batches: Vec<&'a RecordBatch>, + ranges: Vec, + nulls: bool, + 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 +418,96 @@ enum BufferedRows<'a> { nulls: bool, indices: Vec<(usize, usize)>, }, + /// 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<'_> { + /// 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, filter_indices(predicate, &range_indices(range))?) + } + Self::Ranges { + batches, ranges, .. + } => { + let (kept_ranges, nulls) = filter_ranges(&ranges, kept); + ranges_or_gathered(batches, kept_ranges, nulls, num_kept) + } + Self::Batch(batch, indices) => { + Self::Batch(batch, filter_indices(predicate, &indices)?) + } + 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, + nulls, + num_rows, + } => { + // 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| 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) => { - 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 +533,326 @@ 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(), +/// 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: &[BufferedRange], + nulls: bool, + num_rows: usize, +) -> Result> { + let arrays: Vec<&ArrayRef> = batches.iter().map(|b| b.column(column)).collect(); + let array = arrays[0]; + 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, 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: &[BufferedRange], + nulls: bool, + 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) => values.extend_from_slice( + &arrays[source].values()[range.start..range.start + range.len], ), - 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, - } - } - all_passed => all_passed, + None => values.resize(values.len() + range.len, T::Native::default()), + } + } + 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(), nulls) + .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: &[BufferedRange], + nulls: bool, + num_rows: usize, +) -> Result { + let arrays: Vec<&GenericByteArray> = + arrays.iter().map(|a| a.as_bytes::()).collect(); + let value_offsets = |range: &BufferedRange| { + 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 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). + let offsets = unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) }; + Ok(Arc::new(unsafe { + GenericByteArray::::new_unchecked(offsets, values.into(), nulls) + })) } -/// 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, +/// 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( + source_nulls: &[Option<&NullBuffer>], + ranges: &[BufferedRange], + nulls: bool, + num_rows: usize, +) -> Option { + 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 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)) => { + let bits = source.inner(); + let start = bits.offset() + range.start; + validity.append_packed_range(start..start + range.len, bits.values()); + } + } + } + Some(NullBuffer::new(validity.finish())) +} + +/// 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) { + // 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.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; + } + nulls |= r.source.is_none(); + kept.push(BufferedRange { + start: r.start + (start - range_start), + len: end.min(range_end) - start, + ..*r + }); + if end <= range_end { + break; + } + start = range_end; + (range, range_start) = (ranges.next(), range_end); + } + } + (kept, nulls) +} + +/// `num_rows` rows of `batches`, in `ranges` whose sources index `batches`: +/// copied as ranges when they are long, and otherwise gathered row by row. +/// `nulls` tells whether a range has no source. +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, + nulls, + 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 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; + last = next; + } + 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(), + } +} + +/// 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, +} + +/// 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. @@ -165,12 +866,10 @@ 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 { @@ -180,9 +879,8 @@ impl StreamedBatch { batch, idx: 0, join_arrays, - output_indices: vec![], + runs: vec![], num_output_rows: 0, - buffered_batch_idx: None, }) } @@ -191,9 +889,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 +899,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_idx: 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_idx`. fn append_output_pairs( &mut self, buffered_batch_idx: usize, - buffered_start: usize, + buffered_row: 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, - 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_idx: Some(buffered_batch_idx), + buffered_row, + len, }); - self.buffered_batch_idx = buffered_batch_idx; + self.num_output_rows += len; } } @@ -379,12 +995,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 @@ -475,14 +1098,17 @@ 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`]). + /// 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. /// - /// 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 @@ -535,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` @@ -724,7 +1353,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, @@ -736,11 +1365,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, @@ -750,23 +1379,11 @@ 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 - } else { - 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| match &filter { - Some(f) if join_type == JoinType::Inner => f - .column_indices() - .iter() - .filter(|c| c.side == side) - .map(|c| c.index) - .collect(), - _ => vec![], - }; - let streamed_filter_columns = filter_columns(JoinSide::Left); - let buffered_filter_columns = filter_columns(JoinSide::Right); + 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| { @@ -799,11 +1416,31 @@ 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); + // Buffered batches keep only the gathered columns, in their order, once + // 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()) + { + 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()); for (column_index, field) in @@ -845,12 +1482,14 @@ impl MaterializingSortMergeJoinStream { buffered_gathered_columns, streamed_filter_columns, buffered_filter_columns, + buffered_projection, filter_first, filter, joined_record_batches: JoinedRecordBatches { 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, @@ -980,7 +1619,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 +1639,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(); } @@ -1158,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 @@ -1262,8 +1895,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_idx + && needed.last() != Some(&idx) + { needed.push(idx); } } @@ -1360,10 +1995,18 @@ 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()); - self.streamed_batch = - StreamedBatch::try_new(batch, &self.on_streamed)?; + // The runs, which the freeze emptied, keep their capacity. + let runs = take(&mut self.streamed_batch.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; @@ -1557,8 +2200,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); @@ -1612,8 +2259,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; } @@ -1680,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)?; @@ -1760,360 +2414,470 @@ 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.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, &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 = 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 + && let Some(passed) = &frozen.passed + { + let mut offset = 0; + for run in runs { + 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() { + 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 => self + .joined_record_batches + .push_batch_without_metadata(frozen.batch), + } 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 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. + /// + /// 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 { + 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 { + // 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 + && !(matches!(streamed_rows, StreamedRows::Range(_)) + && matches!( + buffered_rows, + BufferedRows::Range(..) | BufferedRows::Nulls(..) + )) + && (!self.deferred_filtering || num_pairs > runs.len()) => + { + filter + } + _ => { + return self + .materialize_all_pairs(&streamed_rows, &buffered_rows, num_pairs) + .map(Freeze::Frozen); + } }; - 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(); let mut buffered_arrays = buffered_filter_arrays.iter().cloned(); + let streamed_side = self.streamed_side(); 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(|| { + 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") + }) + } + _ => buffered_arrays.next().ok_or_else(|| { internal_datafusion_err!("missing buffered filter column") }), - JoinSide::None => internal_err!("Unexpected JoinSide::None in filter"), }) .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 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 { + 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(Freeze::Frozen(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(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(()) } - /// 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 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. + fn materialize_all_pairs( + &self, + 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 = self.filter.as_ref(); + 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 passed = evaluate_join_filter( + filter, + self.filter_schema.as_ref(), + 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 { + SortMergeJoinExec::probe_side(&self.join_type) + } + + /// 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` 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], + 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_pairs, + num_ranges, + batch_bounds, + nulls, + .. + } = *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( + 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 +2888,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" @@ -2150,43 +2910,43 @@ impl MaterializingSortMergeJoinStream { 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)); - } + 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_idx) { + 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 .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: 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: source_data, + ranges, + nulls, + num_rows: num_pairs, + } + } else { + // Gathering row by row needs no merged ranges. + let ranges = runs.iter().map(|run| source(run.buffered_range())); + gather_ranges(source_data, ranges, nulls, num_pairs) }) } @@ -2370,12 +3130,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 +3149,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,28 +3181,28 @@ 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()), - } +/// 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 03eeccd0e07b2..7f8b0a2dc8d6a 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,11 @@ use crate::{ }; use arrow::array::{ ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, DictionaryArray, - FixedSizeBinaryArray, Int32Array, RecordBatch, UInt64Array, + FixedSizeBinaryArray, Int8Array, Int32Array, RecordBatch, StringArray, UInt64Array, + new_null_array, }; 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; @@ -63,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; @@ -5395,9 +5397,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 +5539,188 @@ 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. 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( + ("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("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| { + 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 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(4) + .as_any() + .downcast_ref::() + .unwrap(); + 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, 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( + ("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 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(), + 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 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 /// 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 +5729,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![ @@ -8484,6 +8662,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)) = @@ -8495,6 +8675,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( @@ -8522,17 +8708,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); } } } @@ -8713,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(()) +} 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