Skip to main content

arrow_select/
coalesce.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`BatchCoalescer`]  concatenates multiple [`RecordBatch`]es after
6//! operations such as [`filter`] and [`take`].
7//!
8//! [`filter`]: crate::filter::filter
9//! [`take`]: crate::take::take
10use crate::filter::{FilterBuilder, FilterPredicate, FilterSelection};
11use crate::interleave::interleave_record_batch;
12use crate::take::{
13    TakeOptions, check_bounds, take, take_arrays_unchecked, take_bits, take_record_batch,
14};
15use arrow_array::types::{
16    BinaryViewType, GenericBinaryType, GenericStringType, StringViewType, UInt32Type,
17};
18use arrow_array::{Array, ArrayRef, BooleanArray, RecordBatch, UInt32Array, downcast_primitive};
19use arrow_buffer::{NullBuffer, NullBufferBuilder};
20use arrow_schema::{ArrowError, DataType, SchemaRef};
21use std::collections::VecDeque;
22use std::sync::Arc;
23// Originally From DataFusion's coalesce module:
24// https://github.com/apache/datafusion/blob/9d2f04996604e709ee440b65f41e7b882f50b788/datafusion/physical-plan/src/coalesce/mod.rs#L26-L25
25
26mod boolean;
27mod byte;
28mod byte_view;
29mod dictionary;
30mod fixed_size_binary;
31mod generic;
32mod list;
33mod primitive;
34
35use boolean::InProgressBooleanArray;
36use byte::InProgressByteArray;
37use byte_view::InProgressByteViewArray;
38use dictionary::create_in_progress_dictionary;
39use fixed_size_binary::InProgressFixedSizeBinaryArray;
40use generic::GenericInProgressArray;
41use list::InProgressListArray;
42use primitive::InProgressPrimitiveArray;
43
44/// Appends the validity bits selected by `indices` to `nulls`.
45///
46/// # Safety
47///
48/// `indices` must not contain nulls, and every value must be less than
49/// `source_nulls.len()`.
50pub(crate) unsafe fn append_gathered_nulls(
51    nulls: &mut NullBufferBuilder,
52    source_nulls: &NullBuffer,
53    indices: &UInt32Array,
54) {
55    debug_assert!(
56        indices
57            .values()
58            .iter()
59            .all(|&idx| (idx as usize) < source_nulls.len()),
60        "append_gathered_nulls received out-of-bounds index",
61    );
62    if source_nulls.null_count() == 0 {
63        nulls.append_n_non_nulls(indices.len());
64        return;
65    }
66    let gathered = take_bits::<UInt32Type, false>(source_nulls.inner(), indices);
67    nulls.append_buffer(&NullBuffer::new(gathered));
68}
69
70fn has_sparse_filter_copy(data_type: &DataType) -> bool {
71    data_type.is_primitive()
72        || matches!(
73            data_type,
74            DataType::Boolean
75                | DataType::Utf8
76                | DataType::LargeUtf8
77                | DataType::Binary
78                | DataType::LargeBinary
79                // Unlike offset-based byte arrays, views can reuse their backing buffers.
80                | DataType::Utf8View
81                | DataType::BinaryView
82                | DataType::List(_)
83                | DataType::LargeList(_)
84        )
85}
86
87/// Maximum selected row fraction for the fused sparse-filter copy path.
88///
89/// Shared benchmark results show this path helps low-selectivity filters, but
90/// can regress once the filter becomes denser. Keep this as a cheap integer
91/// threshold on the hot path: `selected_count <= filter_len / 16`.
92const SPARSE_FILTER_COPY_MAX_SELECTIVITY_DENOMINATOR: usize = 16;
93
94fn should_use_sparse_filter_copy(filter_len: usize, selected_count: usize) -> bool {
95    selected_count <= filter_len / SPARSE_FILTER_COPY_MAX_SELECTIVITY_DENOMINATOR
96}
97
98// Variable-width byte arrays only outperform the materialized filter kernel at
99// very low selection densities.
100const BYTE_ARRAY_DIRECT_COPY_MAX_SELECTIVITY_DENOMINATOR: usize = 1024;
101
102fn should_use_byte_array_direct_copy(filter_len: usize, selected_count: usize) -> bool {
103    selected_count <= filter_len / BYTE_ARRAY_DIRECT_COPY_MAX_SELECTIVITY_DENOMINATOR
104}
105
106// Dense selections are faster through `take`.
107const INDEXED_COPY_MAX_SELECTIVITY_DENOMINATOR: usize = 2;
108
109// Byte-view indexed copying is only faster for sparse selections.
110const BYTE_VIEW_INDEXED_COPY_MAX_SELECTIVITY_DENOMINATOR: usize = 16;
111
112fn should_use_indexed_copy(input_rows: usize, selected_rows: usize) -> bool {
113    selected_rows <= input_rows / INDEXED_COPY_MAX_SELECTIVITY_DENOMINATOR
114}
115
116fn should_use_byte_view_indexed_copy(input_rows: usize, selected_rows: usize) -> bool {
117    selected_rows <= input_rows / BYTE_VIEW_INDEXED_COPY_MAX_SELECTIVITY_DENOMINATOR
118}
119
120/// Concatenate multiple [`RecordBatch`]es
121///
122/// Implements the common pattern of incrementally creating output
123/// [`RecordBatch`]es of a specific size from an input stream of
124/// [`RecordBatch`]es.
125///
126/// This is useful after operations such as [`filter`] and [`take`] that produce
127/// smaller batches, and we want to coalesce them into larger batches for
128/// further processing.
129///
130/// # Motivation
131///
132/// If we use [`concat_batches`] to implement the same functionality, there are 2 potential issues:
133/// 1. At least 2x peak memory (holding the input and output of concat)
134/// 2. 2 copies of the data (to create the output of filter and then create the output of concat)
135///
136/// See: <https://github.com/apache/arrow-rs/issues/6692> for more discussions
137/// about the motivation.
138///
139/// [`filter`]: crate::filter::filter
140/// [`take`]: crate::take::take
141/// [`concat_batches`]: crate::concat::concat_batches
142///
143/// # Example
144/// ```
145/// use arrow_array::record_batch;
146/// use arrow_select::coalesce::{BatchCoalescer};
147/// let batch1 = record_batch!(("a", Int32, [1, 2, 3])).unwrap();
148/// let batch2 = record_batch!(("a", Int32, [4, 5])).unwrap();
149///
150/// // Create a `BatchCoalescer` that will produce batches with at least 4 rows
151/// let target_batch_size = 4;
152/// let mut coalescer = BatchCoalescer::new(batch1.schema(), 4);
153///
154/// // push the batches
155/// coalescer.push_batch(batch1).unwrap();
156/// // only pushed 3 rows (not yet 4, enough to produce a batch)
157/// assert!(coalescer.next_completed_batch().is_none());
158/// coalescer.push_batch(batch2).unwrap();
159/// // now we have 5 rows, so we can produce a batch
160/// let finished = coalescer.next_completed_batch().unwrap();
161/// // 4 rows came out (target batch size is 4)
162/// let expected = record_batch!(("a", Int32, [1, 2, 3, 4])).unwrap();
163/// assert_eq!(finished, expected);
164///
165/// // Have no more input, but still have an in-progress batch
166/// assert!(coalescer.next_completed_batch().is_none());
167/// // We can finish the batch, which will produce the remaining rows
168/// coalescer.finish_buffered_batch().unwrap();
169/// let expected = record_batch!(("a", Int32, [5])).unwrap();
170/// assert_eq!(coalescer.next_completed_batch().unwrap(), expected);
171///
172/// // The coalescer is now empty
173/// assert!(coalescer.next_completed_batch().is_none());
174/// ```
175///
176/// # Background
177///
178/// Generally speaking, larger [`RecordBatch`]es are more efficient to process
179/// than smaller [`RecordBatch`]es (until the CPU cache is exceeded) because
180/// there is fixed processing overhead per batch. This coalescer builds up these
181/// larger batches incrementally.
182///
183/// ```text
184/// ┌────────────────────┐
185/// │    RecordBatch     │
186/// │   num_rows = 100   │
187/// └────────────────────┘                 ┌────────────────────┐
188///                                        │                    │
189/// ┌────────────────────┐     Coalesce    │                    │
190/// │                    │      Batches    │                    │
191/// │    RecordBatch     │                 │                    │
192/// │   num_rows = 200   │  ─ ─ ─ ─ ─ ─ ▶  │                    │
193/// │                    │                 │    RecordBatch     │
194/// │                    │                 │   num_rows = 400   │
195/// └────────────────────┘                 │                    │
196///                                        │                    │
197/// ┌────────────────────┐                 │                    │
198/// │                    │                 │                    │
199/// │    RecordBatch     │                 │                    │
200/// │   num_rows = 100   │                 └────────────────────┘
201/// │                    │
202/// └────────────────────┘
203/// ```
204///
205/// # Notes:
206///
207/// 1. Output rows are produced in the same order as the input rows
208///
209/// 2. The output is a sequence of batches, with all but the last being at exactly
210///    `target_batch_size` rows.
211#[derive(Debug)]
212pub struct BatchCoalescer {
213    /// The input schema
214    schema: SchemaRef,
215    /// The target batch size (and thus size for views allocation). This is a
216    /// hard limit: the output batch will be exactly `target_batch_size`,
217    /// rather than possibly being slightly above.
218    target_batch_size: usize,
219    /// In-progress arrays
220    in_progress_arrays: Vec<Box<dyn InProgressArray>>,
221    /// True if some column still needs the materialized filter path.
222    has_non_specialized_filter_columns: bool,
223    /// True if the schema contains a variable-width byte-array column.
224    has_byte_array_columns: bool,
225    /// True if some column uses the byte-view indexed-copy path.
226    has_byte_view_columns: bool,
227    /// Buffered row count. Always less than `batch_size`
228    buffered_rows: usize,
229    /// Completed batches
230    completed: VecDeque<RecordBatch>,
231    /// Biggest coalesce batch size. See [`Self::with_biggest_coalesce_batch_size`]
232    biggest_coalesce_batch_size: Option<usize>,
233}
234
235impl BatchCoalescer {
236    /// Create a new `BatchCoalescer`
237    ///
238    /// # Arguments
239    /// - `schema` - the schema of the output batches
240    /// - `target_batch_size` - the number of rows in each output batch.
241    ///   Typical values are `4096` or `8192` rows.
242    ///
243    pub fn new(schema: SchemaRef, target_batch_size: usize) -> Self {
244        let has_non_specialized_filter_columns = schema
245            .fields()
246            .iter()
247            .any(|field| !has_sparse_filter_copy(field.data_type()));
248        let has_byte_array_columns = schema.fields().iter().any(|field| {
249            matches!(
250                field.data_type(),
251                DataType::Utf8 | DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary
252            )
253        });
254        let has_byte_view_columns = schema
255            .fields()
256            .iter()
257            .any(|field| matches!(field.data_type(), DataType::Utf8View | DataType::BinaryView));
258        let in_progress_arrays = schema
259            .fields()
260            .iter()
261            .map(|field| create_in_progress_array(field.data_type(), target_batch_size))
262            .collect::<Vec<_>>();
263
264        Self {
265            schema,
266            target_batch_size,
267            in_progress_arrays,
268            has_non_specialized_filter_columns,
269            has_byte_array_columns,
270            has_byte_view_columns,
271            // We will for sure store at least one completed batch
272            completed: VecDeque::with_capacity(1),
273            buffered_rows: 0,
274            biggest_coalesce_batch_size: None,
275        }
276    }
277
278    /// Set the coalesce batch size limit (default `None`)
279    ///
280    /// This limit determine when batches should bypass coalescing. Intuitively,
281    /// batches that are already large are costly to coalesce and are efficient
282    /// enough to process directly without coalescing.
283    ///
284    /// If `Some(limit)`, batches larger than this limit will bypass coalescing
285    /// when there is no buffered data, or when the previously buffered data
286    /// already exceeds this limit.
287    ///
288    /// If `None`, all batches will be coalesced according to the
289    /// target_batch_size.
290    pub fn with_biggest_coalesce_batch_size(mut self, limit: Option<usize>) -> Self {
291        self.biggest_coalesce_batch_size = limit;
292        self
293    }
294
295    /// Get the current biggest coalesce batch size limit
296    ///
297    /// See [`Self::with_biggest_coalesce_batch_size`] for details
298    pub fn biggest_coalesce_batch_size(&self) -> Option<usize> {
299        self.biggest_coalesce_batch_size
300    }
301
302    /// Set the biggest coalesce batch size limit
303    ///
304    /// See [`Self::with_biggest_coalesce_batch_size`] for details
305    pub fn set_biggest_coalesce_batch_size(&mut self, limit: Option<usize>) {
306        self.biggest_coalesce_batch_size = limit;
307    }
308
309    /// Return the schema of the output batches
310    pub fn schema(&self) -> SchemaRef {
311        Arc::clone(&self.schema)
312    }
313
314    /// Push a batch into the Coalescer after applying a filter
315    ///
316    /// This is semantically equivalent of calling [`Self::push_batch`]
317    /// with the results from [`crate::filter::filter_record_batch`]
318    ///
319    /// If the number of rows that `filter` selects is already known,
320    /// [`Self::push_batch_with_filter_builder`] with
321    /// [`FilterBuilder::with_count`] avoids counting them again.
322    ///
323    /// # Example
324    /// ```
325    /// # use arrow_array::{record_batch, BooleanArray};
326    /// # use arrow_select::coalesce::BatchCoalescer;
327    /// let batch1 = record_batch!(("a", Int32, [1, 2, 3])).unwrap();
328    /// let batch2 = record_batch!(("a", Int32, [4, 5, 6])).unwrap();
329    /// // Apply a filter to each batch to pick the first and last row
330    /// let filter = BooleanArray::from(vec![true, false, true]);
331    /// // create a new Coalescer that targets creating 1000 row batches
332    /// let mut coalescer = BatchCoalescer::new(batch1.schema(), 1000);
333    /// coalescer.push_batch_with_filter(batch1, &filter);
334    /// coalescer.push_batch_with_filter(batch2, &filter);
335    /// // finish and retrieve the created batch
336    /// coalescer.finish_buffered_batch().unwrap();
337    /// let completed_batch = coalescer.next_completed_batch().unwrap();
338    /// // filtered out 2 and 5:
339    /// let expected_batch = record_batch!(("a", Int32, [1, 3, 4, 6])).unwrap();
340    /// assert_eq!(completed_batch, expected_batch);
341    /// ```
342    pub fn push_batch_with_filter(
343        &mut self,
344        batch: RecordBatch,
345        filter: &BooleanArray,
346    ) -> Result<(), ArrowError> {
347        self.push_batch_with_filter_builder(batch, FilterBuilder::new(filter))
348    }
349
350    /// Push a batch into the Coalescer after applying the filter described by
351    /// `filter_builder`.
352    ///
353    /// This is [`Self::push_batch_with_filter`] for a [`FilterBuilder`] the
354    /// caller has already created. For example, callers that already know how
355    /// many rows the filter selects can provide that number with
356    /// [`FilterBuilder::with_count`] so that it is not counted again.
357    ///
358    /// Callers do not need to call [`FilterBuilder::optimize`]: like
359    /// [`Self::push_batch_with_filter`], this optimizes the filter when `batch`
360    /// has more than one column, or one column for which
361    /// [`FilterBuilder::is_optimize_beneficial`] returns true. A filter the
362    /// caller already optimized stays optimized.
363    ///
364    /// # Example
365    /// ```
366    /// # use arrow_array::{record_batch, BooleanArray};
367    /// # use arrow_select::coalesce::BatchCoalescer;
368    /// # use arrow_select::filter::FilterBuilder;
369    /// let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap();
370    /// let filter = BooleanArray::from(vec![true, false, true]);
371    /// // SAFETY: the filter selects two rows
372    /// let filter_builder = unsafe { FilterBuilder::new(&filter).with_count(2) };
373    /// let mut coalescer = BatchCoalescer::new(batch.schema(), 1000);
374    /// coalescer.push_batch_with_filter_builder(batch, filter_builder).unwrap();
375    /// coalescer.finish_buffered_batch().unwrap();
376    /// let expected_batch = record_batch!(("a", Int32, [1, 3])).unwrap();
377    /// assert_eq!(coalescer.next_completed_batch().unwrap(), expected_batch);
378    /// ```
379    pub fn push_batch_with_filter_builder(
380        &mut self,
381        batch: RecordBatch,
382        filter_builder: FilterBuilder,
383    ) -> Result<(), ArrowError> {
384        let predicate = Self::filter_predicate_for_batch(&batch, filter_builder);
385        self.push_batch_with_filtered_columns(batch, &predicate)
386    }
387
388    /// Push a batch into the Coalescer after applying a set of indices
389    /// This is semantically equivalent of calling [`Self::push_batch`]
390    /// with the results from  [`take_record_batch`]
391    ///
392    /// Returns `Err(ArrowError::InvalidArgumentError)` if `indices` is a
393    /// non-null `UInt32Array` with any out-of-bounds value.
394    ///
395    /// Non-null `UInt32Array` indices may use a direct-copy fast path; other
396    /// supported index arrays use [`take_record_batch`] instead.
397    ///
398    /// # Example
399    /// ```
400    /// # use arrow_array::{record_batch, UInt32Array};
401    /// # use arrow_select::coalesce::BatchCoalescer;
402    /// let batch1 = record_batch!(("a", Int32, [0, 0, 0])).unwrap();
403    /// let batch2 = record_batch!(("a", Int32, [1, 1, 4, 5, 1, 4])).unwrap();
404    /// // Sorted indices to create a sorted output, this can be obtained with
405    /// // `arrow-ord`'s sort_to_indices operation
406    /// let indices = UInt32Array::from(vec![0, 1, 4, 2, 5, 3]);
407    /// // create a new Coalescer that targets creating 1000 row batches
408    /// let mut coalescer = BatchCoalescer::new(batch1.schema(), 1000);
409    /// coalescer.push_batch(batch1);
410    /// coalescer.push_batch_with_indices(batch2, &indices);
411    /// // finish and retrieve the created batch
412    /// coalescer.finish_buffered_batch().unwrap();
413    /// let completed_batch = coalescer.next_completed_batch().unwrap();
414    /// let expected_batch = record_batch!(("a", Int32, [0, 0, 0, 1, 1, 1, 4, 4, 5])).unwrap();
415    /// assert_eq!(completed_batch, expected_batch);
416    /// ```
417    pub fn push_batch_with_indices(
418        &mut self,
419        batch: RecordBatch,
420        indices: &dyn Array,
421    ) -> Result<(), ArrowError> {
422        let u32_indices = indices
423            .as_any()
424            .downcast_ref::<UInt32Array>()
425            .filter(|array| array.null_count() == 0);
426        if let Some(u32_arr) = u32_indices {
427            check_bounds(batch.num_rows(), u32_arr)?;
428        }
429
430        // Direct indexed copying is a fast path for non-null UInt32 selections
431        // that are sparse enough for every column (with a stricter ByteView
432        // threshold). It is only equivalent to `push_batch(take(...))` when the
433        // materialized batch would not trigger the configured large-batch bypass.
434        let exceeds_byte_view_threshold = self.has_byte_view_columns
435            && !should_use_byte_view_indexed_copy(batch.num_rows(), indices.len());
436        let indexed_copy_allowed = should_use_indexed_copy(batch.num_rows(), indices.len())
437            && !exceeds_byte_view_threshold;
438
439        let fast_path_allowed = self
440            .biggest_coalesce_batch_size
441            .is_none_or(|limit| indices.len() <= limit);
442        if indexed_copy_allowed
443            && fast_path_allowed
444            && let Some(u32_arr) = u32_indices
445        {
446            return self.push_batch_with_index(batch, u32_arr);
447        }
448
449        let taken_batch = if let Some(u32_arr) = u32_indices {
450            // SAFETY: `u32_arr` was bounds-checked against `batch.num_rows()` above,
451            // which is the length of every column in the record batch.
452            let columns = unsafe { take_arrays_unchecked(batch.columns(), u32_arr)? };
453            // SAFETY: `take_arrays_unchecked` returns one array of `u32_arr.len()` rows
454            // for every field in `batch.schema()`.
455            unsafe { RecordBatch::new_unchecked(batch.schema(), columns, u32_arr.len()) }
456        } else {
457            take_record_batch(&batch, indices)?
458        };
459        self.push_batch(taken_batch)
460    }
461
462    fn push_batch_with_index(
463        &mut self,
464        batch: RecordBatch,
465        indices: &UInt32Array,
466    ) -> Result<(), ArrowError> {
467        if indices.is_empty() {
468            return Ok(());
469        }
470        let columns = batch.columns();
471        if columns.len() != self.in_progress_arrays.len() {
472            return Err(ArrowError::InvalidArgumentError(format!(
473                "Batch has {} columns but BatchCoalescer expects {}",
474                columns.len(),
475                self.in_progress_arrays.len()
476            )));
477        }
478        debug_assert!(
479            indices.null_count() == 0
480                && indices
481                    .values()
482                    .iter()
483                    .all(|&idx| (idx as usize) < batch.num_rows()),
484            "push_batch_with_index requires caller-validated non-null, in-bounds indices",
485        );
486
487        let mut offset = 0;
488        while offset < indices.len() {
489            let room = self.target_batch_size - self.buffered_rows;
490            let take_n = (indices.len() - offset).min(room);
491            let sliced;
492            let chunk: &UInt32Array = if offset == 0 && take_n == indices.len() {
493                indices
494            } else {
495                sliced = indices.slice(offset, take_n);
496                &sliced
497            };
498            for (in_progress, column) in self.in_progress_arrays.iter_mut().zip(columns) {
499                // SAFETY: `push_batch_with_indices` validated every index against
500                // `batch.num_rows()`, which equals `column.len()`, and slicing the
501                // validated indices preserves both bounds and validity.
502                unsafe { in_progress.copy_rows_by_indices(column, chunk)? };
503            }
504            self.buffered_rows += take_n;
505            offset += take_n;
506            if self.buffered_rows >= self.target_batch_size {
507                self.finish_buffered_batch()?;
508            }
509        }
510        Ok(())
511    }
512
513    /// Push rows gathered from multiple `batches` into the Coalescer.
514    ///
515    /// Semantically equivalent to
516    /// [`interleave_record_batch`]`(batches, indices)` followed by
517    /// [`Self::push_batch`].
518    ///
519    /// `indices` are `(batch_idx, row_idx)` pairs identifying the source of
520    /// each output row.
521    ///
522    /// # Example
523    /// ```
524    /// # use arrow_array::record_batch;
525    /// # use arrow_select::coalesce::BatchCoalescer;
526    /// let batch1 = record_batch!(("a", Int32, [0, 1, 2])).unwrap();
527    /// let batch2 = record_batch!(("a", Int32, [3, 4, 5])).unwrap();
528    /// // (batch_idx, row_idx) pairs select rows across both batches
529    /// let indices = vec![(0, 0), (1, 2), (0, 2), (1, 0)];
530    /// // create a new Coalescer that targets creating 1000 row batches
531    /// let mut coalescer = BatchCoalescer::new(batch1.schema(), 1000);
532    /// coalescer.push_batch_interleaved(&[batch1, batch2], &indices).unwrap();
533    /// // finish and retrieve the created batch
534    /// coalescer.finish_buffered_batch().unwrap();
535    /// let completed_batch = coalescer.next_completed_batch().unwrap();
536    /// let expected_batch = record_batch!(("a", Int32, [0, 5, 2, 3])).unwrap();
537    /// assert_eq!(completed_batch, expected_batch);
538    /// ```
539    pub fn push_batch_interleaved(
540        &mut self,
541        batches: &[RecordBatch],
542        indices: &[(usize, usize)],
543    ) -> Result<(), ArrowError> {
544        if batches.is_empty() {
545            return Err(ArrowError::InvalidArgumentError(
546                "push_batch_interleaved requires at least one input batch".to_string(),
547            ));
548        }
549
550        // todo: optimize this to avoid materializing the intermediate RecordBatch
551        let refs: Vec<&RecordBatch> = batches.iter().collect();
552        let interleaved = interleave_record_batch(&refs, indices)?;
553        self.push_batch(interleaved)
554    }
555
556    /// Push all the rows from `batch` into the Coalescer
557    ///
558    /// When buffered data plus incoming rows reach `target_batch_size` ,
559    /// completed batches are generated eagerly and can be retrieved via
560    /// [`Self::next_completed_batch()`].
561    /// Output batches contain exactly `target_batch_size` rows, so the tail of
562    /// the input batch may remain buffered.
563    /// Remaining partial data either waits for future input batches or can be
564    /// materialized immediately by calling [`Self::finish_buffered_batch()`].
565    ///
566    /// # Example
567    /// ```
568    /// # use arrow_array::record_batch;
569    /// # use arrow_select::coalesce::BatchCoalescer;
570    /// let batch1 = record_batch!(("a", Int32, [1, 2, 3])).unwrap();
571    /// let batch2 = record_batch!(("a", Int32, [4, 5, 6])).unwrap();
572    /// // create a new Coalescer that targets creating 1000 row batches
573    /// let mut coalescer = BatchCoalescer::new(batch1.schema(), 1000);
574    /// coalescer.push_batch(batch1);
575    /// coalescer.push_batch(batch2);
576    /// // finish and retrieve the created batch
577    /// coalescer.finish_buffered_batch().unwrap();
578    /// let completed_batch = coalescer.next_completed_batch().unwrap();
579    /// let expected_batch = record_batch!(("a", Int32, [1, 2, 3, 4, 5, 6])).unwrap();
580    /// assert_eq!(completed_batch, expected_batch);
581    /// ```
582    pub fn push_batch(&mut self, batch: RecordBatch) -> Result<(), ArrowError> {
583        // Large batch bypass optimization:
584        // When biggest_coalesce_batch_size is configured and a batch exceeds this limit,
585        // we can avoid expensive split-and-merge operations by passing it through directly.
586        //
587        // IMPORTANT: This optimization is OPTIONAL and only active when biggest_coalesce_batch_size
588        // is explicitly set via with_biggest_coalesce_batch_size(Some(limit)).
589        // If not set (None), ALL batches follow normal coalescing behavior regardless of size.
590
591        // =============================================================================
592        // CASE 1: No buffer + large batch → Direct bypass
593        // =============================================================================
594        // Example scenario (target_batch_size=1000, biggest_coalesce_batch_size=Some(500)):
595        // Input sequence: [600, 1200, 300]
596        //
597        // With biggest_coalesce_batch_size=Some(500) (optimization enabled):
598        //   600 → large batch detected! buffered_rows=0 → Case 1: direct bypass
599        //        → output: [600] (bypass, preserves large batch)
600        //   1200 → large batch detected! buffered_rows=0 → Case 1: direct bypass
601        //         → output: [1200] (bypass, preserves large batch)
602        //   300 → normal batch, buffer: [300]
603        //   Result: [600], [1200], [300] - large batches preserved, mixed sizes
604
605        // =============================================================================
606        // CASE 2: Buffer too large + large batch → Flush first, then bypass
607        // =============================================================================
608        // This case prevents creating extremely large merged batches that would
609        // significantly exceed both target_batch_size and biggest_coalesce_batch_size.
610        //
611        // Example 1: Buffer exceeds limit before large batch arrives
612        // target_batch_size=1000, biggest_coalesce_batch_size=Some(400)
613        // Input: [350, 200, 800]
614        //
615        // Step 1: push_batch([350])
616        //   → batch_size=350 <= 400, normal path
617        //   → buffer: [350], buffered_rows=350
618        //
619        // Step 2: push_batch([200])
620        //   → batch_size=200 <= 400, normal path
621        //   → buffer: [350, 200], buffered_rows=550
622        //
623        // Step 3: push_batch([800])
624        //   → batch_size=800 > 400, large batch path
625        //   → buffered_rows=550 > 400 → Case 2: flush first
626        //   → flush: output [550] (combined [350, 200])
627        //   → then bypass: output [800]
628        //   Result: [550], [800] - buffer flushed to prevent oversized merge
629        //
630        // Example 2: Multiple small batches accumulate before large batch
631        // target_batch_size=1000, biggest_coalesce_batch_size=Some(300)
632        // Input: [150, 100, 80, 900]
633        //
634        // Step 1-3: Accumulate small batches
635        //   150 → buffer: [150], buffered_rows=150
636        //   100 → buffer: [150, 100], buffered_rows=250
637        //   80  → buffer: [150, 100, 80], buffered_rows=330
638        //
639        // Step 4: push_batch([900])
640        //   → batch_size=900 > 300, large batch path
641        //   → buffered_rows=330 > 300 → Case 2: flush first
642        //   → flush: output [330] (combined [150, 100, 80])
643        //   → then bypass: output [900]
644        //   Result: [330], [900] - prevents merge into [1230] which would be too large
645
646        // =============================================================================
647        // CASE 3: Small buffer + large batch → Normal coalescing (no bypass)
648        // =============================================================================
649        // When buffer is small enough, we still merge to maintain efficiency
650        // Example: target_batch_size=1000, biggest_coalesce_batch_size=Some(500)
651        // Input: [300, 1200]
652        //
653        // Step 1: push_batch([300])
654        //   → batch_size=300 <= 500, normal path
655        //   → buffer: [300], buffered_rows=300
656        //
657        // Step 2: push_batch([1200])
658        //   → batch_size=1200 > 500, large batch path
659        //   → buffered_rows=300 <= 500 → Case 3: normal merge
660        //   → buffer: [300, 1200] (1500 total)
661        //   → 1500 > target_batch_size → split: output [1000], buffer [500]
662        //   Result: [1000], [500] - normal split/merge behavior maintained
663
664        // =============================================================================
665        // Comparison: Default vs Optimized Behavior
666        // =============================================================================
667        // target_batch_size=1000, biggest_coalesce_batch_size=Some(500)
668        // Input: [600, 1200, 300]
669        //
670        // DEFAULT BEHAVIOR (biggest_coalesce_batch_size=None):
671        //   600 → buffer: [600]
672        //   1200 → buffer: [600, 1200] (1800 rows total)
673        //         → split: output [1000 rows], buffer [800 rows remaining]
674        //   300 → buffer: [800, 300] (1100 rows total)
675        //        → split: output [1000 rows], buffer [100 rows remaining]
676        //   Result: [1000], [1000], [100] - all outputs respect target_batch_size
677        //
678        // OPTIMIZED BEHAVIOR (biggest_coalesce_batch_size=Some(500)):
679        //   600 → Case 1: direct bypass → output: [600]
680        //   1200 → Case 1: direct bypass → output: [1200]
681        //   300 → normal path → buffer: [300]
682        //   Result: [600], [1200], [300] - large batches preserved
683
684        // =============================================================================
685        // Benefits and Trade-offs
686        // =============================================================================
687        // Benefits of the optimization:
688        // - Large batches stay intact (better for downstream vectorized processing)
689        // - Fewer split/merge operations (better CPU performance)
690        // - More predictable memory usage patterns
691        // - Maintains streaming efficiency while preserving batch boundaries
692        //
693        // Trade-offs:
694        // - Output batch sizes become variable (not always target_batch_size)
695        // - May produce smaller partial batches when flushing before large batches
696        // - Requires tuning biggest_coalesce_batch_size parameter for optimal performance
697
698        // TODO, for unsorted batches, we may can filter all large batches, and coalesce all
699        // small batches together?
700
701        let batch_size = batch.num_rows();
702
703        // Fast path: skip empty batches
704        if batch_size == 0 {
705            return Ok(());
706        }
707
708        // Large batch optimization: bypass coalescing for oversized batches
709        if let Some(limit) = self.biggest_coalesce_batch_size
710            && batch_size > limit
711        {
712            // Case 1: No buffered data - emit large batch directly
713            // Example: [] + [1200] → output [1200], buffer []
714            if self.buffered_rows == 0 {
715                self.completed.push_back(batch);
716                return Ok(());
717            }
718
719            // Case 2: Buffer too large - flush then emit to avoid oversized merge
720            // Example: [850] + [1200] → output [850], then output [1200]
721            // This prevents creating batches much larger than both target_batch_size
722            // and biggest_coalesce_batch_size, which could cause memory issues
723            if self.buffered_rows > limit {
724                self.finish_buffered_batch()?;
725                self.completed.push_back(batch);
726                return Ok(());
727            }
728
729            // Case 3: Small buffer - proceed with normal coalescing
730            // Example: [300] + [1200] → split and merge normally
731            // This ensures small batches still get properly coalesced
732            // while allowing some controlled growth beyond the limit
733        }
734
735        let (_schema, arrays, mut num_rows) = batch.into_parts();
736
737        // Validate column count matches the expected schema
738        if arrays.len() != self.in_progress_arrays.len() {
739            return Err(ArrowError::InvalidArgumentError(format!(
740                "Batch has {} columns but BatchCoalescer expects {}",
741                arrays.len(),
742                self.in_progress_arrays.len()
743            )));
744        }
745        self.in_progress_arrays
746            .iter_mut()
747            .zip(arrays)
748            .for_each(|(in_progress, array)| {
749                in_progress.set_source(Some(array));
750            });
751
752        // If pushing this batch would exceed the target batch size,
753        // finish the current batch and start a new one
754        let mut offset = 0;
755        while num_rows > (self.target_batch_size - self.buffered_rows) {
756            let remaining_rows = self.target_batch_size - self.buffered_rows;
757            debug_assert!(remaining_rows > 0);
758
759            // Copy remaining_rows from each array
760            for in_progress in &mut self.in_progress_arrays {
761                in_progress.copy_rows(offset, remaining_rows)?;
762            }
763
764            self.buffered_rows += remaining_rows;
765            offset += remaining_rows;
766            num_rows -= remaining_rows;
767
768            self.finish_buffered_batch()?;
769        }
770
771        // Add any the remaining rows to the buffer
772        self.buffered_rows += num_rows;
773        if num_rows > 0 {
774            for in_progress in &mut self.in_progress_arrays {
775                in_progress.copy_rows(offset, num_rows)?;
776            }
777        }
778
779        // If we have reached the target batch size, finalize the buffered batch
780        if self.buffered_rows >= self.target_batch_size {
781            self.finish_buffered_batch()?;
782        }
783
784        // clear in progress sources (to allow the memory to be freed)
785        for in_progress in &mut self.in_progress_arrays {
786            in_progress.set_source(None);
787        }
788
789        Ok(())
790    }
791
792    /// Returns the number of buffered rows
793    pub fn get_buffered_rows(&self) -> usize {
794        self.buffered_rows
795    }
796
797    /// Concatenates any buffered batches into a single `RecordBatch` and
798    /// clears any output buffers
799    ///
800    /// Normally this is called when the input stream is exhausted, and
801    /// we want to finalize the last batch of rows.
802    ///
803    /// See [`Self::next_completed_batch()`] for the completed batches.
804    pub fn finish_buffered_batch(&mut self) -> Result<(), ArrowError> {
805        if self.buffered_rows == 0 {
806            return Ok(());
807        }
808        let new_arrays = self
809            .in_progress_arrays
810            .iter_mut()
811            .zip(self.schema.fields())
812            .map(|(array, field)| {
813                array.finish().map_err(|e| {
814                    ArrowError::ComputeError(format!(
815                        "Failed to concatenate column '{}': {e}",
816                        field.name()
817                    ))
818                })
819            })
820            .collect::<Result<Vec<_>, ArrowError>>()?;
821
822        for (array, field) in new_arrays.iter().zip(self.schema.fields().iter()) {
823            debug_assert_eq!(array.data_type(), field.data_type());
824            debug_assert_eq!(array.len(), self.buffered_rows);
825        }
826
827        // SAFETY: each array was created of the correct type and length.
828        let batch = unsafe {
829            RecordBatch::new_unchecked(Arc::clone(&self.schema), new_arrays, self.buffered_rows)
830        };
831
832        self.buffered_rows = 0;
833        self.completed.push_back(batch);
834        Ok(())
835    }
836
837    /// Returns true if there are no buffered rows and no completed batches
838    pub fn is_empty(&self) -> bool {
839        self.buffered_rows == 0 && self.completed.is_empty()
840    }
841
842    /// Returns true if there are any completed batches
843    pub fn has_completed_batch(&self) -> bool {
844        !self.completed.is_empty()
845    }
846
847    /// Removes and returns the next completed batch, if any.
848    pub fn next_completed_batch(&mut self) -> Option<RecordBatch> {
849        self.completed.pop_front()
850    }
851
852    /// Returns the number of bytes used by this data structure.
853    pub fn size(&self) -> usize {
854        self.in_progress_arrays.capacity() * size_of::<Box<dyn InProgressArray>>()
855            + self
856                .in_progress_arrays
857                .iter()
858                .map(|array| array.size())
859                .sum::<usize>()
860            + self.completed.capacity() * size_of::<RecordBatch>()
861            + self
862                .completed
863                .iter()
864                .map(|batch| batch.get_array_memory_size())
865                .sum::<usize>()
866    }
867}
868
869impl BatchCoalescer {
870    fn filter_predicate_for_batch(
871        batch: &RecordBatch,
872        mut filter_builder: FilterBuilder,
873    ) -> FilterPredicate {
874        if batch.num_columns() > 1
875            || (batch.num_columns() > 0
876                && FilterBuilder::is_optimize_beneficial(batch.schema_ref().field(0).data_type()))
877        {
878            filter_builder = filter_builder.optimize();
879        }
880        filter_builder.build()
881    }
882
883    fn push_batch_with_filtered_columns(
884        &mut self,
885        batch: RecordBatch,
886        predicate: &FilterPredicate,
887    ) -> Result<(), ArrowError> {
888        let filter_len = predicate.filter_len();
889        let selected_count = predicate.count();
890        let batch_num_rows = batch.num_rows();
891        let batch_num_columns = batch.num_columns();
892
893        if filter_len > batch_num_rows {
894            return Err(ArrowError::InvalidArgumentError(format!(
895                "Filter predicate of length {filter_len} is larger than target array of length {batch_num_rows}"
896            )));
897        }
898
899        if selected_count == 0 {
900            return Ok(());
901        }
902
903        if selected_count == batch_num_rows && filter_len == batch_num_rows {
904            return self.push_batch(batch);
905        }
906
907        if batch_num_columns != self.in_progress_arrays.len() {
908            return Err(ArrowError::InvalidArgumentError(format!(
909                "Batch has {} columns but BatchCoalescer expects {}",
910                batch_num_columns,
911                self.in_progress_arrays.len()
912            )));
913        }
914
915        let exceeds_coalesce_limit = self
916            .biggest_coalesce_batch_size
917            .is_some_and(|limit| selected_count > limit);
918        let does_not_fit_buffer = selected_count > self.target_batch_size - self.buffered_rows;
919        let should_materialize_filter = exceeds_coalesce_limit
920            || self.has_non_specialized_filter_columns
921            || does_not_fit_buffer
922            || (self.has_byte_array_columns
923                && !should_use_byte_array_direct_copy(filter_len, selected_count))
924            || !should_use_sparse_filter_copy(filter_len, selected_count);
925
926        if should_materialize_filter {
927            // Use materialized filtering when sparse per-column copying is unavailable.
928            let filtered_batch = predicate.filter_record_batch(&batch)?;
929            return self.push_batch(filtered_batch);
930        }
931
932        let (_schema, arrays, _num_rows) = batch.into_parts();
933
934        for (in_progress, array) in self.in_progress_arrays.iter_mut().zip(arrays) {
935            in_progress.copy_rows_by_filter_from(array, predicate)?;
936        }
937
938        self.buffered_rows += selected_count;
939        if self.buffered_rows >= self.target_batch_size {
940            self.finish_buffered_batch()?;
941        }
942
943        Ok(())
944    }
945}
946
947/// Return a new `InProgressArray` for the given data type
948fn create_in_progress_array(data_type: &DataType, batch_size: usize) -> Box<dyn InProgressArray> {
949    macro_rules! instantiate_primitive {
950        ($t:ty) => {
951            Box::new(InProgressPrimitiveArray::<$t>::new(
952                batch_size,
953                data_type.clone(),
954            ))
955        };
956    }
957
958    downcast_primitive! {
959        // Instantiate InProgressPrimitiveArray for each primitive type
960        data_type => (instantiate_primitive),
961        DataType::Utf8View => Box::new(InProgressByteViewArray::<StringViewType>::new(batch_size)),
962        DataType::BinaryView => {
963            Box::new(InProgressByteViewArray::<BinaryViewType>::new(batch_size))
964        }
965        DataType::Boolean => Box::new(InProgressBooleanArray::new(batch_size)),
966        DataType::Utf8 => Box::new(InProgressByteArray::<GenericStringType<i32>>::new(batch_size)),
967        DataType::LargeUtf8 => {
968            Box::new(InProgressByteArray::<GenericStringType<i64>>::new(batch_size))
969        }
970        DataType::Binary => Box::new(InProgressByteArray::<GenericBinaryType<i32>>::new(batch_size)),
971        DataType::LargeBinary => {
972            Box::new(InProgressByteArray::<GenericBinaryType<i64>>::new(batch_size))
973        }
974        DataType::Dictionary(key, value) => {
975            create_in_progress_dictionary(key, value)
976        }
977        DataType::FixedSizeBinary(size) => {
978            Box::new(InProgressFixedSizeBinaryArray::new(*size, batch_size))
979        }
980        DataType::List(_) | DataType::LargeList(_) => {
981            Box::new(InProgressListArray::new(data_type.clone()))
982        }
983        _ => Box::new(GenericInProgressArray::new()),
984    }
985}
986
987/// Return an error if `filter` is longer than the source array it is applied to.
988///
989/// A [`FilterPredicate`] yields positions less than its length, so once this
990/// check passes, the filter is guaranteed to produce valid indices less than
991/// `source_len`.
992fn check_filter_len(filter: &FilterPredicate, source_len: usize) -> Result<(), ArrowError> {
993    let filter_len = filter.filter_len();
994    if filter_len > source_len {
995        return Err(ArrowError::InvalidArgumentError(format!(
996            "Filter predicate of length {filter_len} is larger than source array of length {source_len}"
997        )));
998    }
999    Ok(())
1000}
1001
1002/// Incrementally builds up arrays
1003///
1004/// [`GenericInProgressArray`] is the default implementation that buffers
1005/// arrays, uses other kernels, and concatenates them when finished.
1006///
1007/// Some types have specialized, faster implementations (e.g.,
1008/// [`StringViewArray`], etc.).
1009///
1010/// [`StringViewArray`]: arrow_array::StringViewArray
1011trait InProgressArray: std::fmt::Debug + Send + Sync {
1012    /// Returns true if this implementation supports dense indexed copying.
1013    #[cfg_attr(not(test), expect(dead_code))]
1014    fn supports_dense_indexed_copy(&self) -> bool {
1015        false
1016    }
1017
1018    /// Set the source array.
1019    ///
1020    /// Calls to [`Self::copy_rows`] will copy rows from this array into the
1021    /// current in-progress array
1022    fn set_source(&mut self, source: Option<ArrayRef>);
1023
1024    /// Copy rows from the current source array into the in-progress array
1025    ///
1026    /// Note: The source array is set by [`Self::set_source`].
1027    ///
1028    /// Return an error if the source array is not set
1029    fn copy_rows(&mut self, offset: usize, len: usize) -> Result<(), ArrowError>;
1030
1031    /// Copy rows selected by `filter` from the current source array.
1032    ///
1033    /// The default implementation calls [`Self::copy_rows_by_selection`]
1034    fn copy_rows_by_filter(&mut self, filter: &FilterPredicate) -> Result<(), ArrowError> {
1035        self.copy_rows_by_selection(filter.selection())
1036    }
1037
1038    /// Copy rows selected by a [`FilterPredicate`] from `source`.
1039    ///
1040    /// Unlike the other copy methods, the source array is passed in directly,
1041    /// which allows implementations more flexibility. The default
1042    /// implementation simply sets `source` via [`Self::set_source`] and then
1043    /// calls [`Self::copy_rows_by_filter`].
1044    fn copy_rows_by_filter_from(
1045        &mut self,
1046        source: ArrayRef,
1047        filter: &FilterPredicate,
1048    ) -> Result<(), ArrowError> {
1049        self.set_source(Some(source));
1050        let result = self.copy_rows_by_filter(filter);
1051        self.set_source(None);
1052        result
1053    }
1054
1055    /// Copy rows described by a [`FilterSelection`] from the current source array.
1056    ///
1057    /// You typically get a [`FilterSelection`] from [`FilterPredicate::selection`].
1058    ///
1059    /// Note: The source array is set by [`Self::set_source`].
1060    fn copy_rows_by_selection(&mut self, selection: FilterSelection<'_>) -> Result<(), ArrowError> {
1061        match selection {
1062            FilterSelection::None => Ok(()),
1063            FilterSelection::All { len } => self.copy_rows(0, len),
1064            FilterSelection::Slices(slices) => {
1065                slices.try_for_each(|(start, end)| self.copy_rows(start, end - start))
1066            }
1067            FilterSelection::Indices(indices) => indices.try_for_each(|idx| self.copy_rows(idx, 1)),
1068        }
1069    }
1070
1071    /// Copy rows at `indices` from `source` into the in-progress array.
1072    ///
1073    /// # Safety
1074    ///
1075    /// `indices` must not contain nulls, and every value must be less than
1076    /// `source.len()`. Specialized implementations may use unchecked indexing.
1077    unsafe fn copy_rows_by_indices(
1078        &mut self,
1079        source: &ArrayRef,
1080        indices: &UInt32Array,
1081    ) -> Result<(), ArrowError> {
1082        if indices.is_empty() {
1083            return Ok(());
1084        }
1085        let taken = take(
1086            source.as_ref(),
1087            indices,
1088            Some(TakeOptions { check_bounds: true }),
1089        )?;
1090        self.set_source(Some(taken));
1091        let result = self.copy_rows(0, indices.len());
1092        self.set_source(None);
1093        result
1094    }
1095
1096    /// Finish the currently in-progress array and return it as an `ArrayRef`
1097    fn finish(&mut self) -> Result<ArrayRef, ArrowError>;
1098
1099    /// Get the number of bytes this array is using
1100    fn size(&self) -> usize;
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105    use super::*;
1106    use crate::concat::concat_batches;
1107    use crate::filter::filter_record_batch;
1108    use crate::take::take_record_batch;
1109    use arrow_array::builder::StringViewBuilder;
1110    use arrow_array::cast::AsArray;
1111    use arrow_array::types::{Int32Type, UInt8Type};
1112    use arrow_array::{
1113        BinaryViewArray, DictionaryArray, FixedSizeBinaryArray, Int32Array, Int64Array,
1114        RecordBatchOptions, StringArray, StringViewArray, TimestampNanosecondArray, UInt8Array,
1115        UInt32Array, UInt64Array, make_array, record_batch,
1116    };
1117    use arrow_buffer::BooleanBufferBuilder;
1118    use arrow_schema::{DataType, Field, Schema};
1119    use rand::{RngExt, SeedableRng};
1120    use std::ops::Range;
1121
1122    #[test]
1123    fn test_coalesce() {
1124        let batch = uint32_batch(0..8);
1125        Test::new("coalesce")
1126            .with_batches(std::iter::repeat_n(batch, 10))
1127            // expected output is exactly 21 rows (except for the final batch)
1128            .with_batch_size(21)
1129            .with_expected_output_sizes(vec![21, 21, 21, 17])
1130            .run();
1131    }
1132
1133    #[test]
1134    fn test_coalesce_one_by_one() {
1135        let batch = uint32_batch(0..1); // single row input
1136        Test::new("coalesce_one_by_one")
1137            .with_batches(std::iter::repeat_n(batch, 97))
1138            // expected output is exactly 20 rows (except for the final batch)
1139            .with_batch_size(20)
1140            .with_expected_output_sizes(vec![20, 20, 20, 20, 17])
1141            .run();
1142    }
1143
1144    #[test]
1145    fn test_coalesce_empty() {
1146        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt32, false)]));
1147
1148        Test::new("coalesce_empty")
1149            .with_batches(vec![])
1150            .with_schema(schema)
1151            .with_batch_size(21)
1152            .with_expected_output_sizes(vec![])
1153            .run();
1154    }
1155
1156    #[test]
1157    fn test_coalesce_error_includes_column_name() {
1158        let schema = Arc::new(Schema::new(vec![
1159            Field::new("a", DataType::Utf8, false),
1160            Field::new(
1161                "b",
1162                DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
1163                false,
1164            ),
1165        ]));
1166        let batch = RecordBatch::try_new(
1167            Arc::clone(&schema),
1168            vec![
1169                Arc::new(StringArray::from_iter_values(std::iter::repeat_n("a", 256))),
1170                Arc::new(DictionaryArray::<UInt8Type>::new(
1171                    UInt8Array::from_iter_values(0..=u8::MAX),
1172                    Arc::new(StringArray::from_iter_values(
1173                        (0..=u8::MAX).map(|i| i.to_string()),
1174                    )),
1175                )),
1176            ],
1177        )
1178        .unwrap();
1179        let overflow = RecordBatch::try_new(
1180            Arc::clone(&schema),
1181            vec![
1182                Arc::new(StringArray::from(vec!["a"])),
1183                Arc::new(DictionaryArray::<UInt8Type>::new(
1184                    UInt8Array::from(vec![0]),
1185                    Arc::new(StringArray::from(vec!["overflow"])),
1186                )),
1187            ],
1188        )
1189        .unwrap();
1190
1191        let mut coalescer = BatchCoalescer::new(schema, 258);
1192        coalescer.push_batch(batch).unwrap();
1193        coalescer.push_batch(overflow).unwrap();
1194        let err = coalescer.finish_buffered_batch().unwrap_err();
1195
1196        assert_eq!(
1197            err.to_string(),
1198            "Compute error: Failed to concatenate column 'b': Dictionary key bigger than the key type"
1199        );
1200    }
1201
1202    #[test]
1203    fn test_sparse_filter_copy_threshold() {
1204        assert!(should_use_sparse_filter_copy(8192, 8));
1205        assert!(should_use_sparse_filter_copy(8192, 81));
1206        assert!(!should_use_sparse_filter_copy(8192, 819));
1207        assert!(!should_use_sparse_filter_copy(8192, 6553));
1208    }
1209
1210    #[test]
1211    fn test_indexed_copy_thresholds() {
1212        assert!(should_use_indexed_copy(8192, 4096));
1213        assert!(!should_use_indexed_copy(8192, 4097));
1214        assert!(should_use_byte_view_indexed_copy(8192, 512));
1215        assert!(!should_use_byte_view_indexed_copy(8192, 513));
1216        assert!(!should_use_byte_view_indexed_copy(8192, 819));
1217    }
1218
1219    #[test]
1220    fn test_single_large_batch_greater_than_target() {
1221        // test a single large batch
1222        let batch = uint32_batch(0..4096);
1223        Test::new("coalesce_single_large_batch_greater_than_target")
1224            .with_batch(batch)
1225            .with_batch_size(1000)
1226            .with_expected_output_sizes(vec![1000, 1000, 1000, 1000, 96])
1227            .run();
1228    }
1229
1230    #[test]
1231    fn test_single_large_batch_smaller_than_target() {
1232        // test a single large batch
1233        let batch = uint32_batch(0..4096);
1234        Test::new("coalesce_single_large_batch_smaller_than_target")
1235            .with_batch(batch)
1236            .with_batch_size(8192)
1237            .with_expected_output_sizes(vec![4096])
1238            .run();
1239    }
1240
1241    #[test]
1242    fn test_single_large_batch_equal_to_target() {
1243        // test a single large batch
1244        let batch = uint32_batch(0..4096);
1245        Test::new("coalesce_single_large_batch_equal_to_target")
1246            .with_batch(batch)
1247            .with_batch_size(4096)
1248            .with_expected_output_sizes(vec![4096])
1249            .run();
1250    }
1251
1252    #[test]
1253    fn test_single_large_batch_equally_divisible_in_target() {
1254        // test a single large batch
1255        let batch = uint32_batch(0..4096);
1256        Test::new("coalesce_single_large_batch_equally_divisible_in_target")
1257            .with_batch(batch)
1258            .with_batch_size(1024)
1259            .with_expected_output_sizes(vec![1024, 1024, 1024, 1024])
1260            .run();
1261    }
1262
1263    #[test]
1264    fn test_empty_schema() {
1265        let schema = Schema::empty();
1266        let batch = RecordBatch::new_empty(schema.into());
1267        Test::new("coalesce_empty_schema")
1268            .with_batch(batch)
1269            .with_expected_output_sizes(vec![])
1270            .run();
1271    }
1272
1273    /// Coalesce multiple batches, 80k rows, with a 0.1% selectivity filter
1274    #[test]
1275    #[cfg_attr(miri, ignore)] // Takes too long
1276    fn test_coalesce_filtered_001() {
1277        let mut filter_builder = RandomFilterBuilder {
1278            num_rows: 8000,
1279            selectivity: 0.001,
1280            seed: 0,
1281        };
1282
1283        // add 10 batches of 8000 rows each
1284        // 80k rows, selecting 0.1% means 80 rows
1285        // not exactly 80 as the rows are random;
1286        let mut test = Test::new("coalesce_filtered_001");
1287        for _ in 0..10 {
1288            test = test
1289                .with_batch(multi_column_batch(0..8000))
1290                .with_filter(filter_builder.next_filter())
1291        }
1292        test.with_batch_size(15)
1293            .with_expected_output_sizes(vec![15, 15, 15, 13])
1294            .run();
1295    }
1296
1297    /// Coalesce multiple batches, 80k rows, with a 1% selectivity filter
1298    #[test]
1299    #[cfg_attr(miri, ignore)] // Takes too long
1300    fn test_coalesce_filtered_01() {
1301        let mut filter_builder = RandomFilterBuilder {
1302            num_rows: 8000,
1303            selectivity: 0.01,
1304            seed: 0,
1305        };
1306
1307        // add 10 batches of 8000 rows each
1308        // 80k rows, selecting 1% means 800 rows
1309        // not exactly 800 as the rows are random;
1310        let mut test = Test::new("coalesce_filtered_01");
1311        for _ in 0..10 {
1312            test = test
1313                .with_batch(multi_column_batch(0..8000))
1314                .with_filter(filter_builder.next_filter())
1315        }
1316        test.with_batch_size(128)
1317            .with_expected_output_sizes(vec![128, 128, 128, 128, 128, 128, 15])
1318            .run();
1319    }
1320
1321    /// Coalesce multiple batches, 80k rows, with a 10% selectivity filter
1322    #[test]
1323    #[cfg_attr(miri, ignore)] // Takes too long
1324    fn test_coalesce_filtered_10() {
1325        let mut filter_builder = RandomFilterBuilder {
1326            num_rows: 8000,
1327            selectivity: 0.1,
1328            seed: 0,
1329        };
1330
1331        // add 10 batches of 8000 rows each
1332        // 80k rows, selecting 10% means 8000 rows
1333        // not exactly 800 as the rows are random;
1334        let mut test = Test::new("coalesce_filtered_10");
1335        for _ in 0..10 {
1336            test = test
1337                .with_batch(multi_column_batch(0..8000))
1338                .with_filter(filter_builder.next_filter())
1339        }
1340        test.with_batch_size(1024)
1341            .with_expected_output_sizes(vec![1024, 1024, 1024, 1024, 1024, 1024, 1024, 840])
1342            .run();
1343    }
1344
1345    /// Coalesce multiple batches, 8k rows, with a 90% selectivity filter
1346    #[test]
1347    #[cfg_attr(miri, ignore)] // Takes too long
1348    fn test_coalesce_filtered_90() {
1349        let mut filter_builder = RandomFilterBuilder {
1350            num_rows: 800,
1351            selectivity: 0.90,
1352            seed: 0,
1353        };
1354
1355        // add 10 batches of 800 rows each
1356        // 8k rows, selecting 99% means 7200 rows
1357        // not exactly 7200 as the rows are random;
1358        let mut test = Test::new("coalesce_filtered_90");
1359        for _ in 0..10 {
1360            test = test
1361                .with_batch(multi_column_batch(0..800))
1362                .with_filter(filter_builder.next_filter())
1363        }
1364        test.with_batch_size(1024)
1365            .with_expected_output_sizes(vec![1024, 1024, 1024, 1024, 1024, 1024, 1024, 13])
1366            .run();
1367    }
1368
1369    /// Coalesce multiple batches, 8k rows, with mixed filers, including 100%
1370    #[test]
1371    #[cfg_attr(miri, ignore)] // Takes too long
1372    fn test_coalesce_filtered_mixed() {
1373        let mut filter_builder = RandomFilterBuilder {
1374            num_rows: 800,
1375            selectivity: 0.90,
1376            seed: 0,
1377        };
1378
1379        let mut test = Test::new("coalesce_filtered_mixed");
1380        for _ in 0..3 {
1381            // also add in a batch that selects almost all rows and when
1382            // sliced will have some batches that are entirely used
1383            let mut all_filter_builder = BooleanBufferBuilder::new(1000);
1384            all_filter_builder.append_n(500, true);
1385            all_filter_builder.append_n(1, false);
1386            all_filter_builder.append_n(499, false);
1387            let all_filter = all_filter_builder.build();
1388
1389            test = test
1390                .with_batch(multi_column_batch(0..1000))
1391                .with_filter(BooleanArray::from(all_filter))
1392                .with_batch(multi_column_batch(0..800))
1393                .with_filter(filter_builder.next_filter());
1394            // decrease selectivity
1395            filter_builder.selectivity *= 0.6;
1396        }
1397
1398        // use a small batch size to ensure the filter is appended in slices
1399        // and some of those slides will select the entire thing.
1400        test.with_batch_size(250)
1401            .with_expected_output_sizes(vec![
1402                250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 179,
1403            ])
1404            .run();
1405    }
1406
1407    #[test]
1408    fn test_push_batch_with_filter_builder() {
1409        let batch = record_batch!(("a", Int32, [1, 2, 3, 4])).unwrap();
1410        // The null is not selected, so the filter selects two rows.
1411        let filter = BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]);
1412        let expected = record_batch!(("a", Int32, [1, 4])).unwrap();
1413
1414        // SAFETY: the count matches the filter.
1415        let with_count = unsafe { FilterBuilder::new(&filter).with_count(2) };
1416        // The coalescer does not optimize a single primitive column itself, so
1417        // this covers a predicate that only the caller optimized.
1418        let optimized = FilterBuilder::new(&filter).optimize();
1419        for filter_builder in [with_count, optimized] {
1420            let mut coalescer = BatchCoalescer::new(batch.schema(), 10);
1421            coalescer
1422                .push_batch_with_filter_builder(batch.clone(), filter_builder)
1423                .unwrap();
1424            coalescer.finish_buffered_batch().unwrap();
1425            assert_eq!(coalescer.next_completed_batch().unwrap(), expected);
1426            assert!(coalescer.next_completed_batch().is_none());
1427        }
1428    }
1429
1430    #[test]
1431    fn test_coalesce_non_null() {
1432        Test::new("coalesce_non_null")
1433            // 4040 rows of unit32
1434            .with_batch(uint32_batch_non_null(0..3000))
1435            .with_batch(uint32_batch_non_null(0..1040))
1436            .with_batch_size(1024)
1437            .with_expected_output_sizes(vec![1024, 1024, 1024, 968])
1438            .run();
1439    }
1440    #[test]
1441    #[cfg_attr(miri, ignore)] // Takes too long
1442    fn test_utf8_split() {
1443        Test::new("coalesce_utf8")
1444            // 4040 rows of utf8 strings in total, split into batches of 1024
1445            .with_batch(utf8_batch(0..3000))
1446            .with_batch(utf8_batch(0..1040))
1447            .with_batch_size(1024)
1448            .with_expected_output_sizes(vec![1024, 1024, 1024, 968])
1449            .run();
1450    }
1451
1452    #[test]
1453    fn test_string_view_no_views() {
1454        let output_batches = Test::new("coalesce_string_view_no_views")
1455            // both input batches have no views, so no need to compact
1456            .with_batch(stringview_batch([Some("foo"), Some("bar")]))
1457            .with_batch(stringview_batch([Some("baz"), Some("qux")]))
1458            .with_expected_output_sizes(vec![4])
1459            .run();
1460
1461        expect_buffer_layout(
1462            col_as_string_view("c0", output_batches.first().unwrap()),
1463            vec![],
1464        );
1465    }
1466
1467    #[test]
1468    fn test_string_view_batch_small_no_compact() {
1469        // view with only short strings (no buffers) --> no need to compact
1470        let batch = stringview_batch_repeated(1000, [Some("a"), Some("b"), Some("c")]);
1471        let output_batches = Test::new("coalesce_string_view_batch_small_no_compact")
1472            .with_batch(batch.clone())
1473            .with_expected_output_sizes(vec![1000])
1474            .run();
1475
1476        let array = col_as_string_view("c0", &batch);
1477        let gc_array = col_as_string_view("c0", output_batches.first().unwrap());
1478        assert_eq!(array.data_buffers().len(), 0);
1479        assert_eq!(array.data_buffers().len(), gc_array.data_buffers().len()); // no compaction
1480
1481        expect_buffer_layout(gc_array, vec![]);
1482    }
1483
1484    #[test]
1485    #[cfg_attr(miri, ignore)] // Takes too long
1486    fn test_string_view_batch_large_no_compact() {
1487        // view with large strings (has buffers) but full --> no need to compact
1488        let batch = stringview_batch_repeated(1000, [Some("This string is longer than 12 bytes")]);
1489        let output_batches = Test::new("coalesce_string_view_batch_large_no_compact")
1490            .with_batch(batch.clone())
1491            .with_batch_size(1000)
1492            .with_expected_output_sizes(vec![1000])
1493            .run();
1494
1495        let array = col_as_string_view("c0", &batch);
1496        let gc_array = col_as_string_view("c0", output_batches.first().unwrap());
1497        assert_eq!(array.data_buffers().len(), 5);
1498        assert_eq!(array.data_buffers().len(), gc_array.data_buffers().len()); // no compaction
1499
1500        expect_buffer_layout(
1501            gc_array,
1502            vec![
1503                ExpectedLayout {
1504                    len: 8190,
1505                    capacity: 8192,
1506                },
1507                ExpectedLayout {
1508                    len: 8190,
1509                    capacity: 8192,
1510                },
1511                ExpectedLayout {
1512                    len: 8190,
1513                    capacity: 8192,
1514                },
1515                ExpectedLayout {
1516                    len: 8190,
1517                    capacity: 8192,
1518                },
1519                ExpectedLayout {
1520                    len: 2240,
1521                    capacity: 8192,
1522                },
1523            ],
1524        );
1525    }
1526
1527    #[test]
1528    fn test_string_view_batch_small_with_buffers_no_compact() {
1529        // view with buffers but only short views
1530        let short_strings = std::iter::repeat(Some("SmallString"));
1531        let long_strings = std::iter::once(Some("This string is longer than 12 bytes"));
1532        // 20 short strings, then a long ones
1533        let values = short_strings.take(20).chain(long_strings);
1534        let batch = stringview_batch_repeated(1000, values)
1535            // take only 10 short strings (no long ones)
1536            .slice(5, 10);
1537        let output_batches = Test::new("coalesce_string_view_batch_small_with_buffers_no_compact")
1538            .with_batch(batch.clone())
1539            .with_batch_size(1000)
1540            .with_expected_output_sizes(vec![10])
1541            .run();
1542
1543        let array = col_as_string_view("c0", &batch);
1544        let gc_array = col_as_string_view("c0", output_batches.first().unwrap());
1545        assert_eq!(array.data_buffers().len(), 1); // input has one buffer
1546        assert_eq!(gc_array.data_buffers().len(), 0); // output has no buffers as only short strings
1547    }
1548
1549    #[test]
1550    fn test_string_view_batch_large_slice_compact() {
1551        // view with large strings (has buffers) and only partially used  --> no need to compact
1552        let batch = stringview_batch_repeated(1000, [Some("This string is longer than 12 bytes")])
1553            // slice only 22 rows, so most of the buffer is not used
1554            .slice(11, 22);
1555
1556        let output_batches = Test::new("coalesce_string_view_batch_large_slice_compact")
1557            .with_batch(batch.clone())
1558            .with_batch_size(1000)
1559            .with_expected_output_sizes(vec![22])
1560            .run();
1561
1562        let array = col_as_string_view("c0", &batch);
1563        let gc_array = col_as_string_view("c0", output_batches.first().unwrap());
1564        assert_eq!(array.data_buffers().len(), 5);
1565
1566        expect_buffer_layout(
1567            gc_array,
1568            vec![ExpectedLayout {
1569                len: 770,
1570                capacity: 8192,
1571            }],
1572        );
1573    }
1574
1575    #[test]
1576    #[cfg_attr(miri, ignore)] // Takes too long
1577    fn test_string_view_mixed() {
1578        let large_view_batch =
1579            stringview_batch_repeated(1000, [Some("This string is longer than 12 bytes")]);
1580        let small_view_batch = stringview_batch_repeated(1000, [Some("SmallString")]);
1581        let mixed_batch = stringview_batch_repeated(
1582            1000,
1583            [Some("This string is longer than 12 bytes"), Some("Small")],
1584        );
1585        let mixed_batch_nulls = stringview_batch_repeated(
1586            1000,
1587            [
1588                Some("This string is longer than 12 bytes"),
1589                Some("Small"),
1590                None,
1591            ],
1592        );
1593
1594        // Several batches with mixed inline / non inline
1595        // 4k rows in
1596        let output_batches = Test::new("coalesce_string_view_mixed")
1597            .with_batch(large_view_batch.clone())
1598            .with_batch(small_view_batch)
1599            // this batch needs to be compacted (less than 1/2 full)
1600            .with_batch(large_view_batch.slice(10, 20))
1601            .with_batch(mixed_batch_nulls)
1602            // this batch needs to be compacted (less than 1/2 full)
1603            .with_batch(large_view_batch.slice(10, 20))
1604            .with_batch(mixed_batch)
1605            .with_expected_output_sizes(vec![1024, 1024, 1024, 968])
1606            .run();
1607
1608        expect_buffer_layout(
1609            col_as_string_view("c0", output_batches.first().unwrap()),
1610            vec![
1611                ExpectedLayout {
1612                    len: 8190,
1613                    capacity: 8192,
1614                },
1615                ExpectedLayout {
1616                    len: 8190,
1617                    capacity: 8192,
1618                },
1619                ExpectedLayout {
1620                    len: 8190,
1621                    capacity: 8192,
1622                },
1623                ExpectedLayout {
1624                    len: 8190,
1625                    capacity: 8192,
1626                },
1627                ExpectedLayout {
1628                    len: 2240,
1629                    capacity: 8192,
1630                },
1631            ],
1632        );
1633    }
1634
1635    #[test]
1636    #[cfg_attr(miri, ignore)] // Takes too long
1637    fn test_string_view_many_small_compact() {
1638        // 200 rows alternating long (28) and short (≤12) strings.
1639        // Only the 100 long strings go into data buffers: 100 × 28 = 2800.
1640        let batch = stringview_batch_repeated(
1641            200,
1642            [Some("This string is 28 bytes long"), Some("small string")],
1643        );
1644        let output_batches = Test::new("coalesce_string_view_many_small_compact")
1645            // First allocated buffer is 8kb.
1646            // Appending 10 batches of 2800 bytes will use 2800 * 10 = 14kb (8kb, an 16kb and 32kbkb)
1647            .with_batch(batch.clone())
1648            .with_batch(batch.clone())
1649            .with_batch(batch.clone())
1650            .with_batch(batch.clone())
1651            .with_batch(batch.clone())
1652            .with_batch(batch.clone())
1653            .with_batch(batch.clone())
1654            .with_batch(batch.clone())
1655            .with_batch(batch.clone())
1656            .with_batch(batch.clone())
1657            .with_batch_size(8000)
1658            .with_expected_output_sizes(vec![2000]) // only 1000 rows total
1659            .run();
1660
1661        // expect a nice even distribution of buffers
1662        expect_buffer_layout(
1663            col_as_string_view("c0", output_batches.first().unwrap()),
1664            vec![
1665                ExpectedLayout {
1666                    len: 8176,
1667                    capacity: 8192,
1668                },
1669                ExpectedLayout {
1670                    len: 16380,
1671                    capacity: 16384,
1672                },
1673                ExpectedLayout {
1674                    len: 3444,
1675                    capacity: 32768,
1676                },
1677            ],
1678        );
1679    }
1680
1681    #[test]
1682    #[cfg_attr(miri, ignore)] // Takes too long
1683    fn test_string_view_many_small_boundary() {
1684        // The strings are designed to exactly fit into buffers that are powers of 2 long
1685        let batch = stringview_batch_repeated(100, [Some("This string is a power of two=32")]);
1686        let output_batches = Test::new("coalesce_string_view_many_small_boundary")
1687            .with_batches(std::iter::repeat_n(batch, 20))
1688            .with_batch_size(900)
1689            .with_expected_output_sizes(vec![900, 900, 200])
1690            .run();
1691
1692        // expect each buffer to be entirely full except the last one
1693        expect_buffer_layout(
1694            col_as_string_view("c0", output_batches.first().unwrap()),
1695            vec![
1696                ExpectedLayout {
1697                    len: 8192,
1698                    capacity: 8192,
1699                },
1700                ExpectedLayout {
1701                    len: 16384,
1702                    capacity: 16384,
1703                },
1704                ExpectedLayout {
1705                    len: 4224,
1706                    capacity: 32768,
1707                },
1708            ],
1709        );
1710    }
1711
1712    #[test]
1713    #[cfg_attr(miri, ignore)] // Takes too long
1714    fn test_string_view_large_small() {
1715        // The strings are 37 bytes long, so each batch has 100 * 28 = 2800 bytes
1716        let mixed_batch = stringview_batch_repeated(
1717            200,
1718            [Some("This string is 28 bytes long"), Some("small string")],
1719        );
1720        // These strings aren't copied, this array has an 8k buffer
1721        let all_large = stringview_batch_repeated(
1722            50,
1723            [Some(
1724                "This buffer has only large strings in it so there are no buffer copies",
1725            )],
1726        );
1727
1728        let output_batches = Test::new("coalesce_string_view_large_small")
1729            // First allocated buffer is 8kb.
1730            // Appending five batches of 2800 bytes will use 2800 * 10 = 28kb (8kb, an 16kb and 32kbkb)
1731            .with_batch(mixed_batch.clone())
1732            .with_batch(mixed_batch.clone())
1733            .with_batch(all_large.clone())
1734            .with_batch(mixed_batch.clone())
1735            .with_batch(all_large.clone())
1736            .with_batch(mixed_batch.clone())
1737            .with_batch(mixed_batch.clone())
1738            .with_batch(all_large.clone())
1739            .with_batch(mixed_batch.clone())
1740            .with_batch(all_large.clone())
1741            .with_batch_size(8000)
1742            .with_expected_output_sizes(vec![1400])
1743            .run();
1744
1745        expect_buffer_layout(
1746            col_as_string_view("c0", output_batches.first().unwrap()),
1747            vec![
1748                ExpectedLayout {
1749                    len: 8190,
1750                    capacity: 8192,
1751                },
1752                ExpectedLayout {
1753                    len: 16366,
1754                    capacity: 16384,
1755                },
1756                ExpectedLayout {
1757                    len: 6244,
1758                    capacity: 32768,
1759                },
1760            ],
1761        );
1762    }
1763
1764    #[test]
1765    #[cfg_attr(miri, ignore)] // Takes too long
1766    fn test_binary_view() {
1767        let values: Vec<Option<&[u8]>> = vec![
1768            Some(b"foo"),
1769            None,
1770            Some(b"A longer string that is more than 12 bytes"),
1771        ];
1772
1773        let binary_view =
1774            BinaryViewArray::from_iter(std::iter::repeat(values.iter()).flatten().take(1000));
1775        let batch =
1776            RecordBatch::try_from_iter(vec![("c0", Arc::new(binary_view) as ArrayRef)]).unwrap();
1777
1778        Test::new("coalesce_binary_view")
1779            .with_batch(batch.clone())
1780            .with_batch(batch.clone())
1781            .with_batch_size(512)
1782            .with_expected_output_sizes(vec![512, 512, 512, 464])
1783            .run();
1784    }
1785
1786    #[test]
1787    fn test_binary_view_filtered() {
1788        let values: Vec<Option<&[u8]>> = vec![
1789            Some(b"foo"),
1790            None,
1791            Some(b"A longer string that is more than 12 bytes"),
1792        ];
1793
1794        let binary_view =
1795            BinaryViewArray::from_iter(std::iter::repeat(values.iter()).flatten().take(1000));
1796        let batch =
1797            RecordBatch::try_from_iter(vec![("c0", Arc::new(binary_view) as ArrayRef)]).unwrap();
1798        let filter = sparse_filter(1000);
1799
1800        Test::new("coalesce_binary_view_filtered")
1801            .with_batch(batch.clone())
1802            .with_filter(filter.clone())
1803            .with_batch(batch)
1804            .with_filter(filter)
1805            .with_batch_size(256)
1806            .with_expected_output_sizes(vec![250])
1807            .run();
1808    }
1809
1810    #[test]
1811    fn test_binary_view_filtered_inline() {
1812        let values: Vec<Option<&[u8]>> = vec![Some(b"foo"), None, Some(b"barbaz")];
1813
1814        let binary_view =
1815            BinaryViewArray::from_iter(std::iter::repeat(values.iter()).flatten().take(1000));
1816        let batch =
1817            RecordBatch::try_from_iter(vec![("c0", Arc::new(binary_view) as ArrayRef)]).unwrap();
1818        let filter = sparse_filter(1000);
1819
1820        Test::new("coalesce_binary_view_filtered_inline")
1821            .with_batch(batch.clone())
1822            .with_filter(filter.clone())
1823            .with_batch(batch)
1824            .with_filter(filter)
1825            .with_batch_size(300)
1826            .with_expected_output_sizes(vec![250])
1827            .run();
1828    }
1829
1830    #[test]
1831    fn test_string_view_filtered_inline() {
1832        let values: Vec<Option<&str>> = vec![Some("foo"), None, Some("barbaz")];
1833
1834        let string_view =
1835            StringViewArray::from_iter(std::iter::repeat(values.iter()).flatten().take(1000));
1836        let batch =
1837            RecordBatch::try_from_iter(vec![("c0", Arc::new(string_view) as ArrayRef)]).unwrap();
1838        let filter = sparse_filter(1000);
1839
1840        Test::new("coalesce_string_view_filtered_inline")
1841            .with_batch(batch.clone())
1842            .with_filter(filter.clone())
1843            .with_batch(batch)
1844            .with_filter(filter)
1845            .with_batch_size(300)
1846            .with_expected_output_sizes(vec![250])
1847            .run();
1848    }
1849
1850    #[test]
1851    fn test_mixed_inline_binary_view_filtered() {
1852        let int_values =
1853            Int32Array::from_iter((0..1000).map(|v| if v % 5 == 0 { None } else { Some(v) }));
1854        let float_values = arrow_array::Float64Array::from_iter((0..1000).map(|v| Some(v as f64)));
1855        let binary_values: Vec<Option<&[u8]>> = vec![Some(b"foo"), None, Some(b"barbaz")];
1856        let binary_view = BinaryViewArray::from_iter(
1857            std::iter::repeat(binary_values.iter()).flatten().take(1000),
1858        );
1859
1860        let batch = RecordBatch::try_from_iter(vec![
1861            ("i", Arc::new(int_values) as ArrayRef),
1862            ("f", Arc::new(float_values) as ArrayRef),
1863            ("b", Arc::new(binary_view) as ArrayRef),
1864        ])
1865        .unwrap();
1866
1867        let filter = sparse_filter(1000);
1868
1869        Test::new("coalesce_mixed_inline_binary_view_filtered")
1870            .with_batch(batch.clone())
1871            .with_filter(filter.clone())
1872            .with_batch(batch)
1873            .with_filter(filter)
1874            .with_batch_size(300)
1875            .with_expected_output_sizes(vec![250])
1876            .run();
1877    }
1878
1879    #[test]
1880    fn test_mixed_inline_string_view_filtered() {
1881        let int_values =
1882            Int32Array::from_iter((0..1000).map(|v| if v % 5 == 0 { None } else { Some(v) }));
1883        let float_values = arrow_array::Float64Array::from_iter((0..1000).map(|v| Some(v as f64)));
1884        let string_values: Vec<Option<&str>> = vec![Some("foo"), None, Some("barbaz")];
1885        let string_view = StringViewArray::from_iter(
1886            std::iter::repeat(string_values.iter()).flatten().take(1000),
1887        );
1888
1889        let batch = RecordBatch::try_from_iter(vec![
1890            ("i", Arc::new(int_values) as ArrayRef),
1891            ("f", Arc::new(float_values) as ArrayRef),
1892            ("s", Arc::new(string_view) as ArrayRef),
1893        ])
1894        .unwrap();
1895
1896        let filter = sparse_filter(1000);
1897
1898        Test::new("coalesce_mixed_inline_string_view_filtered")
1899            .with_batch(batch.clone())
1900            .with_filter(filter.clone())
1901            .with_batch(batch)
1902            .with_filter(filter)
1903            .with_batch_size(300)
1904            .with_expected_output_sizes(vec![250])
1905            .run();
1906    }
1907
1908    #[test]
1909    fn test_inline_binary_view_sparse() {
1910        // All-inline binary views (<=12 bytes) + 5% selectivity
1911        let values: Vec<Option<&[u8]>> = vec![Some(b"foo"), None, Some(b"barbaz")];
1912        let binary_view =
1913            BinaryViewArray::from_iter(std::iter::repeat(values.iter()).flatten().take(1000));
1914        let batch =
1915            RecordBatch::try_from_iter(vec![("c0", Arc::new(binary_view) as ArrayRef)]).unwrap();
1916        let filter = very_sparse_filter(1000);
1917
1918        Test::new("inline_binary_view_sparse")
1919            .with_batch(batch.clone())
1920            .with_filter(filter.clone())
1921            .with_batch(batch)
1922            .with_filter(filter)
1923            .with_batch_size(1024)
1924            .with_expected_output_sizes(vec![100])
1925            .run();
1926    }
1927
1928    #[test]
1929    fn test_inline_string_view_sparse() {
1930        let values: Vec<Option<&str>> = vec![Some("foo"), None, Some("barbaz")];
1931        let string_view =
1932            StringViewArray::from_iter(std::iter::repeat(values.iter()).flatten().take(1000));
1933        let batch =
1934            RecordBatch::try_from_iter(vec![("c0", Arc::new(string_view) as ArrayRef)]).unwrap();
1935        let filter = very_sparse_filter(1000);
1936
1937        Test::new("inline_string_view_sparse")
1938            .with_batch(batch.clone())
1939            .with_filter(filter.clone())
1940            .with_batch(batch)
1941            .with_filter(filter)
1942            .with_batch_size(1024)
1943            .with_expected_output_sizes(vec![100])
1944            .run();
1945    }
1946
1947    #[test]
1948    fn test_inline_mixed_sparse() {
1949        // Mixing primitives with inline views exercises materialized `Indices`
1950        // selection for both the primitive and the byte-view.
1951        let int_values =
1952            Int32Array::from_iter((0..1000).map(|v| if v % 5 == 0 { None } else { Some(v) }));
1953        let float_values = arrow_array::Float64Array::from_iter((0..1000).map(|v| Some(v as f64)));
1954        let string_values: Vec<Option<&str>> = vec![Some("foo"), None, Some("barbaz")];
1955        let string_view = StringViewArray::from_iter(
1956            std::iter::repeat(string_values.iter()).flatten().take(1000),
1957        );
1958        let binary_values: Vec<Option<&[u8]>> = vec![Some(b"x"), None, Some(b"abcdef")];
1959        let binary_view = BinaryViewArray::from_iter(
1960            std::iter::repeat(binary_values.iter()).flatten().take(1000),
1961        );
1962
1963        let batch = RecordBatch::try_from_iter(vec![
1964            ("i", Arc::new(int_values) as ArrayRef),
1965            ("f", Arc::new(float_values) as ArrayRef),
1966            ("s", Arc::new(string_view) as ArrayRef),
1967            ("b", Arc::new(binary_view) as ArrayRef),
1968        ])
1969        .unwrap();
1970        let filter = very_sparse_filter(1000);
1971
1972        Test::new("inline_mixed_sparse")
1973            .with_batch(batch.clone())
1974            .with_filter(filter.clone())
1975            .with_batch(batch)
1976            .with_filter(filter)
1977            .with_batch_size(1024)
1978            .with_expected_output_sizes(vec![100])
1979            .run();
1980    }
1981
1982    #[test]
1983    fn test_inline_crosses_target_batch_size() {
1984        // Each 1000-row batch selects 50 rows; target_batch_size 100
1985        // exercises intermediate batch flushing batch (not just the final
1986        // flush).
1987        let values: Vec<Option<&[u8]>> = vec![Some(b"foo"), None, Some(b"barbaz")];
1988        let make_batch = || {
1989            let binary_view =
1990                BinaryViewArray::from_iter(std::iter::repeat(values.iter()).flatten().take(1000));
1991            RecordBatch::try_from_iter(vec![("c0", Arc::new(binary_view) as ArrayRef)]).unwrap()
1992        };
1993        let filter = very_sparse_filter(1000);
1994
1995        Test::new("inline_crosses_target_batch_size")
1996            .with_batch(make_batch())
1997            .with_filter(filter.clone())
1998            .with_batch(make_batch())
1999            .with_filter(filter.clone())
2000            .with_batch(make_batch())
2001            .with_filter(filter)
2002            .with_batch_size(100)
2003            .with_expected_output_sizes(vec![100, 50])
2004            .run();
2005    }
2006
2007    #[test]
2008    fn test_inline_filter_rejects_filter_longer_than_batch() {
2009        let values: Vec<Option<&[u8]>> = vec![Some(b"foo"), Some(b"bar")];
2010        let binary_view = BinaryViewArray::from_iter(values);
2011        let batch =
2012            RecordBatch::try_from_iter(vec![("c0", Arc::new(binary_view) as ArrayRef)]).unwrap();
2013        let filter = BooleanArray::from(vec![true, false, true]);
2014
2015        let mut coalescer = BatchCoalescer::new(batch.schema(), 100);
2016        let result = coalescer.push_batch_with_filter(batch, &filter);
2017        assert!(result.is_err());
2018        let err = result.unwrap_err().to_string();
2019        assert!(
2020            err.contains("Filter predicate of length 3 is larger than target array of length 2"),
2021            "unexpected error: {err}"
2022        );
2023    }
2024
2025    #[test]
2026    fn test_mixed_boolean_inline_string_view_filtered() {
2027        let bool_values = BooleanArray::from_iter((0..1000).map(|v| Some(v % 3 == 0)));
2028        let string_values: Vec<Option<&str>> = vec![Some("foo"), None, Some("barbaz")];
2029        let string_view = StringViewArray::from_iter(
2030            std::iter::repeat(string_values.iter()).flatten().take(1000),
2031        );
2032
2033        let batch = RecordBatch::try_from_iter(vec![
2034            ("b", Arc::new(bool_values) as ArrayRef),
2035            ("s", Arc::new(string_view) as ArrayRef),
2036        ])
2037        .unwrap();
2038
2039        let filter = sparse_filter(1000);
2040
2041        Test::new("coalesce_mixed_boolean_inline_string_view_filtered")
2042            .with_batch(batch.clone())
2043            .with_filter(filter.clone())
2044            .with_batch(batch)
2045            .with_filter(filter)
2046            .with_batch_size(300)
2047            .with_expected_output_sizes(vec![250])
2048            .run();
2049    }
2050
2051    #[test]
2052    fn test_filter_fast_path_schema_capability() {
2053        let supported = Arc::new(Schema::new(vec![
2054            Field::new("primitive", DataType::UInt32, false),
2055            Field::new("utf8_view", DataType::Utf8View, true),
2056            Field::new("binary_view", DataType::BinaryView, true),
2057            Field::new("list", DataType::new_list(DataType::Int32, true), true),
2058            Field::new(
2059                "large_list",
2060                DataType::new_large_list(DataType::Utf8, true),
2061                true,
2062            ),
2063        ]));
2064        let coalescer = BatchCoalescer::new(supported, 100);
2065        assert!(!coalescer.has_non_specialized_filter_columns);
2066        assert!(!coalescer.has_byte_array_columns);
2067
2068        let utf8 = Arc::new(Schema::new(vec![Field::new("utf8", DataType::Utf8, true)]));
2069        let coalescer = BatchCoalescer::new(utf8, 100);
2070        assert!(!coalescer.has_non_specialized_filter_columns);
2071        assert!(coalescer.has_byte_array_columns);
2072
2073        let boolean = Arc::new(Schema::new(vec![Field::new(
2074            "boolean",
2075            DataType::Boolean,
2076            true,
2077        )]));
2078        let coalescer = BatchCoalescer::new(boolean, 100);
2079        assert!(!coalescer.has_non_specialized_filter_columns);
2080    }
2081
2082    #[test]
2083    fn test_dense_indexed_copy_capability() {
2084        let cases = [
2085            (DataType::Int32, true),
2086            (DataType::Utf8View, true),
2087            (DataType::BinaryView, true),
2088            (
2089                DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
2090                true,
2091            ),
2092            (DataType::Boolean, true),
2093            (DataType::Utf8, false),
2094            (DataType::FixedSizeBinary(4), false),
2095            (DataType::new_list(DataType::Int32, true), false),
2096            (DataType::Null, false),
2097        ];
2098
2099        for (data_type, expected) in cases {
2100            let in_progress = create_in_progress_array(&data_type, 100);
2101            assert_eq!(
2102                in_progress.supports_dense_indexed_copy(),
2103                expected,
2104                "unexpected capability for {data_type}"
2105            );
2106        }
2107    }
2108
2109    fn sparse_filter_byte_array_input() -> (RecordBatch, BooleanArray) {
2110        let mut strings = vec![Some("padding"); 4096];
2111        strings[..4].copy_from_slice(&[Some("zero"), None, Some("two"), Some("three")]);
2112        let batch = RecordBatch::try_from_iter([(
2113            "bytes",
2114            Arc::new(StringArray::from(strings)) as ArrayRef,
2115        )])
2116        .unwrap();
2117        let filter = BooleanArray::from_iter((0..batch.num_rows()).map(|idx| Some(idx < 4)));
2118        (batch, filter)
2119    }
2120
2121    #[test]
2122    fn test_sparse_filter_byte_array_direct_copy() {
2123        let (batch, filter) = sparse_filter_byte_array_input();
2124        assert!(should_use_byte_array_direct_copy(batch.num_rows(), 4));
2125
2126        let fallback_filter =
2127            BooleanArray::from_iter((0..batch.num_rows()).map(|idx| Some(idx < 5)));
2128        assert!(!should_use_byte_array_direct_copy(batch.num_rows(), 5));
2129        let mut coalescer = BatchCoalescer::new(batch.schema(), 6);
2130        coalescer
2131            .push_batch_with_filter(batch.clone(), &fallback_filter)
2132            .unwrap();
2133        coalescer.finish_buffered_batch().unwrap();
2134        let expected = filter_record_batch(&batch, &fallback_filter).unwrap();
2135        assert_eq!(coalescer.next_completed_batch().unwrap(), expected);
2136
2137        Test::new("coalesce_sparse_filter_utf8_direct_copy")
2138            .with_batch(batch)
2139            .with_filter(filter)
2140            .with_batch_size(4)
2141            .with_expected_output_sizes([4])
2142            .run();
2143    }
2144
2145    #[derive(Debug, Clone, PartialEq)]
2146    struct ExpectedLayout {
2147        len: usize,
2148        capacity: usize,
2149    }
2150
2151    /// Asserts that the buffer layout of the specified StringViewArray matches the expected layout
2152    fn expect_buffer_layout(array: &StringViewArray, expected: Vec<ExpectedLayout>) {
2153        let actual = array
2154            .data_buffers()
2155            .iter()
2156            .map(|b| ExpectedLayout {
2157                len: b.len(),
2158                capacity: b.capacity(),
2159            })
2160            .collect::<Vec<_>>();
2161
2162        assert_eq!(
2163            actual, expected,
2164            "Expected buffer layout {expected:#?} but got {actual:#?}"
2165        );
2166    }
2167
2168    /// Test for [`BatchCoalescer`]
2169    ///
2170    /// Pushes the input batches to the coalescer and verifies that the resulting
2171    /// batches have the
2172    /// 1. expected number of rows
2173    /// 2. The same results when the batches are filtered using the filter kernel
2174    #[derive(Debug, Clone)]
2175    struct Test {
2176        /// A human readable name to assist in debugging
2177        name: String,
2178        /// Batches to feed to the coalescer.
2179        input_batches: Vec<RecordBatch>,
2180        /// Filters to apply to the corresponding input batches.
2181        ///
2182        /// If there are no filters for the input batches, the batch will be
2183        /// pushed as is.
2184        filters: Vec<BooleanArray>,
2185        /// The schema. If not provided, the first batch's schema is used.
2186        schema: Option<SchemaRef>,
2187        /// Expected output sizes of the resulting batches
2188        expected_output_sizes: Vec<usize>,
2189        /// target batch size (default to 1024)
2190        target_batch_size: usize,
2191    }
2192
2193    impl Default for Test {
2194        fn default() -> Self {
2195            Self {
2196                name: String::new(),
2197                input_batches: vec![],
2198                filters: vec![],
2199                schema: None,
2200                expected_output_sizes: vec![],
2201                target_batch_size: 1024,
2202            }
2203        }
2204    }
2205
2206    impl Test {
2207        fn new(name: impl Into<String>) -> Self {
2208            Self {
2209                name: name.into(),
2210                ..Self::default()
2211            }
2212        }
2213
2214        /// Append the description to the test name
2215        fn with_description(mut self, description: &str) -> Self {
2216            self.name.push_str(": ");
2217            self.name.push_str(description);
2218            self
2219        }
2220
2221        /// Set the target batch size
2222        fn with_batch_size(mut self, target_batch_size: usize) -> Self {
2223            self.target_batch_size = target_batch_size;
2224            self
2225        }
2226
2227        /// Extend the input batches with `batch`
2228        fn with_batch(mut self, batch: RecordBatch) -> Self {
2229            self.input_batches.push(batch);
2230            self
2231        }
2232
2233        /// Extend the filters with `filter`
2234        fn with_filter(mut self, filter: BooleanArray) -> Self {
2235            self.filters.push(filter);
2236            self
2237        }
2238
2239        /// Replaces the input batches with `batches`
2240        fn with_batches(mut self, batches: impl IntoIterator<Item = RecordBatch>) -> Self {
2241            self.input_batches = batches.into_iter().collect();
2242            self
2243        }
2244
2245        /// Specifies the schema for the test
2246        fn with_schema(mut self, schema: SchemaRef) -> Self {
2247            self.schema = Some(schema);
2248            self
2249        }
2250
2251        /// Extends `sizes` to expected output sizes
2252        fn with_expected_output_sizes(mut self, sizes: impl IntoIterator<Item = usize>) -> Self {
2253            self.expected_output_sizes.extend(sizes);
2254            self
2255        }
2256
2257        /// Runs the test -- see documentation on [`Test`] for details
2258        ///
2259        /// Returns the resulting output batches
2260        fn run(self) -> Vec<RecordBatch> {
2261            // Test several permutations of input batches:
2262            // 1. Removing nulls from some batches (test non-null fast paths)
2263            // 2. Empty batches
2264            // 3. One column (from the batch)
2265            let mut extra_tests = vec![];
2266            extra_tests.push(self.clone().make_half_non_nullable());
2267            extra_tests.push(self.clone().insert_empty_batches());
2268            let single_column_tests = self.make_single_column_tests();
2269            for test in single_column_tests {
2270                extra_tests.push(test.clone().make_half_non_nullable());
2271                extra_tests.push(test);
2272            }
2273
2274            // Run original test case first, so any obvious errors are caught
2275            // by an easier to understand test case
2276            let results = self.run_inner();
2277            // Run the extra cases to expand coverage
2278            for extra in extra_tests {
2279                extra.run_inner();
2280            }
2281
2282            results
2283        }
2284
2285        /// Runs the current test instance
2286        fn run_inner(self) -> Vec<RecordBatch> {
2287            let expected_output = self.expected_output();
2288            let schema = self.schema();
2289
2290            let Self {
2291                name,
2292                input_batches,
2293                filters,
2294                schema: _,
2295                target_batch_size,
2296                expected_output_sizes,
2297            } = self;
2298
2299            println!("Running test '{name}'");
2300
2301            let had_input = input_batches.iter().any(|b| b.num_rows() > 0);
2302
2303            let mut coalescer = BatchCoalescer::new(Arc::clone(&schema), target_batch_size);
2304
2305            // feed input batches and filters to the coalescer
2306            let mut filters = filters.into_iter();
2307            for batch in input_batches {
2308                if let Some(filter) = filters.next() {
2309                    coalescer.push_batch_with_filter(batch, &filter).unwrap();
2310                } else {
2311                    coalescer.push_batch(batch).unwrap();
2312                }
2313            }
2314            assert_eq!(schema, coalescer.schema());
2315
2316            if had_input {
2317                assert!(!coalescer.is_empty(), "Coalescer should not be empty");
2318            } else {
2319                assert!(coalescer.is_empty(), "Coalescer should be empty");
2320            }
2321
2322            coalescer.finish_buffered_batch().unwrap();
2323            if had_input {
2324                assert!(
2325                    coalescer.has_completed_batch(),
2326                    "Coalescer should have completed batches"
2327                );
2328            }
2329
2330            let mut output_batches = vec![];
2331            while let Some(batch) = coalescer.next_completed_batch() {
2332                output_batches.push(batch);
2333            }
2334
2335            // make sure we got the expected number of output batches and content
2336            let mut starting_idx = 0;
2337            let actual_output_sizes: Vec<usize> =
2338                output_batches.iter().map(|b| b.num_rows()).collect();
2339            assert_eq!(
2340                expected_output_sizes, actual_output_sizes,
2341                "Unexpected number of rows in output batches\n\
2342                Expected\n{expected_output_sizes:#?}\nActual:{actual_output_sizes:#?}"
2343            );
2344            let iter = expected_output_sizes
2345                .iter()
2346                .zip(output_batches.iter())
2347                .enumerate();
2348
2349            // Verify that the actual contents of each output batch matches the expected output
2350            for (i, (expected_size, batch)) in iter {
2351                // compare the contents of the batch after normalization (using
2352                // `==` compares the underlying memory layout too)
2353                let expected_batch = expected_output.slice(starting_idx, *expected_size);
2354                let expected_batch = normalize_batch(expected_batch);
2355                let batch = normalize_batch(batch.clone());
2356                assert_eq!(
2357                    expected_batch, batch,
2358                    "Unexpected content in batch {i}:\
2359                    \n\nExpected:\n{expected_batch:#?}\n\nActual:\n{batch:#?}"
2360                );
2361                starting_idx += *expected_size;
2362            }
2363            output_batches
2364        }
2365
2366        /// Return the expected output schema. If not overridden by `with_schema`, it
2367        /// returns the schema of the first input batch.
2368        fn schema(&self) -> SchemaRef {
2369            self.schema
2370                .clone()
2371                .unwrap_or_else(|| Arc::clone(&self.input_batches[0].schema()))
2372        }
2373
2374        /// Returns the expected output as a single `RecordBatch`
2375        fn expected_output(&self) -> RecordBatch {
2376            let schema = self.schema();
2377            if self.filters.is_empty() {
2378                return concat_batches(&schema, &self.input_batches).unwrap();
2379            }
2380
2381            let mut filters = self.filters.iter();
2382            let filtered_batches = self
2383                .input_batches
2384                .iter()
2385                .map(|batch| {
2386                    if let Some(filter) = filters.next() {
2387                        filter_record_batch(batch, filter).unwrap()
2388                    } else {
2389                        batch.clone()
2390                    }
2391                })
2392                .collect::<Vec<_>>();
2393            concat_batches(&schema, &filtered_batches).unwrap()
2394        }
2395
2396        /// Return a copy of self where every other batch has had its nulls removed
2397        /// (there are often fast paths that are used when there are no nulls)
2398        fn make_half_non_nullable(mut self) -> Self {
2399            // remove the nulls from every other batch
2400            self.input_batches = self
2401                .input_batches
2402                .iter()
2403                .enumerate()
2404                .map(|(i, batch)| {
2405                    if i % 2 == 1 {
2406                        batch.clone()
2407                    } else {
2408                        Self::remove_nulls_from_batch(batch)
2409                    }
2410                })
2411                .collect();
2412            self.with_description("non-nullable")
2413        }
2414
2415        /// Insert several empty batches into the input before each existing input
2416        fn insert_empty_batches(mut self) -> Self {
2417            let empty_batch = RecordBatch::new_empty(self.schema());
2418            self.input_batches = self
2419                .input_batches
2420                .into_iter()
2421                .flat_map(|batch| [empty_batch.clone(), batch])
2422                .collect();
2423            let empty_filters = BooleanArray::builder(0).finish();
2424            self.filters = self
2425                .filters
2426                .into_iter()
2427                .flat_map(|filter| [empty_filters.clone(), filter])
2428                .collect();
2429            self.with_description("empty batches inserted")
2430        }
2431
2432        /// Sets one batch to be non-nullable by removing nulls from all columns
2433        fn remove_nulls_from_batch(batch: &RecordBatch) -> RecordBatch {
2434            let new_columns = batch
2435                .columns()
2436                .iter()
2437                .map(Self::remove_nulls_from_array)
2438                .collect::<Vec<_>>();
2439            let options = RecordBatchOptions::new().with_row_count(Some(batch.num_rows()));
2440            RecordBatch::try_new_with_options(batch.schema(), new_columns, &options).unwrap()
2441        }
2442
2443        fn remove_nulls_from_array(array: &ArrayRef) -> ArrayRef {
2444            make_array(array.to_data().into_builder().nulls(None).build().unwrap())
2445        }
2446
2447        /// Returns a set of tests where each test that is the sae as self, but
2448        /// has a single column from the original input batch
2449        ///
2450        /// This can be useful to single column optimizations, specifically
2451        /// filter optimization.
2452        fn make_single_column_tests(&self) -> Vec<Self> {
2453            let original_schema = self.schema();
2454            let mut new_tests = vec![];
2455            for column in original_schema.fields() {
2456                let single_column_schema = Arc::new(Schema::new(vec![column.clone()]));
2457
2458                let single_column_batches = self.input_batches.iter().map(|batch| {
2459                    let single_column = batch.column_by_name(column.name()).unwrap();
2460                    RecordBatch::try_new(
2461                        Arc::clone(&single_column_schema),
2462                        vec![single_column.clone()],
2463                    )
2464                    .unwrap()
2465                });
2466
2467                let single_column_test = self
2468                    .clone()
2469                    .with_schema(Arc::clone(&single_column_schema))
2470                    .with_batches(single_column_batches)
2471                    .with_description("single column")
2472                    .with_description(column.name());
2473
2474                new_tests.push(single_column_test);
2475            }
2476            new_tests
2477        }
2478    }
2479
2480    /// Return a RecordBatch with a UInt32Array with the specified range and
2481    /// every third value is null.
2482    fn uint32_batch<T: std::iter::Iterator<Item = u32>>(range: T) -> RecordBatch {
2483        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt32, true)]));
2484
2485        let array = UInt32Array::from_iter(range.map(|i| if i % 3 == 0 { None } else { Some(i) }));
2486        RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap()
2487    }
2488
2489    /// Return a RecordBatch with a UInt32Array with no nulls specified range
2490    fn uint32_batch_non_null<T: std::iter::Iterator<Item = u32>>(range: T) -> RecordBatch {
2491        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt32, false)]));
2492
2493        let array = UInt32Array::from_iter_values(range);
2494        RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap()
2495    }
2496
2497    /// Return a RecordBatch with a UInt64Array with no nulls specified range
2498    fn uint64_batch_non_null<T: std::iter::Iterator<Item = u64>>(range: T) -> RecordBatch {
2499        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt64, false)]));
2500
2501        let array = UInt64Array::from_iter_values(range);
2502        RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap()
2503    }
2504
2505    /// Return a RecordBatch with a StringArray with values `value0`, `value1`, ...
2506    /// and every third value is `None`.
2507    fn utf8_batch(range: Range<u32>) -> RecordBatch {
2508        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::Utf8, true)]));
2509
2510        let array = StringArray::from_iter(range.map(|i| {
2511            if i % 3 == 0 {
2512                None
2513            } else {
2514                Some(format!("value{i}"))
2515            }
2516        }));
2517
2518        RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap()
2519    }
2520
2521    /// Return a RecordBatch with a StringViewArray with (only) the specified values
2522    fn stringview_batch<'a>(values: impl IntoIterator<Item = Option<&'a str>>) -> RecordBatch {
2523        let schema = Arc::new(Schema::new(vec![Field::new(
2524            "c0",
2525            DataType::Utf8View,
2526            false,
2527        )]));
2528
2529        let array = StringViewArray::from_iter(values);
2530        RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap()
2531    }
2532
2533    /// Return a RecordBatch with a StringViewArray with num_rows by repeating
2534    /// values over and over.
2535    fn stringview_batch_repeated<'a>(
2536        num_rows: usize,
2537        values: impl IntoIterator<Item = Option<&'a str>>,
2538    ) -> RecordBatch {
2539        let schema = Arc::new(Schema::new(vec![Field::new(
2540            "c0",
2541            DataType::Utf8View,
2542            true,
2543        )]));
2544
2545        // Repeat the values to a total of num_rows
2546        let values: Vec<_> = values.into_iter().collect();
2547        let values_iter = std::iter::repeat(values.iter())
2548            .flatten()
2549            .copied()
2550            .take(num_rows);
2551
2552        let mut builder = StringViewBuilder::with_capacity(100).with_fixed_block_size(8192);
2553        for val in values_iter {
2554            builder.append_option(val);
2555        }
2556
2557        let array = builder.finish();
2558        RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap()
2559    }
2560
2561    /// Return a RecordBatch of 100 rows
2562    fn multi_column_batch(range: Range<i32>) -> RecordBatch {
2563        let int64_array = Int64Array::from_iter(
2564            range
2565                .clone()
2566                .map(|v| if v % 5 == 0 { None } else { Some(v as i64) }),
2567        );
2568        let string_view_array = StringViewArray::from_iter(range.clone().map(|v| {
2569            if v % 5 == 0 {
2570                None
2571            } else if v % 7 == 0 {
2572                Some(format!("This is a string longer than 12 bytes{v}"))
2573            } else {
2574                Some(format!("Short {v}"))
2575            }
2576        }));
2577        let string_array = StringArray::from_iter(range.clone().map(|v| {
2578            if v % 11 == 0 {
2579                None
2580            } else {
2581                Some(format!("Value {v}"))
2582            }
2583        }));
2584        let timestamp_array = TimestampNanosecondArray::from_iter(range.map(|v| {
2585            if v % 3 == 0 {
2586                None
2587            } else {
2588                Some(v as i64 * 1000) // simulate a timestamp in milliseconds
2589            }
2590        }))
2591        .with_timezone("America/New_York");
2592
2593        RecordBatch::try_from_iter(vec![
2594            ("int64", Arc::new(int64_array) as ArrayRef),
2595            ("stringview", Arc::new(string_view_array) as ArrayRef),
2596            ("string", Arc::new(string_array) as ArrayRef),
2597            ("timestamp", Arc::new(timestamp_array) as ArrayRef),
2598        ])
2599        .unwrap()
2600    }
2601
2602    /// Return a boolean array that filters out randomly selected rows
2603    /// from the input batch with a `selectivity`.
2604    ///
2605    /// For example a `selectivity` of 0.1 will filter out
2606    /// 90% of the rows.
2607    #[derive(Debug)]
2608    struct RandomFilterBuilder {
2609        /// Number of rows to add to each filter
2610        num_rows: usize,
2611        /// selectivity of the filter (between 0.0 and 1.0)
2612        /// 0 selects no rows, 1.0 selects all rows
2613        selectivity: f64,
2614        /// seed for random number generator, increases by one each time
2615        /// `next_filter` is called
2616        seed: u64,
2617    }
2618    impl RandomFilterBuilder {
2619        /// Build the next filter with the current seed and increment the seed
2620        /// by one.
2621        fn next_filter(&mut self) -> BooleanArray {
2622            assert!(self.selectivity >= 0.0 && self.selectivity <= 1.0);
2623            let mut rng = rand::rngs::StdRng::seed_from_u64(self.seed);
2624            self.seed += 1;
2625            BooleanArray::from_iter(
2626                (0..self.num_rows)
2627                    .map(|_| rng.random_bool(self.selectivity))
2628                    .map(Some),
2629            )
2630        }
2631    }
2632
2633    /// Returns the named column as a StringViewArray
2634    fn col_as_string_view<'b>(name: &str, batch: &'b RecordBatch) -> &'b StringViewArray {
2635        batch
2636            .column_by_name(name)
2637            .expect("column not found")
2638            .as_string_view_opt()
2639            .expect("column is not a string view")
2640    }
2641
2642    /// Filter that selects 12.5% of the rows (`idx % 8 == 0`)
2643    fn sparse_filter(len: usize) -> BooleanArray {
2644        BooleanArray::from_iter((0..len).map(|idx| Some(idx % 8 == 0)))
2645    }
2646
2647    /// Filter that selects 5% of the rows (`idx % 20 == 0`)
2648    ///
2649    /// Different code paths are taken for very sparse filters
2650    fn very_sparse_filter(len: usize) -> BooleanArray {
2651        BooleanArray::from_iter((0..len).map(|idx| Some(idx % 20 == 0)))
2652    }
2653
2654    /// Normalize the `RecordBatch` so that the memory layout is consistent
2655    /// (e.g. StringArray is compacted).
2656    fn normalize_batch(batch: RecordBatch) -> RecordBatch {
2657        // Only need to normalize StringViews (as == also tests for memory layout)
2658        let (schema, mut columns, row_count) = batch.into_parts();
2659
2660        for column in &mut columns {
2661            if let Some(string_view) = column.as_string_view_opt() {
2662                // Re-create the StringViewArray to ensure memory layout is
2663                // consistent
2664                let mut builder = StringViewBuilder::new();
2665                for s in string_view {
2666                    builder.append_option(s);
2667                }
2668                *column = Arc::new(builder.finish());
2669                continue;
2670            }
2671
2672            if let Some(binary_view) = column.as_binary_view_opt() {
2673                *column = Arc::new(BinaryViewArray::from_iter(binary_view.iter()));
2674            }
2675        }
2676
2677        let options = RecordBatchOptions::new().with_row_count(Some(row_count));
2678        RecordBatch::try_new_with_options(schema, columns, &options).unwrap()
2679    }
2680
2681    /// Helper function to create a test batch with specified number of rows
2682    fn create_test_batch(num_rows: usize) -> RecordBatch {
2683        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)]));
2684        let array = Int32Array::from_iter_values(0..num_rows as i32);
2685        RecordBatch::try_new(schema, vec![Arc::new(array)]).unwrap()
2686    }
2687    #[test]
2688    fn test_biggest_coalesce_batch_size_none_default() {
2689        // Test that default behavior (None) coalesces all batches
2690        let mut coalescer = BatchCoalescer::new(
2691            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2692            100,
2693        );
2694
2695        // Push a large batch (1000 rows) - should be coalesced normally
2696        let large_batch = create_test_batch(1000);
2697        coalescer.push_batch(large_batch).unwrap();
2698
2699        // Should produce multiple batches of target size (100)
2700        let mut output_batches = vec![];
2701        while let Some(batch) = coalescer.next_completed_batch() {
2702            output_batches.push(batch);
2703        }
2704
2705        coalescer.finish_buffered_batch().unwrap();
2706        while let Some(batch) = coalescer.next_completed_batch() {
2707            output_batches.push(batch);
2708        }
2709
2710        // Should have 10 batches of 100 rows each
2711        assert_eq!(output_batches.len(), 10);
2712        for batch in output_batches {
2713            assert_eq!(batch.num_rows(), 100);
2714        }
2715    }
2716
2717    #[test]
2718    fn test_biggest_coalesce_batch_size_bypass_large_batch() {
2719        // Test that batches larger than biggest_coalesce_batch_size bypass coalescing
2720        let mut coalescer = BatchCoalescer::new(
2721            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2722            100,
2723        );
2724        coalescer.set_biggest_coalesce_batch_size(Some(500));
2725
2726        // Push a large batch (1000 rows) - should bypass coalescing
2727        let large_batch = create_test_batch(1000);
2728        coalescer.push_batch(large_batch.clone()).unwrap();
2729
2730        // Should have one completed batch immediately (the original large batch)
2731        assert!(coalescer.has_completed_batch());
2732        let output_batch = coalescer.next_completed_batch().unwrap();
2733        assert_eq!(output_batch.num_rows(), 1000);
2734
2735        // Should be no more completed batches
2736        assert!(!coalescer.has_completed_batch());
2737        assert_eq!(coalescer.get_buffered_rows(), 0);
2738    }
2739
2740    #[test]
2741    fn test_biggest_coalesce_batch_size_coalesce_small_batch() {
2742        // Test that batches smaller than biggest_coalesce_batch_size are coalesced normally
2743        let mut coalescer = BatchCoalescer::new(
2744            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2745            100,
2746        )
2747        .with_biggest_coalesce_batch_size(Some(500));
2748
2749        // Push small batches that should be coalesced
2750        let small_batch = create_test_batch(50);
2751        coalescer.push_batch(small_batch.clone()).unwrap();
2752
2753        // Should not have completed batch yet (only 50 rows, target is 100)
2754        assert!(!coalescer.has_completed_batch());
2755        assert_eq!(coalescer.get_buffered_rows(), 50);
2756
2757        // Push another small batch
2758        coalescer.push_batch(small_batch).unwrap();
2759
2760        // Now should have a completed batch (100 rows total)
2761        assert!(coalescer.has_completed_batch());
2762        let output_batch = coalescer.next_completed_batch().unwrap();
2763        let size = output_batch
2764            .column(0)
2765            .as_primitive::<Int32Type>()
2766            .get_buffer_memory_size();
2767        assert_eq!(size, 400); // 100 rows * 4 bytes each
2768        assert_eq!(output_batch.num_rows(), 100);
2769
2770        assert_eq!(coalescer.get_buffered_rows(), 0);
2771    }
2772
2773    #[test]
2774    fn test_biggest_coalesce_batch_size_equal_boundary() {
2775        // Test behavior when batch size equals biggest_coalesce_batch_size
2776        let mut coalescer = BatchCoalescer::new(
2777            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2778            100,
2779        );
2780        coalescer.set_biggest_coalesce_batch_size(Some(500));
2781
2782        // Push a batch exactly equal to the limit
2783        let boundary_batch = create_test_batch(500);
2784        coalescer.push_batch(boundary_batch).unwrap();
2785
2786        // Should be coalesced (not bypass) since it's equal, not greater
2787        let mut output_count = 0;
2788        while coalescer.next_completed_batch().is_some() {
2789            output_count += 1;
2790        }
2791
2792        coalescer.finish_buffered_batch().unwrap();
2793        while coalescer.next_completed_batch().is_some() {
2794            output_count += 1;
2795        }
2796
2797        // Should have 5 batches of 100 rows each
2798        assert_eq!(output_count, 5);
2799    }
2800
2801    #[test]
2802    fn test_biggest_coalesce_batch_size_first_large_then_consecutive_bypass() {
2803        // Test the new consecutive large batch bypass behavior
2804        // Pattern: small batches -> first large batch (coalesced) -> consecutive large batches (bypass)
2805        let mut coalescer = BatchCoalescer::new(
2806            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2807            100,
2808        );
2809        coalescer.set_biggest_coalesce_batch_size(Some(200));
2810
2811        let small_batch = create_test_batch(50);
2812
2813        // Push small batch first to create buffered data
2814        coalescer.push_batch(small_batch).unwrap();
2815        assert_eq!(coalescer.get_buffered_rows(), 50);
2816        assert!(!coalescer.has_completed_batch());
2817
2818        // Push first large batch - should go through normal coalescing due to buffered data
2819        let large_batch1 = create_test_batch(250);
2820        coalescer.push_batch(large_batch1).unwrap();
2821
2822        // 50 + 250 = 300 -> 3 complete batches of 100, 0 rows buffered
2823        let mut completed_batches = vec![];
2824        while let Some(batch) = coalescer.next_completed_batch() {
2825            completed_batches.push(batch);
2826        }
2827        assert_eq!(completed_batches.len(), 3);
2828        assert_eq!(coalescer.get_buffered_rows(), 0);
2829
2830        // Now push consecutive large batches - they should bypass
2831        let large_batch2 = create_test_batch(300);
2832        let large_batch3 = create_test_batch(400);
2833
2834        // Push second large batch - should bypass since it's consecutive and buffer is empty
2835        coalescer.push_batch(large_batch2).unwrap();
2836        assert!(coalescer.has_completed_batch());
2837        let output = coalescer.next_completed_batch().unwrap();
2838        assert_eq!(output.num_rows(), 300); // bypassed with original size
2839        assert_eq!(coalescer.get_buffered_rows(), 0);
2840
2841        // Push third large batch - should also bypass
2842        coalescer.push_batch(large_batch3).unwrap();
2843        assert!(coalescer.has_completed_batch());
2844        let output = coalescer.next_completed_batch().unwrap();
2845        assert_eq!(output.num_rows(), 400); // bypassed with original size
2846        assert_eq!(coalescer.get_buffered_rows(), 0);
2847    }
2848
2849    #[test]
2850    fn test_biggest_coalesce_batch_size_empty_batch() {
2851        // Test that empty batches don't trigger the bypass logic
2852        let mut coalescer = BatchCoalescer::new(
2853            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2854            100,
2855        );
2856        coalescer.set_biggest_coalesce_batch_size(Some(50));
2857
2858        let empty_batch = create_test_batch(0);
2859        coalescer.push_batch(empty_batch).unwrap();
2860
2861        // Empty batch should be handled normally (no effect)
2862        assert!(!coalescer.has_completed_batch());
2863        assert_eq!(coalescer.get_buffered_rows(), 0);
2864    }
2865
2866    #[test]
2867    fn test_biggest_coalesce_batch_size_with_buffered_data_no_bypass() {
2868        // Test that when there is buffered data, large batches do NOT bypass (unless consecutive)
2869        let mut coalescer = BatchCoalescer::new(
2870            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2871            100,
2872        );
2873        coalescer.set_biggest_coalesce_batch_size(Some(200));
2874
2875        // Add some buffered data first
2876        let small_batch = create_test_batch(30);
2877        coalescer.push_batch(small_batch.clone()).unwrap();
2878        coalescer.push_batch(small_batch).unwrap();
2879        assert_eq!(coalescer.get_buffered_rows(), 60);
2880
2881        // Push large batch that would normally bypass, but shouldn't because buffered_rows > 0
2882        let large_batch = create_test_batch(250);
2883        coalescer.push_batch(large_batch).unwrap();
2884
2885        // The large batch should be processed through normal coalescing logic
2886        // Total: 60 (buffered) + 250 (new) = 310 rows
2887        // Output: 3 complete batches of 100 rows each, 10 rows remain buffered
2888
2889        let mut completed_batches = vec![];
2890        while let Some(batch) = coalescer.next_completed_batch() {
2891            completed_batches.push(batch);
2892        }
2893
2894        assert_eq!(completed_batches.len(), 3);
2895        for batch in &completed_batches {
2896            assert_eq!(batch.num_rows(), 100);
2897        }
2898        assert_eq!(coalescer.get_buffered_rows(), 10);
2899    }
2900
2901    #[test]
2902    fn test_biggest_coalesce_batch_size_zero_limit() {
2903        // Test edge case where limit is 0 (all batches bypass when no buffered data)
2904        let mut coalescer = BatchCoalescer::new(
2905            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2906            100,
2907        );
2908        coalescer.set_biggest_coalesce_batch_size(Some(0));
2909
2910        // Even a 1-row batch should bypass when there's no buffered data
2911        let tiny_batch = create_test_batch(1);
2912        coalescer.push_batch(tiny_batch).unwrap();
2913
2914        assert!(coalescer.has_completed_batch());
2915        let output = coalescer.next_completed_batch().unwrap();
2916        assert_eq!(output.num_rows(), 1);
2917    }
2918
2919    #[test]
2920    fn test_biggest_coalesce_batch_size_bypass_only_when_no_buffer() {
2921        // Test that bypass only occurs when buffered_rows == 0
2922        let mut coalescer = BatchCoalescer::new(
2923            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2924            100,
2925        );
2926        coalescer.set_biggest_coalesce_batch_size(Some(200));
2927
2928        // First, push a large batch with no buffered data - should bypass
2929        let large_batch = create_test_batch(300);
2930        coalescer.push_batch(large_batch.clone()).unwrap();
2931
2932        assert!(coalescer.has_completed_batch());
2933        let output = coalescer.next_completed_batch().unwrap();
2934        assert_eq!(output.num_rows(), 300); // bypassed
2935        assert_eq!(coalescer.get_buffered_rows(), 0);
2936
2937        // Now add some buffered data
2938        let small_batch = create_test_batch(50);
2939        coalescer.push_batch(small_batch).unwrap();
2940        assert_eq!(coalescer.get_buffered_rows(), 50);
2941
2942        // Push the same large batch again - should NOT bypass this time (not consecutive)
2943        coalescer.push_batch(large_batch).unwrap();
2944
2945        // Should process through normal coalescing: 50 + 300 = 350 rows
2946        // Output: 3 complete batches of 100 rows, 50 rows buffered
2947        let mut completed_batches = vec![];
2948        while let Some(batch) = coalescer.next_completed_batch() {
2949            completed_batches.push(batch);
2950        }
2951
2952        assert_eq!(completed_batches.len(), 3);
2953        for batch in &completed_batches {
2954            assert_eq!(batch.num_rows(), 100);
2955        }
2956        assert_eq!(coalescer.get_buffered_rows(), 50);
2957    }
2958
2959    #[test]
2960    fn test_biggest_coalesce_batch_size_consecutive_large_batches_scenario() {
2961        // Test your exact scenario: 20, 20, 30, 700, 600, 700, 900, 700, 600
2962        let mut coalescer = BatchCoalescer::new(
2963            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2964            1000,
2965        );
2966        coalescer.set_biggest_coalesce_batch_size(Some(500));
2967
2968        // Push small batches first
2969        coalescer.push_batch(create_test_batch(20)).unwrap();
2970        coalescer.push_batch(create_test_batch(20)).unwrap();
2971        coalescer.push_batch(create_test_batch(30)).unwrap();
2972
2973        assert_eq!(coalescer.get_buffered_rows(), 70);
2974        assert!(!coalescer.has_completed_batch());
2975
2976        // Push first large batch (700) - should coalesce due to buffered data
2977        coalescer.push_batch(create_test_batch(700)).unwrap();
2978
2979        // 70 + 700 = 770 rows, not enough for 1000, so all stay buffered
2980        assert_eq!(coalescer.get_buffered_rows(), 770);
2981        assert!(!coalescer.has_completed_batch());
2982
2983        // Push second large batch (600) - should bypass since previous was large
2984        coalescer.push_batch(create_test_batch(600)).unwrap();
2985
2986        // Should flush buffer (770 rows) and bypass the 600
2987        let mut outputs = vec![];
2988        while let Some(batch) = coalescer.next_completed_batch() {
2989            outputs.push(batch);
2990        }
2991        assert_eq!(outputs.len(), 2); // one flushed buffer batch (770) + one bypassed (600)
2992        assert_eq!(outputs[0].num_rows(), 770);
2993        assert_eq!(outputs[1].num_rows(), 600);
2994        assert_eq!(coalescer.get_buffered_rows(), 0);
2995
2996        // Push remaining large batches - should all bypass
2997        let remaining_batches = [700, 900, 700, 600];
2998        for &size in &remaining_batches {
2999            coalescer.push_batch(create_test_batch(size)).unwrap();
3000
3001            assert!(coalescer.has_completed_batch());
3002            let output = coalescer.next_completed_batch().unwrap();
3003            assert_eq!(output.num_rows(), size);
3004            assert_eq!(coalescer.get_buffered_rows(), 0);
3005        }
3006    }
3007
3008    #[test]
3009    fn test_biggest_coalesce_batch_size_truly_consecutive_large_bypass() {
3010        // Test truly consecutive large batches that should all bypass
3011        // This test ensures buffer is completely empty between large batches
3012        let mut coalescer = BatchCoalescer::new(
3013            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
3014            100,
3015        );
3016        coalescer.set_biggest_coalesce_batch_size(Some(200));
3017
3018        // Push consecutive large batches with no prior buffered data
3019        let large_batches = vec![
3020            create_test_batch(300),
3021            create_test_batch(400),
3022            create_test_batch(350),
3023            create_test_batch(500),
3024        ];
3025
3026        let mut all_outputs = vec![];
3027
3028        for (i, large_batch) in large_batches.into_iter().enumerate() {
3029            let expected_size = large_batch.num_rows();
3030
3031            // Buffer should be empty before each large batch
3032            assert_eq!(
3033                coalescer.get_buffered_rows(),
3034                0,
3035                "Buffer should be empty before batch {i}"
3036            );
3037
3038            coalescer.push_batch(large_batch).unwrap();
3039
3040            // Each large batch should bypass and produce exactly one output batch
3041            assert!(
3042                coalescer.has_completed_batch(),
3043                "Should have completed batch after pushing batch {i}"
3044            );
3045
3046            let output = coalescer.next_completed_batch().unwrap();
3047            assert_eq!(
3048                output.num_rows(),
3049                expected_size,
3050                "Batch {i} should have bypassed with original size"
3051            );
3052
3053            // Should be no more batches and buffer should be empty
3054            assert!(
3055                !coalescer.has_completed_batch(),
3056                "Should have no more completed batches after batch {i}"
3057            );
3058            assert_eq!(
3059                coalescer.get_buffered_rows(),
3060                0,
3061                "Buffer should be empty after batch {i}"
3062            );
3063
3064            all_outputs.push(output);
3065        }
3066
3067        // Verify we got exactly 4 output batches with original sizes
3068        assert_eq!(all_outputs.len(), 4);
3069        assert_eq!(all_outputs[0].num_rows(), 300);
3070        assert_eq!(all_outputs[1].num_rows(), 400);
3071        assert_eq!(all_outputs[2].num_rows(), 350);
3072        assert_eq!(all_outputs[3].num_rows(), 500);
3073    }
3074
3075    #[test]
3076    fn test_biggest_coalesce_batch_size_reset_consecutive_on_small_batch() {
3077        // Test that small batches reset the consecutive large batch tracking
3078        let mut coalescer = BatchCoalescer::new(
3079            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
3080            100,
3081        );
3082        coalescer.set_biggest_coalesce_batch_size(Some(200));
3083
3084        // Push first large batch - should bypass (no buffered data)
3085        coalescer.push_batch(create_test_batch(300)).unwrap();
3086        let output = coalescer.next_completed_batch().unwrap();
3087        assert_eq!(output.num_rows(), 300);
3088
3089        // Push second large batch - should bypass (consecutive)
3090        coalescer.push_batch(create_test_batch(400)).unwrap();
3091        let output = coalescer.next_completed_batch().unwrap();
3092        assert_eq!(output.num_rows(), 400);
3093
3094        // Push small batch - resets consecutive tracking
3095        coalescer.push_batch(create_test_batch(50)).unwrap();
3096        assert_eq!(coalescer.get_buffered_rows(), 50);
3097
3098        // Push large batch again - should NOT bypass due to buffered data
3099        coalescer.push_batch(create_test_batch(350)).unwrap();
3100
3101        // Should coalesce: 50 + 350 = 400 -> 4 complete batches of 100
3102        let mut outputs = vec![];
3103        while let Some(batch) = coalescer.next_completed_batch() {
3104            outputs.push(batch);
3105        }
3106        assert_eq!(outputs.len(), 4);
3107        for batch in outputs {
3108            assert_eq!(batch.num_rows(), 100);
3109        }
3110        assert_eq!(coalescer.get_buffered_rows(), 0);
3111    }
3112
3113    #[test]
3114    fn test_coalasce_push_batch_with_indices() {
3115        const MID_POINT: u32 = 2333;
3116        const TOTAL_ROWS: u32 = 23333;
3117        let batch1 = uint32_batch_non_null(0..MID_POINT);
3118        let batch2 = uint32_batch_non_null((MID_POINT..TOTAL_ROWS).rev());
3119
3120        let mut coalescer = BatchCoalescer::new(
3121            Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt32, false)])),
3122            TOTAL_ROWS as usize,
3123        );
3124        coalescer.push_batch(batch1).unwrap();
3125
3126        let rev_indices = (0..((TOTAL_ROWS - MID_POINT) as u64)).rev();
3127        let reversed_indices_batch = uint64_batch_non_null(rev_indices);
3128
3129        let reverse_indices = UInt64Array::from(reversed_indices_batch.column(0).to_data());
3130        coalescer
3131            .push_batch_with_indices(batch2, &reverse_indices)
3132            .unwrap();
3133
3134        coalescer.finish_buffered_batch().unwrap();
3135        let actual = coalescer.next_completed_batch().unwrap();
3136
3137        let expected = uint32_batch_non_null(0..TOTAL_ROWS);
3138
3139        assert_eq!(expected, actual);
3140    }
3141
3142    #[test]
3143    fn test_push_batch_interleaved() {
3144        let batch1 = record_batch!(("a", Int32, [10, 11, 12])).unwrap();
3145        let batch2 = record_batch!(("a", Int32, [20, 21, 22])).unwrap();
3146        let indices = [(0, 0), (1, 2), (0, 2), (1, 0)];
3147
3148        let mut coalescer = BatchCoalescer::new(batch1.schema(), 1000);
3149        coalescer
3150            .push_batch_interleaved(&[batch1, batch2], &indices)
3151            .unwrap();
3152        coalescer.finish_buffered_batch().unwrap();
3153
3154        let expected = record_batch!(("a", Int32, [10, 22, 12, 20])).unwrap();
3155        assert_eq!(coalescer.next_completed_batch().unwrap(), expected);
3156    }
3157
3158    #[test]
3159    fn test_push_batch_interleaved_matches_interleave_then_push() {
3160        let batch1 = record_batch!(("a", Int32, [1, 2, 3, 4])).unwrap();
3161        let batch2 = record_batch!(("a", Int32, [5, 6, 7])).unwrap();
3162        let indices = [(1, 2), (0, 0), (1, 0), (0, 3), (1, 1)];
3163
3164        let mut via_method = BatchCoalescer::new(batch1.schema(), 1000);
3165        via_method
3166            .push_batch_interleaved(&[batch1.clone(), batch2.clone()], &indices)
3167            .unwrap();
3168        via_method.finish_buffered_batch().unwrap();
3169
3170        let mut via_manual = BatchCoalescer::new(batch1.schema(), 1000);
3171        let interleaved = interleave_record_batch(&[&batch1, &batch2], &indices).unwrap();
3172        via_manual.push_batch(interleaved).unwrap();
3173        via_manual.finish_buffered_batch().unwrap();
3174
3175        assert_eq!(
3176            via_method.next_completed_batch().unwrap(),
3177            via_manual.next_completed_batch().unwrap()
3178        );
3179    }
3180
3181    #[test]
3182    fn test_push_batch_interleaved_rejects_empty_batches() {
3183        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
3184        let mut coalescer = BatchCoalescer::new(schema, 1000);
3185
3186        let err = coalescer.push_batch_interleaved(&[], &[]).unwrap_err();
3187        assert_eq!(
3188            err.to_string(),
3189            "Invalid argument error: push_batch_interleaved requires at least one input batch"
3190        );
3191    }
3192
3193    #[test]
3194    fn test_push_batch_schema_mismatch_fewer_columns() {
3195        // Coalescer expects 0 columns, batch has 1
3196        let empty_schema = Arc::new(Schema::empty());
3197        let mut coalescer = BatchCoalescer::new(empty_schema, 100);
3198        let batch = uint32_batch(0..5);
3199        let result = coalescer.push_batch(batch);
3200        assert!(result.is_err());
3201        let err = result.unwrap_err().to_string();
3202        assert!(
3203            err.contains("Batch has 1 columns but BatchCoalescer expects 0"),
3204            "unexpected error: {err}"
3205        );
3206    }
3207
3208    #[test]
3209    fn test_push_batch_schema_mismatch_more_columns() {
3210        // Coalescer expects 2 columns, batch has 1
3211        let schema = Arc::new(Schema::new(vec![
3212            Field::new("c0", DataType::UInt32, false),
3213            Field::new("c1", DataType::UInt32, false),
3214        ]));
3215        let mut coalescer = BatchCoalescer::new(schema, 100);
3216        let batch = uint32_batch(0..5);
3217        let result = coalescer.push_batch(batch);
3218        assert!(result.is_err());
3219        let err = result.unwrap_err().to_string();
3220        assert!(
3221            err.contains("Batch has 1 columns but BatchCoalescer expects 2"),
3222            "unexpected error: {err}"
3223        );
3224    }
3225
3226    #[test]
3227    fn test_push_batch_schema_mismatch_two_vs_zero() {
3228        // Coalescer expects 0 columns, batch has 2
3229        let empty_schema = Arc::new(Schema::empty());
3230        let mut coalescer = BatchCoalescer::new(empty_schema, 100);
3231        let schema = Arc::new(Schema::new(vec![
3232            Field::new("c0", DataType::UInt32, false),
3233            Field::new("c1", DataType::UInt32, false),
3234        ]));
3235        let batch = RecordBatch::try_new(
3236            schema,
3237            vec![
3238                Arc::new(UInt32Array::from(vec![1, 2, 3])),
3239                Arc::new(UInt32Array::from(vec![4, 5, 6])),
3240            ],
3241        )
3242        .unwrap();
3243        let result = coalescer.push_batch(batch);
3244        assert!(result.is_err());
3245        let err = result.unwrap_err().to_string();
3246        assert!(
3247            err.contains("Batch has 2 columns but BatchCoalescer expects 0"),
3248            "unexpected error: {err}"
3249        );
3250    }
3251
3252    #[test]
3253    fn test_size_grows_with_buffering_and_shrinks_when_draining() {
3254        let batch = uint32_batch(0..8);
3255        let mut coalescer = BatchCoalescer::new(batch.schema(), 21);
3256        let baseline = coalescer.size();
3257        assert!(baseline > 0, "size includes container capacities");
3258
3259        // Buffer rows without completing a batch
3260        coalescer.push_batch(batch.clone()).unwrap();
3261        assert!(coalescer.next_completed_batch().is_none());
3262        let buffered = coalescer.size();
3263        assert!(
3264            buffered > baseline,
3265            "buffering rows should grow size ({buffered} > {baseline})"
3266        );
3267
3268        // Push enough to complete several batches
3269        for _ in 0..10 {
3270            coalescer.push_batch(batch.clone()).unwrap();
3271        }
3272        let peak = coalescer.size();
3273        assert!(peak > buffered);
3274
3275        // Draining completed batches must never grow the reported size
3276        let mut prev = peak;
3277        let mut drained_any = false;
3278        while coalescer.next_completed_batch().is_some() {
3279            drained_any = true;
3280            let now = coalescer.size();
3281            assert!(now <= prev, "size grew while draining: {now} > {prev}");
3282            prev = now;
3283        }
3284        assert!(drained_any);
3285        assert!(
3286            prev < peak,
3287            "draining completed batches should release memory"
3288        );
3289    }
3290
3291    #[test]
3292    fn test_size_string_view_buffers_released_after_drain() {
3293        // Long strings spill into external data buffers, exercising the byte-view
3294        // size accounting through the real coalescer path (including compaction).
3295        let batch = stringview_batch_repeated(
3296            1000,
3297            [Some("this string is definitely longer than 12 bytes")],
3298        );
3299        let mut coalescer = BatchCoalescer::new(batch.schema(), 4096);
3300        let baseline = coalescer.size();
3301
3302        for _ in 0..20 {
3303            coalescer.push_batch(batch.clone()).unwrap();
3304        }
3305        let peak = coalescer.size();
3306        assert!(
3307            peak > baseline,
3308            "buffered string view data should grow size ({peak} > {baseline})"
3309        );
3310
3311        coalescer.finish_buffered_batch().unwrap();
3312        while coalescer.next_completed_batch().is_some() {}
3313
3314        // Once fully drained the in-progress byte-view buffers are released.
3315        let drained = coalescer.size();
3316        assert!(
3317            drained < peak,
3318            "draining should release buffered data ({drained} < {peak})"
3319        );
3320    }
3321
3322    /// Every byte added to the accounting must eventually be removed: running the
3323    /// exact same push/finish/drain sequence twice must report identical sizes.
3324    /// This catches accounting leaks and drift without hard-coding magic numbers.
3325    #[test]
3326    fn test_size_accounting_conserved_across_cycles() {
3327        // Primitive column: internal capacities stabilize after the first cycle
3328        // (unlike byte-view, whose buffer sizer keeps growing), so the readings
3329        // are deterministic across cycles.
3330        let batch = uint32_batch(0..8);
3331        let mut coalescer = BatchCoalescer::new(batch.schema(), 4096);
3332
3333        let run_cycle = |coalescer: &mut BatchCoalescer| {
3334            for _ in 0..20 {
3335                coalescer.push_batch(batch.clone()).unwrap();
3336            }
3337            coalescer.finish_buffered_batch().unwrap();
3338            let peak = coalescer.size();
3339            while coalescer.next_completed_batch().is_some() {}
3340            (peak, coalescer.size())
3341        };
3342
3343        let (peak1, drained1) = run_cycle(&mut coalescer);
3344        let (peak2, drained2) = run_cycle(&mut coalescer);
3345
3346        assert_eq!(
3347            peak1, peak2,
3348            "identical work must report identical peak size"
3349        );
3350        assert_eq!(
3351            drained1, drained2,
3352            "fully-drained size must be stable across cycles (no accounting leak)"
3353        );
3354        assert!(
3355            drained1 < peak1,
3356            "draining must release the accounted memory"
3357        );
3358    }
3359
3360    #[test]
3361    fn test_push_batch_with_indices_splits_at_target_batch_size() {
3362        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)]));
3363        let array = Int32Array::from_iter_values(0..1000i32);
3364        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap();
3365        let indices = UInt32Array::from_iter_values((0..1000u32).step_by(3));
3366        let target_batch_size = 100;
3367
3368        let mut coalescer = BatchCoalescer::new(Arc::clone(&schema), target_batch_size);
3369        coalescer
3370            .push_batch_with_indices(batch.clone(), &indices)
3371            .unwrap();
3372        coalescer.finish_buffered_batch().unwrap();
3373        let mut completed = vec![];
3374        while let Some(batch) = coalescer.next_completed_batch() {
3375            completed.push(batch);
3376        }
3377        for batch in &completed[..completed.len() - 1] {
3378            assert_eq!(batch.num_rows(), target_batch_size);
3379        }
3380
3381        let actual = concat_batches(&schema, completed.iter()).unwrap();
3382        let expected = take_record_batch(&batch, &indices).unwrap();
3383        assert_eq!(expected, actual);
3384    }
3385
3386    #[test]
3387    fn test_push_batch_with_indices_mixed_schema_with_nulls_splits_matches_take() {
3388        let fsb_size: i32 = 4;
3389        let schema = Arc::new(Schema::new(vec![
3390            Field::new("i", DataType::Int32, true),
3391            Field::new("s", DataType::Utf8, true),
3392            Field::new("b", DataType::Boolean, true),
3393            Field::new("f", DataType::FixedSizeBinary(fsb_size), true),
3394        ]));
3395
3396        let num_rows = 300usize;
3397        let int_col = Int32Array::from_iter(
3398            (0..num_rows as i32).map(|v| if v % 7 == 0 { None } else { Some(v) }),
3399        );
3400        let str_col = StringArray::from_iter((0..num_rows).map(|v| {
3401            if v % 5 == 0 {
3402                None
3403            } else {
3404                Some(format!("row-{v}"))
3405            }
3406        }));
3407        let bool_col = BooleanArray::from_iter(
3408            (0..num_rows).map(|v| if v % 11 == 0 { None } else { Some(v % 2 == 0) }),
3409        );
3410        let fsb_col = FixedSizeBinaryArray::try_from_sparse_iter_with_size(
3411            (0..num_rows).map(|v| {
3412                if v % 9 == 0 {
3413                    None
3414                } else {
3415                    let mut bytes = [0u8; 4];
3416                    bytes.copy_from_slice(&(v as u32).to_le_bytes());
3417                    Some(bytes)
3418                }
3419            }),
3420            fsb_size,
3421        )
3422        .unwrap();
3423
3424        let batch = RecordBatch::try_new(
3425            Arc::clone(&schema),
3426            vec![
3427                Arc::new(int_col),
3428                Arc::new(str_col),
3429                Arc::new(bool_col),
3430                Arc::new(fsb_col),
3431            ],
3432        )
3433        .unwrap();
3434
3435        let indices = UInt32Array::from_iter_values((0..num_rows as u32).step_by(2));
3436        // Prime < indices.len() (150) so the chunking loop in push_batch_with_index
3437        // runs multiple times and the final chunk is a partial batch (150 % 37 = 2).
3438        let target_batch_size = 37;
3439
3440        let mut coalescer = BatchCoalescer::new(Arc::clone(&schema), target_batch_size);
3441        coalescer
3442            .push_batch_with_indices(batch.clone(), &indices)
3443            .unwrap();
3444        coalescer.finish_buffered_batch().unwrap();
3445
3446        let mut completed = vec![];
3447        while let Some(b) = coalescer.next_completed_batch() {
3448            completed.push(b);
3449        }
3450        assert!(
3451            completed.len() > 1,
3452            "expected the output to span multiple batches"
3453        );
3454        for b in &completed[..completed.len() - 1] {
3455            assert_eq!(b.num_rows(), target_batch_size);
3456        }
3457
3458        let actual = concat_batches(&schema, completed.iter()).unwrap();
3459        let expected = take_record_batch(&batch, &indices).unwrap();
3460        assert_eq!(expected, actual);
3461    }
3462
3463    #[test]
3464    fn test_push_batch_with_indices_empty_is_noop() {
3465        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)]));
3466        let array = Int32Array::from_iter_values(0..4i32);
3467        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap();
3468        let indices = UInt32Array::from(Vec::<u32>::new());
3469
3470        let mut coalescer = BatchCoalescer::new(schema, 4096);
3471        coalescer.push_batch_with_indices(batch, &indices).unwrap();
3472        coalescer.finish_buffered_batch().unwrap();
3473        assert!(coalescer.next_completed_batch().is_none());
3474    }
3475
3476    #[test]
3477    fn test_push_batch_with_indices_rejects_schema_mismatch() {
3478        let schema = Arc::new(Schema::new(vec![
3479            Field::new("c0", DataType::Int32, false),
3480            Field::new("c1", DataType::Int32, false),
3481        ]));
3482        let mut coalescer = BatchCoalescer::new(schema, 100);
3483        let batch = RecordBatch::try_new(
3484            Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
3485            vec![Arc::new(Int32Array::from_iter_values(0..5i32))],
3486        )
3487        .unwrap();
3488        let indices = UInt32Array::from(vec![0u32, 1]);
3489        let err = coalescer
3490            .push_batch_with_indices(batch, &indices)
3491            .unwrap_err()
3492            .to_string();
3493        assert!(
3494            err.contains("Batch has 1 columns but BatchCoalescer expects 2"),
3495            "unexpected error: {err}"
3496        );
3497    }
3498
3499    #[test]
3500    fn test_push_batch_with_indices_oob_is_atomic_and_uniform() {
3501        let int_only_schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)]));
3502        let int_batch = RecordBatch::try_new(
3503            Arc::clone(&int_only_schema),
3504            vec![Arc::new(Int32Array::from_iter_values(0..64i32))],
3505        )
3506        .unwrap();
3507
3508        let view_schema = Arc::new(Schema::new(vec![Field::new(
3509            "c0",
3510            DataType::Utf8View,
3511            false,
3512        )]));
3513        let view_batch = RecordBatch::try_new(
3514            Arc::clone(&view_schema),
3515            vec![Arc::new(StringViewArray::from(vec!["a"; 64]))],
3516        )
3517        .unwrap();
3518        let mixed_schema = Arc::new(Schema::new(vec![
3519            Field::new("c0", DataType::Int32, false),
3520            Field::new("c1", DataType::Utf8View, false),
3521        ]));
3522        let mixed_batch = RecordBatch::try_new(
3523            Arc::clone(&mixed_schema),
3524            vec![
3525                Arc::new(Int32Array::from_iter_values(0..16i32)),
3526                Arc::new(StringViewArray::from(vec!["a"; 16])),
3527            ],
3528        )
3529        .unwrap();
3530
3531        let short_indices = UInt32Array::from(vec![0u32, 1, 99]);
3532        let long_indices = {
3533            let mut values: Vec<u32> = (0..39).collect();
3534            values.push(99);
3535            UInt32Array::from(values)
3536        };
3537        let mixed_indices = UInt32Array::from(vec![0u32, 1, 2, 3, 0, 1, 2, 99]);
3538
3539        for (schema, batch, indices, target_batch_size, source_len) in [
3540            (
3541                int_only_schema.clone(),
3542                int_batch.clone(),
3543                &short_indices,
3544                2,
3545                64,
3546            ),
3547            (int_only_schema, int_batch, &long_indices, 100, 64),
3548            (
3549                view_schema.clone(),
3550                view_batch.clone(),
3551                &short_indices,
3552                2,
3553                64,
3554            ),
3555            (view_schema, view_batch, &long_indices, 100, 64),
3556            (mixed_schema, mixed_batch, &mixed_indices, 4, 16),
3557        ] {
3558            let mut coalescer = BatchCoalescer::new(schema, target_batch_size);
3559            let err = coalescer
3560                .push_batch_with_indices(batch, indices)
3561                .unwrap_err()
3562                .to_string();
3563            let expected_err = format!(
3564                "Array index out of bounds, cannot get item at index 99 from {source_len} entries"
3565            );
3566            assert!(err.contains(&expected_err), "unexpected error: {err}");
3567            assert_eq!(coalescer.get_buffered_rows(), 0);
3568            assert!(!coalescer.has_completed_batch());
3569        }
3570    }
3571
3572    #[test]
3573    fn test_push_batch_with_indices_sparse_byte_view_bounded_size() {
3574        let schema = Arc::new(Schema::new(vec![Field::new(
3575            "v",
3576            DataType::BinaryView,
3577            false,
3578        )]));
3579        let rows_per_batch = 2048;
3580        let num_batches = 64;
3581        let target_batch_size = 4 * num_batches;
3582        let mut coalescer = BatchCoalescer::new(Arc::clone(&schema), target_batch_size);
3583
3584        for batch_idx in 0..num_batches {
3585            let values: Vec<Vec<u8>> = (0..rows_per_batch)
3586                .map(|row| {
3587                    format!("batch={batch_idx:04} row={row:04} padding padding padding")
3588                        .into_bytes()
3589                })
3590                .collect();
3591            let array = BinaryViewArray::from_iter(values.iter().map(|v| Some(v.as_slice())));
3592            assert!(
3593                !array.data_buffers().is_empty(),
3594                "need non-inline views to exercise the sparse path"
3595            );
3596            let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap();
3597            let indices = UInt32Array::from(vec![0u32]);
3598            coalescer.push_batch_with_indices(batch, &indices).unwrap();
3599        }
3600
3601        let max_expected_size = 256 * 1024;
3602        let retained_size = coalescer.size();
3603        assert!(
3604            retained_size < max_expected_size,
3605            "retained {retained_size} bytes; expected under {max_expected_size}",
3606        );
3607    }
3608
3609    #[test]
3610    fn test_push_batch_with_indices_preserves_biggest_bypass() {
3611        let schema = Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)]));
3612        let array = Int32Array::from_iter_values(0..1000i32);
3613        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap();
3614
3615        let mut coalescer = BatchCoalescer::new(Arc::clone(&schema), 100)
3616            .with_biggest_coalesce_batch_size(Some(50));
3617
3618        let indices = UInt32Array::from_iter_values(0..500u32);
3619        coalescer.push_batch_with_indices(batch, &indices).unwrap();
3620
3621        let output = coalescer.next_completed_batch().expect("one batch");
3622        assert_eq!(output.num_rows(), 500);
3623        assert!(coalescer.next_completed_batch().is_none());
3624    }
3625}