1use 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;
23mod 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
44pub(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 | DataType::Utf8View
81 | DataType::BinaryView
82 | DataType::List(_)
83 | DataType::LargeList(_)
84 )
85}
86
87const 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
98const 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
106const INDEXED_COPY_MAX_SELECTIVITY_DENOMINATOR: usize = 2;
108
109const 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#[derive(Debug)]
212pub struct BatchCoalescer {
213 schema: SchemaRef,
215 target_batch_size: usize,
219 in_progress_arrays: Vec<Box<dyn InProgressArray>>,
221 has_non_specialized_filter_columns: bool,
223 has_byte_array_columns: bool,
225 has_byte_view_columns: bool,
227 buffered_rows: usize,
229 completed: VecDeque<RecordBatch>,
231 biggest_coalesce_batch_size: Option<usize>,
233}
234
235impl BatchCoalescer {
236 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 completed: VecDeque::with_capacity(1),
273 buffered_rows: 0,
274 biggest_coalesce_batch_size: None,
275 }
276 }
277
278 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 pub fn biggest_coalesce_batch_size(&self) -> Option<usize> {
299 self.biggest_coalesce_batch_size
300 }
301
302 pub fn set_biggest_coalesce_batch_size(&mut self, limit: Option<usize>) {
306 self.biggest_coalesce_batch_size = limit;
307 }
308
309 pub fn schema(&self) -> SchemaRef {
311 Arc::clone(&self.schema)
312 }
313
314 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 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 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 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 let columns = unsafe { take_arrays_unchecked(batch.columns(), u32_arr)? };
453 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 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 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 let refs: Vec<&RecordBatch> = batches.iter().collect();
552 let interleaved = interleave_record_batch(&refs, indices)?;
553 self.push_batch(interleaved)
554 }
555
556 pub fn push_batch(&mut self, batch: RecordBatch) -> Result<(), ArrowError> {
583 let batch_size = batch.num_rows();
702
703 if batch_size == 0 {
705 return Ok(());
706 }
707
708 if let Some(limit) = self.biggest_coalesce_batch_size
710 && batch_size > limit
711 {
712 if self.buffered_rows == 0 {
715 self.completed.push_back(batch);
716 return Ok(());
717 }
718
719 if self.buffered_rows > limit {
724 self.finish_buffered_batch()?;
725 self.completed.push_back(batch);
726 return Ok(());
727 }
728
729 }
734
735 let (_schema, arrays, mut num_rows) = batch.into_parts();
736
737 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 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 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 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 self.buffered_rows >= self.target_batch_size {
781 self.finish_buffered_batch()?;
782 }
783
784 for in_progress in &mut self.in_progress_arrays {
786 in_progress.set_source(None);
787 }
788
789 Ok(())
790 }
791
792 pub fn get_buffered_rows(&self) -> usize {
794 self.buffered_rows
795 }
796
797 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 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 pub fn is_empty(&self) -> bool {
839 self.buffered_rows == 0 && self.completed.is_empty()
840 }
841
842 pub fn has_completed_batch(&self) -> bool {
844 !self.completed.is_empty()
845 }
846
847 pub fn next_completed_batch(&mut self) -> Option<RecordBatch> {
849 self.completed.pop_front()
850 }
851
852 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 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
947fn 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 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
987fn 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
1002trait InProgressArray: std::fmt::Debug + Send + Sync {
1012 #[cfg_attr(not(test), expect(dead_code))]
1014 fn supports_dense_indexed_copy(&self) -> bool {
1015 false
1016 }
1017
1018 fn set_source(&mut self, source: Option<ArrayRef>);
1023
1024 fn copy_rows(&mut self, offset: usize, len: usize) -> Result<(), ArrowError>;
1030
1031 fn copy_rows_by_filter(&mut self, filter: &FilterPredicate) -> Result<(), ArrowError> {
1035 self.copy_rows_by_selection(filter.selection())
1036 }
1037
1038 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 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 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 fn finish(&mut self) -> Result<ArrayRef, ArrowError>;
1098
1099 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 .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); Test::new("coalesce_one_by_one")
1137 .with_batches(std::iter::repeat_n(batch, 97))
1138 .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 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 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 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 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 #[test]
1275 #[cfg_attr(miri, ignore)] 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 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 #[test]
1299 #[cfg_attr(miri, ignore)] 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 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 #[test]
1323 #[cfg_attr(miri, ignore)] 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 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 #[test]
1347 #[cfg_attr(miri, ignore)] 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 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 #[test]
1371 #[cfg_attr(miri, ignore)] 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 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 filter_builder.selectivity *= 0.6;
1396 }
1397
1398 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 let filter = BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]);
1412 let expected = record_batch!(("a", Int32, [1, 4])).unwrap();
1413
1414 let with_count = unsafe { FilterBuilder::new(&filter).with_count(2) };
1416 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 .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)] fn test_utf8_split() {
1443 Test::new("coalesce_utf8")
1444 .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 .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 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()); expect_buffer_layout(gc_array, vec![]);
1482 }
1483
1484 #[test]
1485 #[cfg_attr(miri, ignore)] fn test_string_view_batch_large_no_compact() {
1487 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()); 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 let short_strings = std::iter::repeat(Some("SmallString"));
1531 let long_strings = std::iter::once(Some("This string is longer than 12 bytes"));
1532 let values = short_strings.take(20).chain(long_strings);
1534 let batch = stringview_batch_repeated(1000, values)
1535 .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); assert_eq!(gc_array.data_buffers().len(), 0); }
1548
1549 #[test]
1550 fn test_string_view_batch_large_slice_compact() {
1551 let batch = stringview_batch_repeated(1000, [Some("This string is longer than 12 bytes")])
1553 .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)] 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 let output_batches = Test::new("coalesce_string_view_mixed")
1597 .with_batch(large_view_batch.clone())
1598 .with_batch(small_view_batch)
1599 .with_batch(large_view_batch.slice(10, 20))
1601 .with_batch(mixed_batch_nulls)
1602 .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)] fn test_string_view_many_small_compact() {
1638 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 .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]) .run();
1660
1661 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)] fn test_string_view_many_small_boundary() {
1684 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_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)] fn test_string_view_large_small() {
1715 let mixed_batch = stringview_batch_repeated(
1717 200,
1718 [Some("This string is 28 bytes long"), Some("small string")],
1719 );
1720 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 .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)] 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 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 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 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 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 #[derive(Debug, Clone)]
2175 struct Test {
2176 name: String,
2178 input_batches: Vec<RecordBatch>,
2180 filters: Vec<BooleanArray>,
2185 schema: Option<SchemaRef>,
2187 expected_output_sizes: Vec<usize>,
2189 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 fn with_description(mut self, description: &str) -> Self {
2216 self.name.push_str(": ");
2217 self.name.push_str(description);
2218 self
2219 }
2220
2221 fn with_batch_size(mut self, target_batch_size: usize) -> Self {
2223 self.target_batch_size = target_batch_size;
2224 self
2225 }
2226
2227 fn with_batch(mut self, batch: RecordBatch) -> Self {
2229 self.input_batches.push(batch);
2230 self
2231 }
2232
2233 fn with_filter(mut self, filter: BooleanArray) -> Self {
2235 self.filters.push(filter);
2236 self
2237 }
2238
2239 fn with_batches(mut self, batches: impl IntoIterator<Item = RecordBatch>) -> Self {
2241 self.input_batches = batches.into_iter().collect();
2242 self
2243 }
2244
2245 fn with_schema(mut self, schema: SchemaRef) -> Self {
2247 self.schema = Some(schema);
2248 self
2249 }
2250
2251 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 fn run(self) -> Vec<RecordBatch> {
2261 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 let results = self.run_inner();
2277 for extra in extra_tests {
2279 extra.run_inner();
2280 }
2281
2282 results
2283 }
2284
2285 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 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 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 for (i, (expected_size, batch)) in iter {
2351 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 fn schema(&self) -> SchemaRef {
2369 self.schema
2370 .clone()
2371 .unwrap_or_else(|| Arc::clone(&self.input_batches[0].schema()))
2372 }
2373
2374 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 fn make_half_non_nullable(mut self) -> Self {
2399 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 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 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 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 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 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 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 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 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 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 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 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) }
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 #[derive(Debug)]
2608 struct RandomFilterBuilder {
2609 num_rows: usize,
2611 selectivity: f64,
2614 seed: u64,
2617 }
2618 impl RandomFilterBuilder {
2619 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 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 fn sparse_filter(len: usize) -> BooleanArray {
2644 BooleanArray::from_iter((0..len).map(|idx| Some(idx % 8 == 0)))
2645 }
2646
2647 fn very_sparse_filter(len: usize) -> BooleanArray {
2651 BooleanArray::from_iter((0..len).map(|idx| Some(idx % 20 == 0)))
2652 }
2653
2654 fn normalize_batch(batch: RecordBatch) -> RecordBatch {
2657 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 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 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 let mut coalescer = BatchCoalescer::new(
2691 Arc::new(Schema::new(vec![Field::new("c0", DataType::Int32, false)])),
2692 100,
2693 );
2694
2695 let large_batch = create_test_batch(1000);
2697 coalescer.push_batch(large_batch).unwrap();
2698
2699 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 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 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 let large_batch = create_test_batch(1000);
2728 coalescer.push_batch(large_batch.clone()).unwrap();
2729
2730 assert!(coalescer.has_completed_batch());
2732 let output_batch = coalescer.next_completed_batch().unwrap();
2733 assert_eq!(output_batch.num_rows(), 1000);
2734
2735 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 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 let small_batch = create_test_batch(50);
2751 coalescer.push_batch(small_batch.clone()).unwrap();
2752
2753 assert!(!coalescer.has_completed_batch());
2755 assert_eq!(coalescer.get_buffered_rows(), 50);
2756
2757 coalescer.push_batch(small_batch).unwrap();
2759
2760 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); 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 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 let boundary_batch = create_test_batch(500);
2784 coalescer.push_batch(boundary_batch).unwrap();
2785
2786 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 assert_eq!(output_count, 5);
2799 }
2800
2801 #[test]
2802 fn test_biggest_coalesce_batch_size_first_large_then_consecutive_bypass() {
2803 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 coalescer.push_batch(small_batch).unwrap();
2815 assert_eq!(coalescer.get_buffered_rows(), 50);
2816 assert!(!coalescer.has_completed_batch());
2817
2818 let large_batch1 = create_test_batch(250);
2820 coalescer.push_batch(large_batch1).unwrap();
2821
2822 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 let large_batch2 = create_test_batch(300);
2832 let large_batch3 = create_test_batch(400);
2833
2834 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); assert_eq!(coalescer.get_buffered_rows(), 0);
2840
2841 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); assert_eq!(coalescer.get_buffered_rows(), 0);
2847 }
2848
2849 #[test]
2850 fn test_biggest_coalesce_batch_size_empty_batch() {
2851 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 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 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 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 let large_batch = create_test_batch(250);
2883 coalescer.push_batch(large_batch).unwrap();
2884
2885 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 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 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 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 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); assert_eq!(coalescer.get_buffered_rows(), 0);
2936
2937 let small_batch = create_test_batch(50);
2939 coalescer.push_batch(small_batch).unwrap();
2940 assert_eq!(coalescer.get_buffered_rows(), 50);
2941
2942 coalescer.push_batch(large_batch).unwrap();
2944
2945 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 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 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 coalescer.push_batch(create_test_batch(700)).unwrap();
2978
2979 assert_eq!(coalescer.get_buffered_rows(), 770);
2981 assert!(!coalescer.has_completed_batch());
2982
2983 coalescer.push_batch(create_test_batch(600)).unwrap();
2985
2986 let mut outputs = vec![];
2988 while let Some(batch) = coalescer.next_completed_batch() {
2989 outputs.push(batch);
2990 }
2991 assert_eq!(outputs.len(), 2); 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 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 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 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 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 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 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 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 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 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 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 coalescer.push_batch(create_test_batch(50)).unwrap();
3096 assert_eq!(coalescer.get_buffered_rows(), 50);
3097
3098 coalescer.push_batch(create_test_batch(350)).unwrap();
3100
3101 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 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 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 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 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 for _ in 0..10 {
3270 coalescer.push_batch(batch.clone()).unwrap();
3271 }
3272 let peak = coalescer.size();
3273 assert!(peak > buffered);
3274
3275 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 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 let drained = coalescer.size();
3316 assert!(
3317 drained < peak,
3318 "draining should release buffered data ({drained} < {peak})"
3319 );
3320 }
3321
3322 #[test]
3326 fn test_size_accounting_conserved_across_cycles() {
3327 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 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}