This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11519-5c70030eaab45ea8427861ffcbe2dc95d2e118c8 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 1357f25f26ca67634e992bdb35220b4ee59c780f Author: RIchard Baah <[email protected]> AuthorDate: Tue Oct 20 01:16:17 2026 +0000 Implement `BatchCoalescer::push_batch_interleaved` (#11519) # Which issue does this PR close? <!-- It is not necessary to raise an issue, but it is encouraged if it is a non-trivial enhancement/bug. If this PR relates to an existing issue, but does not fully resolve it, please change the wording below from "Closes #NNN" to "Relates to #NNN" or "Part of #NNN" to avoid false closing an issue. --> - Closes #11141 # Rationale for this change see #11141 <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. Please try to explain the problem you are trying to solve in terms of the user-visible behavior, rather than the implementation. --> # What changes are included in this PR? adds stump for `push_batch_interleaved` that just uses `interleave` + `push_batch` for now just like `push_batch_indices` <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> # Are these changes tested? yes 2 new test that cover this code path <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests, if so identify these tests)? If this PR claims a performance improvement, please include evidence such as benchmark results. DO NOT simply paste a list of commands ran to verify the code; this is what our CI is for and it pollutes the PR. ONLY explain if testing was included with this PR, or why it wasn't. --> # Are there any significant user-facing changes? yes new public method on `batchCoalecer` <!-- Significant user-facing changes include: - Breaking public API change - Significant change to existing functionality (e.g. function returns something different) These need to be explicitly called out to ensure we have proper documentation if required and to ensure we follow proper semantic versioning. DO NOT restate the changes of this PR; if a bug was fixed and already explained above, we don't need this to be restated as a user-facing change. --> --- arrow-select/src/coalesce.rs | 95 ++++++++++++ arrow/benches/coalesce_kernels.rs | 293 +++++++++++++++++++++++++++++++------- 2 files changed, 335 insertions(+), 53 deletions(-) diff --git a/arrow-select/src/coalesce.rs b/arrow-select/src/coalesce.rs index 863d391829..6f5378a8f5 100644 --- a/arrow-select/src/coalesce.rs +++ b/arrow-select/src/coalesce.rs @@ -21,6 +21,7 @@ //! [`filter`]: crate::filter::filter //! [`take`]: crate::take::take use crate::filter::{FilterBuilder, FilterPredicate, FilterSelection}; +use crate::interleave::interleave_record_batch; use crate::take::take_record_batch; use arrow_array::types::{BinaryViewType, StringViewType}; use arrow_array::{Array, ArrayRef, BooleanArray, RecordBatch, downcast_primitive}; @@ -340,6 +341,49 @@ impl BatchCoalescer { self.push_batch(taken_batch) } + /// Push rows gathered from multiple `batches` into the Coalescer. + /// + /// Semantically equivalent to + /// [`interleave_record_batch`]`(batches, indices)` followed by + /// [`Self::push_batch`]. + /// + /// `indices` are `(batch_idx, row_idx)` pairs identifying the source of + /// each output row. + /// + /// # Example + /// ``` + /// # use arrow_array::record_batch; + /// # use arrow_select::coalesce::BatchCoalescer; + /// let batch1 = record_batch!(("a", Int32, [0, 1, 2])).unwrap(); + /// let batch2 = record_batch!(("a", Int32, [3, 4, 5])).unwrap(); + /// // (batch_idx, row_idx) pairs select rows across both batches + /// let indices = vec![(0, 0), (1, 2), (0, 2), (1, 0)]; + /// // create a new Coalescer that targets creating 1000 row batches + /// let mut coalescer = BatchCoalescer::new(batch1.schema(), 1000); + /// coalescer.push_batch_interleaved(&[batch1, batch2], &indices).unwrap(); + /// // finish and retrieve the created batch + /// coalescer.finish_buffered_batch().unwrap(); + /// let completed_batch = coalescer.next_completed_batch().unwrap(); + /// let expected_batch = record_batch!(("a", Int32, [0, 5, 2, 3])).unwrap(); + /// assert_eq!(completed_batch, expected_batch); + /// ``` + pub fn push_batch_interleaved( + &mut self, + batches: &[RecordBatch], + indices: &[(usize, usize)], + ) -> Result<(), ArrowError> { + if batches.is_empty() { + return Err(ArrowError::InvalidArgumentError( + "push_batch_interleaved requires at least one input batch".to_string(), + )); + } + + // todo: optimize this to avoid materializing the intermediate RecordBatch + let refs: Vec<&RecordBatch> = batches.iter().collect(); + let interleaved = interleave_record_batch(&refs, indices)?; + self.push_batch(interleaved) + } + /// Push all the rows from `batch` into the Coalescer /// /// When buffered data plus incoming rows reach `target_batch_size` , @@ -2727,6 +2771,57 @@ mod tests { assert_eq!(expected, actual); } + #[test] + fn test_push_batch_interleaved() { + let batch1 = record_batch!(("a", Int32, [10, 11, 12])).unwrap(); + let batch2 = record_batch!(("a", Int32, [20, 21, 22])).unwrap(); + let indices = [(0, 0), (1, 2), (0, 2), (1, 0)]; + + let mut coalescer = BatchCoalescer::new(batch1.schema(), 1000); + coalescer + .push_batch_interleaved(&[batch1, batch2], &indices) + .unwrap(); + coalescer.finish_buffered_batch().unwrap(); + + let expected = record_batch!(("a", Int32, [10, 22, 12, 20])).unwrap(); + assert_eq!(coalescer.next_completed_batch().unwrap(), expected); + } + + #[test] + fn test_push_batch_interleaved_matches_interleave_then_push() { + let batch1 = record_batch!(("a", Int32, [1, 2, 3, 4])).unwrap(); + let batch2 = record_batch!(("a", Int32, [5, 6, 7])).unwrap(); + let indices = [(1, 2), (0, 0), (1, 0), (0, 3), (1, 1)]; + + let mut via_method = BatchCoalescer::new(batch1.schema(), 1000); + via_method + .push_batch_interleaved(&[batch1.clone(), batch2.clone()], &indices) + .unwrap(); + via_method.finish_buffered_batch().unwrap(); + + let mut via_manual = BatchCoalescer::new(batch1.schema(), 1000); + let interleaved = interleave_record_batch(&[&batch1, &batch2], &indices).unwrap(); + via_manual.push_batch(interleaved).unwrap(); + via_manual.finish_buffered_batch().unwrap(); + + assert_eq!( + via_method.next_completed_batch().unwrap(), + via_manual.next_completed_batch().unwrap() + ); + } + + #[test] + fn test_push_batch_interleaved_rejects_empty_batches() { + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let mut coalescer = BatchCoalescer::new(schema, 1000); + + let err = coalescer.push_batch_interleaved(&[], &[]).unwrap_err(); + assert_eq!( + err.to_string(), + "Invalid argument error: push_batch_interleaved requires at least one input batch" + ); + } + #[test] fn test_push_batch_schema_mismatch_fewer_columns() { // Coalescer expects 0 columns, batch has 1 diff --git a/arrow/benches/coalesce_kernels.rs b/arrow/benches/coalesce_kernels.rs index dca87ea6cc..da62fa390c 100644 --- a/arrow/benches/coalesce_kernels.rs +++ b/arrow/benches/coalesce_kernels.rs @@ -383,7 +383,32 @@ fn add_all_filter_benchmarks(c: &mut Criterion) { } } +#[derive(Clone, Copy)] +enum GatherOperation { + Take, + Interleave, +} + +const NUM_INTERLEAVE_INPUT_BATCHES: usize = 4; + +impl GatherOperation { + fn name(self) -> &'static str { + match self { + Self::Take => "take", + Self::Interleave => "interleave", + } + } +} + fn add_all_take_benchmarks(c: &mut Criterion) { + add_all_gather_benchmarks(c, GatherOperation::Take); +} + +fn add_all_interleave_benchmarks(c: &mut Criterion) { + add_all_gather_benchmarks(c, GatherOperation::Interleave); +} + +fn add_all_gather_benchmarks(c: &mut Criterion, operation: GatherOperation) { let batch_size = 8192; let primitive_schema = SchemaRef::new(Schema::new(vec![ @@ -477,105 +502,106 @@ fn add_all_take_benchmarks(c: &mut Criterion) { for null_density in [0.0, 0.1] { for selectivity in [0.001, 0.01, 0.1, 0.8] { for scenario in [ - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "primitive", num_output_batches: 50, max_string_len: 30, schema: &primitive_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_utf8view", num_output_batches: 50, max_string_len: 30, schema: &single_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_binaryview", num_output_batches: 50, max_string_len: 30, schema: &single_binaryview_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "mixed_utf8view (max_string_len=20)", num_output_batches: 20, max_string_len: 20, schema: &mixed_utf8view_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "mixed_utf8view (max_string_len=128)", num_output_batches: 20, max_string_len: 128, schema: &mixed_utf8view_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "mixed_binaryview (max_string_len=20)", num_output_batches: 20, max_string_len: 20, schema: &mixed_binaryview_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "mixed_binaryview (max_string_len=128)", num_output_batches: 20, max_string_len: 128, schema: &mixed_binaryview_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_utf8", num_output_batches: 50, max_string_len: 30, schema: &single_utf8_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_binary", num_output_batches: 50, max_string_len: 30, schema: &single_binary_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "mixed_utf8", num_output_batches: 20, max_string_len: 30, schema: &mixed_utf8_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "mixed_dict", num_output_batches: 10, max_string_len: 30, schema: &mixed_dict_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_fsb16", num_output_batches: 50, max_string_len: 16, schema: &single_fsb16_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_fsb32", num_output_batches: 50, max_string_len: 32, schema: &single_fsb32_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_boolean", num_output_batches: 50, max_string_len: 0, schema: &single_boolean_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_fsl4", num_output_batches: 50, max_string_len: 0, schema: &single_fsl4_schema, }, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name: "single_list", num_output_batches: 50, max_string_len: 0, schema: &single_list_schema, }, ] { - TakeBenchmarkBuilder::from_scenario( + GatherBenchmarkBuilder::from_scenario( c, + operation, batch_size, null_density, selectivity, @@ -586,18 +612,19 @@ fn add_all_take_benchmarks(c: &mut Criterion) { } } - // Repeated indices make the taken batch much larger than the source batch, - // which exercises the materialized fallback path for unsupported schemas. + // Repeated indices make the gathered batch much larger than a source batch, + // which exercises the materialized path before coalescing. for (name, schema) in [ ("primitive extra_large_repeat", &primitive_schema), ("mixed_utf8 extra_large_repeat", &mixed_utf8_schema), ] { - TakeBenchmarkBuilder::from_scenario( + GatherBenchmarkBuilder::from_scenario( c, + operation, batch_size, 0.0, 1.0, - TakeBenchmarkScenario { + GatherBenchmarkScenario { name, num_output_batches: 64, max_string_len: 30, @@ -611,7 +638,12 @@ fn add_all_take_benchmarks(c: &mut Criterion) { } } -criterion_group!(benches, add_all_filter_benchmarks, add_all_take_benchmarks); +criterion_group!( + benches, + add_all_filter_benchmarks, + add_all_take_benchmarks, + add_all_interleave_benchmarks +); criterion_main!(benches); /// Run the filters with a batch_size, null_density, selectivity, and schema @@ -675,8 +707,9 @@ impl FilterBenchmarkBuilder<'_> { } } -struct TakeBenchmarkBuilder<'a> { +struct GatherBenchmarkBuilder<'a> { c: &'a mut Criterion, + operation: GatherOperation, name: &'a str, batch_size: usize, num_output_batches: usize, @@ -690,30 +723,32 @@ struct TakeBenchmarkBuilder<'a> { } #[derive(Clone, Copy)] -struct TakeBenchmarkScenario<'a> { +struct GatherBenchmarkScenario<'a> { name: &'a str, num_output_batches: usize, max_string_len: usize, schema: &'a SchemaRef, } -impl<'a> TakeBenchmarkBuilder<'a> { +impl<'a> GatherBenchmarkBuilder<'a> { fn from_scenario( c: &'a mut Criterion, + operation: GatherOperation, batch_size: usize, null_density: f32, selectivity: f32, - scenario: TakeBenchmarkScenario<'a>, - ) -> TakeBenchmarkBuilder<'a> { - let TakeBenchmarkScenario { + scenario: GatherBenchmarkScenario<'a>, + ) -> GatherBenchmarkBuilder<'a> { + let GatherBenchmarkScenario { name, num_output_batches, max_string_len, schema, } = scenario; - TakeBenchmarkBuilder { + GatherBenchmarkBuilder { c, + operation, name, batch_size, num_output_batches, @@ -745,6 +780,7 @@ impl<'a> TakeBenchmarkBuilder<'a> { fn build(self) { let Self { c, + operation, name, batch_size, num_output_batches, @@ -760,41 +796,66 @@ impl<'a> TakeBenchmarkBuilder<'a> { let output_len = index_output_len .unwrap_or_else(|| ((batch_size as f32) * selectivity).round().max(1.0) as usize); - let indices = match index_output_len { - Some(_) => IndexStreamBuilder::new() - .with_batch_size(batch_size) - .with_output_len(output_len) - .build(), - None => IndexStreamBuilder::new() - .with_batch_size(batch_size) - .with_selectivity(selectivity) - .build(), - }; - let data = DataStreamBuilder::new(Arc::clone(schema)) .with_batch_size(batch_size) .with_null_density(null_density) .with_max_string_len(max_string_len) .build(); + let operation_name = operation.name(); let id = if index_output_len.is_some() || biggest_coalesce_batch_size.is_some() { format!( - "take: {name}, input: {batch_size}, output: {output_len}, nulls: {null_density}, biggest: {biggest_coalesce_batch_size:?}" + "{operation_name}: {name}, input: {batch_size}, output: {output_len}, nulls: {null_density}, biggest: {biggest_coalesce_batch_size:?}" ) } else { - format!("take: {name}, {batch_size}, nulls: {null_density}, selectivity: {selectivity}") + format!( + "{operation_name}: {name}, {batch_size}, nulls: {null_density}, selectivity: {selectivity}" + ) }; - c.bench_function(&id, |b| { - b.iter(|| { - take_streams( - num_output_batches, - indices.clone(), - data.clone(), - biggest_coalesce_batch_size, - drain_all_completed_batches, - ); - }) - }); + + match operation { + GatherOperation::Take => { + let indices = match index_output_len { + Some(_) => IndexStreamBuilder::new() + .with_batch_size(batch_size) + .with_output_len(output_len) + .build(), + None => IndexStreamBuilder::new() + .with_batch_size(batch_size) + .with_selectivity(selectivity) + .build(), + }; + c.bench_function(&id, |b| { + b.iter(|| { + take_streams( + num_output_batches, + indices.clone(), + data.clone(), + biggest_coalesce_batch_size, + drain_all_completed_batches, + ); + }) + }); + } + GatherOperation::Interleave => { + let indices = InterleaveIndexStreamBuilder::new() + .with_batch_size(batch_size) + .with_num_input_batches(NUM_INTERLEAVE_INPUT_BATCHES) + .with_output_len(output_len) + .build(); + c.bench_function(&id, |b| { + b.iter(|| { + interleave_streams( + num_output_batches, + indices.clone(), + data.clone(), + biggest_coalesce_batch_size, + drain_all_completed_batches, + ); + }) + }); + } + } } } @@ -851,6 +912,36 @@ fn take_streams( } } +fn interleave_streams( + mut num_output_batches: usize, + mut index_stream: InterleaveIndexStream, + data_stream: DataStream, + biggest_coalesce_batch_size: Option<usize>, + drain_all_completed_batches: bool, +) { + let schema = data_stream.schema(); + let batch_size = data_stream.batch_size(); + let num_input_batches = index_stream.num_input_batches(); + let batches = data_stream + .batches + .get(..num_input_batches) + .expect("Not enough input batches for interleave benchmark"); + let mut coalescer = BatchCoalescer::new(Arc::clone(schema), batch_size) + .with_biggest_coalesce_batch_size(biggest_coalesce_batch_size); + + while num_output_batches > 0 { + let indices = index_stream.next_indices(); + coalescer.push_batch_interleaved(batches, indices).unwrap(); + if drain_all_completed_batches { + while num_output_batches > 0 && coalescer.next_completed_batch().is_some() { + num_output_batches -= 1; + } + } else if coalescer.next_completed_batch().is_some() { + num_output_batches -= 1; + } + } +} + /// Stream of filters to apply to a sequence of input RecordBatches /// /// This pre-computes a sequence of filters and then repeats it forever. @@ -867,6 +958,13 @@ struct IndexStream { batches: Arc<[UInt32Array]>, } +#[derive(Debug, Clone)] +struct InterleaveIndexStream { + index: usize, + num_input_batches: usize, + batches: Arc<[Vec<(usize, usize)>]>, +} + impl IndexStream { fn next_indices(&mut self) -> &UInt32Array { let current_index = self.index; @@ -880,6 +978,23 @@ impl IndexStream { } } +impl InterleaveIndexStream { + fn num_input_batches(&self) -> usize { + self.num_input_batches + } + + fn next_indices(&mut self) -> &[(usize, usize)] { + let current_index = self.index; + self.index += 1; + if self.index >= self.batches.len() { + self.index = 0; + } + self.batches + .get(current_index) + .expect("No more interleave index batches available") + } +} + impl FilterStream { pub fn next_filter(&mut self) -> &BooleanArray { let current_index = self.index; @@ -1002,6 +1117,61 @@ impl IndexStreamBuilder { } } +#[derive(Debug)] +struct InterleaveIndexStreamBuilder { + batch_size: usize, + num_batches: usize, + num_input_batches: usize, + output_len: usize, +} + +impl InterleaveIndexStreamBuilder { + fn new() -> Self { + Self { + batch_size: 8192, + num_batches: 11, + num_input_batches: NUM_INTERLEAVE_INPUT_BATCHES, + output_len: 4096, + } + } + + fn with_batch_size(mut self, batch_size: usize) -> Self { + self.batch_size = batch_size; + self + } + + fn with_num_input_batches(mut self, num_input_batches: usize) -> Self { + self.num_input_batches = num_input_batches; + self + } + + fn with_output_len(mut self, output_len: usize) -> Self { + self.output_len = output_len.max(1); + self + } + + fn build(self) -> InterleaveIndexStream { + let Self { + batch_size, + num_batches, + num_input_batches, + output_len, + } = self; + + let batches = (0..num_batches) + .map(|seed| { + create_interleave_indices(num_input_batches, batch_size, output_len, seed as u64) + }) + .collect::<Vec<_>>(); + + InterleaveIndexStream { + index: 0, + num_input_batches, + batches: Arc::from(batches), + } + } +} + fn create_index_array(input_len: usize, output_len: usize, seed: u64) -> UInt32Array { let mut rng = StdRng::seed_from_u64(seed); UInt32Array::from_iter_values( @@ -1009,6 +1179,23 @@ fn create_index_array(input_len: usize, output_len: usize, seed: u64) -> UInt32A ) } +fn create_interleave_indices( + num_input_batches: usize, + input_len: usize, + output_len: usize, + seed: u64, +) -> Vec<(usize, usize)> { + let mut rng = StdRng::seed_from_u64(seed); + (0..output_len) + .map(|_| { + ( + rng.random_range(0..num_input_batches), + rng.random_range(0..input_len), + ) + }) + .collect() +} + #[derive(Debug, Clone)] struct DataStream { schema: SchemaRef,
