1use crate::{FileRange, PartitionedFile};
8use arrow::compute::SortOptions;
9use datafusion_common::utils::compare_rows;
10use datafusion_common::{ScalarValue, SplitPoint, Statistics};
11use itertools::Itertools;
12use std::cmp::{Ordering, min};
13use std::collections::{BinaryHeap, HashMap};
14use std::iter::repeat_with;
15use std::mem;
16use std::ops::{Deref, DerefMut, Index, IndexMut};
17use std::sync::Arc;
18
19#[derive(Debug, Clone, Copy)]
118pub struct FileGroupPartitioner {
119 target_partitions: usize,
121 repartition_file_min_size: usize,
123 preserve_order_within_groups: bool,
125}
126
127impl Default for FileGroupPartitioner {
128 fn default() -> Self {
129 Self::new()
130 }
131}
132
133impl FileGroupPartitioner {
134 pub fn new() -> Self {
139 Self {
140 target_partitions: 1,
141 repartition_file_min_size: 10 * 1024 * 1024,
142 preserve_order_within_groups: false,
143 }
144 }
145
146 pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
148 self.target_partitions = target_partitions;
149 self
150 }
151
152 pub fn with_repartition_file_min_size(
154 mut self,
155 repartition_file_min_size: usize,
156 ) -> Self {
157 self.repartition_file_min_size = repartition_file_min_size;
158 self
159 }
160
161 pub fn with_preserve_order_within_groups(
163 mut self,
164 preserve_order_within_groups: bool,
165 ) -> Self {
166 self.preserve_order_within_groups = preserve_order_within_groups;
167 self
168 }
169
170 pub fn repartition_file_groups(
174 &self,
175 file_groups: &[FileGroup],
176 ) -> Option<Vec<FileGroup>> {
177 if file_groups.is_empty() {
178 return None;
179 }
180
181 if self.preserve_order_within_groups {
183 self.repartition_preserving_order(file_groups)
184 } else {
185 self.repartition_evenly_by_size(file_groups)
186 }
187 }
188
189 fn repartition_evenly_by_size(
192 &self,
193 file_groups: &[FileGroup],
194 ) -> Option<Vec<FileGroup>> {
195 let target_partitions = self.target_partitions;
196 let repartition_file_min_size = self.repartition_file_min_size;
197 let flattened_files = file_groups.iter().flat_map(FileGroup::iter).collect_vec();
198
199 let total_size = flattened_files
200 .iter()
201 .map(|f| f.effective_size())
202 .sum::<u64>();
203 if total_size < (repartition_file_min_size as u64) || total_size == 0 {
204 return None;
205 }
206
207 let target_partition_size = total_size.div_ceil(target_partitions as u64);
208
209 let current_partition_index: usize = 0;
210 let current_partition_size: u64 = 0;
211
212 let repartitioned_files = flattened_files
214 .into_iter()
215 .scan(
216 (current_partition_index, current_partition_size),
217 |(current_partition_index, current_partition_size), source_file| {
218 let mut produced_files = vec![];
219 let (mut range_start, file_end) = source_file.range();
220 while range_start < file_end {
221 let range_end = min(
222 range_start
223 + (target_partition_size - *current_partition_size),
224 file_end,
225 );
226
227 let mut produced_file = source_file.clone();
228 produced_file.range = Some(FileRange {
229 start: range_start as i64,
230 end: range_end as i64,
231 });
232 produced_files.push((*current_partition_index, produced_file));
233
234 if *current_partition_size + (range_end - range_start)
235 >= target_partition_size
236 {
237 *current_partition_index += 1;
238 *current_partition_size = 0;
239 } else {
240 *current_partition_size += range_end - range_start;
241 }
242 range_start = range_end;
243 }
244 Some(produced_files)
245 },
246 )
247 .flatten()
248 .chunk_by(|(partition_idx, _)| *partition_idx)
249 .into_iter()
250 .map(|(_, group)| FileGroup::new(group.map(|(_, vals)| vals).collect_vec()))
251 .collect_vec();
252
253 Some(repartitioned_files)
254 }
255
256 fn repartition_preserving_order(
258 &self,
259 file_groups: &[FileGroup],
260 ) -> Option<Vec<FileGroup>> {
261 if file_groups.len() >= self.target_partitions {
264 return None;
265 }
266 let num_new_groups = self.target_partitions - file_groups.len();
267
268 if file_groups.len() == 1 && file_groups[0].len() == 1 {
270 return self.repartition_evenly_by_size(file_groups);
271 }
272
273 let mut heap: BinaryHeap<_> = file_groups
275 .iter()
276 .enumerate()
277 .filter_map(|(group_index, group)| {
278 if group.len() == 1 {
280 Some(ToRepartition {
281 source_index: group_index,
282 file_size: group[0].effective_size(),
283 new_groups: vec![group_index],
284 })
285 } else {
286 None
287 }
288 })
289 .map(CompareByRangeSize)
290 .collect();
291
292 if heap.is_empty() {
294 return None;
295 }
296
297 let mut file_groups: Vec<_> = file_groups
300 .iter()
301 .cloned()
302 .chain(repeat_with(|| FileGroup::new(Vec::new())).take(num_new_groups))
303 .collect();
304
305 for (group_index, group) in file_groups.iter().enumerate() {
307 if !group.is_empty() {
308 continue;
309 }
310 let mut largest_group = heap.pop().unwrap();
312 largest_group.new_groups.push(group_index);
313 heap.push(largest_group);
314 }
315
316 while let Some(to_repartition) = heap.pop() {
318 let range_size = to_repartition.range_size();
319 let ToRepartition {
320 source_index,
321 file_size: _,
322 new_groups,
323 } = to_repartition.into_inner();
324 assert_eq!(file_groups[source_index].len(), 1);
325 let original_file = file_groups[source_index].pop().unwrap();
326
327 let last_group = new_groups.len() - 1;
328 let (mut range_start, file_end) = original_file.range();
329 let mut range_end = range_start + range_size;
330 for (i, group_index) in new_groups.into_iter().enumerate() {
331 let target_group = &mut file_groups[group_index];
332 assert!(target_group.is_empty());
333
334 if i == last_group {
336 range_end = file_end;
337 }
338 target_group.push(
339 original_file
340 .clone()
341 .with_range(range_start as i64, range_end as i64),
342 );
343 range_start = range_end;
344 range_end += range_size;
345 }
346 }
347
348 Some(file_groups)
349 }
350}
351
352#[derive(Debug, Clone)]
369pub struct FileGroup {
370 files: Vec<PartitionedFile>,
372 statistics: Option<Arc<Statistics>>,
378}
379
380impl FileGroup {
381 pub fn new(files: Vec<PartitionedFile>) -> Self {
383 Self {
384 files,
385 statistics: None,
386 }
387 }
388
389 pub fn len(&self) -> usize {
391 self.files.len()
392 }
393
394 pub fn with_statistics(mut self, statistics: Arc<Statistics>) -> Self {
396 self.statistics = Some(statistics);
397 self
398 }
399
400 pub fn files(&self) -> &[PartitionedFile] {
402 &self.files
403 }
404
405 pub fn iter(&self) -> impl Iterator<Item = &PartitionedFile> {
406 self.files.iter()
407 }
408
409 pub fn into_inner(self) -> Vec<PartitionedFile> {
410 self.files
411 }
412
413 pub fn is_empty(&self) -> bool {
414 self.files.is_empty()
415 }
416
417 pub fn pop(&mut self) -> Option<PartitionedFile> {
419 self.files.pop()
420 }
421
422 pub fn push(&mut self, partitioned_file: PartitionedFile) {
424 self.files.push(partitioned_file);
425 }
426
427 pub fn file_statistics(&self, index: Option<usize>) -> Option<&Statistics> {
430 if let Some(index) = index {
431 self.files.get(index).and_then(|f| f.statistics.as_deref())
432 } else {
433 self.statistics.as_deref()
434 }
435 }
436
437 pub fn statistics_mut(&mut self) -> Option<&mut Statistics> {
439 self.statistics.as_mut().map(Arc::make_mut)
440 }
441
442 pub fn split_files(mut self, n: usize) -> Vec<FileGroup> {
444 if self.is_empty() {
445 return vec![];
446 }
447
448 self.files.sort_by(|a, b| a.path().cmp(b.path()));
452
453 let chunk_size = self.len().div_ceil(n);
455 let mut chunks = Vec::with_capacity(n);
456 let mut current_chunk = Vec::with_capacity(chunk_size);
457 for file in self.files.drain(..) {
458 current_chunk.push(file);
459 if current_chunk.len() == chunk_size {
460 let full_chunk = FileGroup::new(mem::replace(
461 &mut current_chunk,
462 Vec::with_capacity(chunk_size),
463 ));
464 chunks.push(full_chunk);
465 }
466 }
467
468 if !current_chunk.is_empty() {
469 chunks.push(FileGroup::new(current_chunk))
470 }
471
472 chunks
473 }
474
475 pub fn group_by_partition_values(
484 self,
485 max_target_partitions: usize,
486 ) -> Vec<FileGroup> {
487 self.group_by_partition_values_with_split_points(max_target_partitions)
488 .0
489 }
490
491 #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
497 pub fn group_by_partition_values_with_split_points(
498 self,
499 max_target_partitions: usize,
500 ) -> (Vec<FileGroup>, Vec<SplitPoint>) {
501 if self.is_empty() || max_target_partitions == 0 {
502 return (vec![], vec![]);
503 }
504
505 let mut partition_groups: HashMap<Vec<ScalarValue>, Vec<PartitionedFile>> =
506 HashMap::new();
507
508 for file in self.files {
509 partition_groups
510 .entry(file.partition_values.clone())
511 .or_default()
512 .push(file);
513 }
514
515 let num_unique_partitions = partition_groups.len();
516
517 let mut sorted_partitions: Vec<_> = partition_groups.into_iter().collect();
521 let sort_options =
522 vec![
523 SortOptions::default();
524 sorted_partitions.first().map(|(k, _)| k.len()).unwrap_or(0)
525 ];
526 sorted_partitions.sort_by(|a, b| {
527 compare_rows(&a.0, &b.0, &sort_options).unwrap_or(Ordering::Equal)
528 });
529
530 let bucket_count = min(num_unique_partitions, max_target_partitions);
531 let mut groups = Vec::with_capacity(bucket_count);
532 let mut split_points = Vec::with_capacity(bucket_count.saturating_sub(1));
533
534 let mut iter = sorted_partitions.into_iter();
537 for bucket in 0..bucket_count {
538 let start = bucket * num_unique_partitions / bucket_count;
539 let end = (bucket + 1) * num_unique_partitions / bucket_count;
540 let mut files = Vec::new();
541 for offset in start..end {
542 let (values, group_files) = iter
543 .next()
544 .expect("contiguous chunking never runs past the sorted partitions");
545 if offset == start && bucket > 0 {
546 split_points.push(SplitPoint::new(values));
547 }
548 files.extend(group_files);
549 }
550 groups.push(FileGroup::new(files));
551 }
552 debug_assert_eq!(split_points.len() + 1, groups.len());
553
554 (groups, split_points)
555 }
556}
557
558impl Index<usize> for FileGroup {
559 type Output = PartitionedFile;
560
561 fn index(&self, index: usize) -> &Self::Output {
562 &self.files[index]
563 }
564}
565
566impl IndexMut<usize> for FileGroup {
567 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
568 &mut self.files[index]
569 }
570}
571
572impl FromIterator<PartitionedFile> for FileGroup {
573 fn from_iter<I: IntoIterator<Item = PartitionedFile>>(iter: I) -> Self {
574 let files = iter.into_iter().collect();
575 FileGroup::new(files)
576 }
577}
578
579impl From<Vec<PartitionedFile>> for FileGroup {
580 fn from(files: Vec<PartitionedFile>) -> Self {
581 FileGroup::new(files)
582 }
583}
584
585impl Default for FileGroup {
586 fn default() -> Self {
587 Self::new(Vec::new())
588 }
589}
590
591#[derive(Debug, Clone)]
593struct ToRepartition {
594 source_index: usize,
596 file_size: u64,
598 new_groups: Vec<usize>,
600}
601
602impl ToRepartition {
603 fn range_size(&self) -> u64 {
605 self.file_size / (self.new_groups.len() as u64)
606 }
607}
608
609struct CompareByRangeSize(ToRepartition);
610impl CompareByRangeSize {
611 fn into_inner(self) -> ToRepartition {
612 self.0
613 }
614}
615impl Ord for CompareByRangeSize {
616 fn cmp(&self, other: &Self) -> Ordering {
617 self.0.range_size().cmp(&other.0.range_size())
618 }
619}
620impl PartialOrd for CompareByRangeSize {
621 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
622 Some(self.cmp(other))
623 }
624}
625impl PartialEq for CompareByRangeSize {
626 fn eq(&self, other: &Self) -> bool {
627 self.cmp(other) == Ordering::Equal
629 }
630}
631impl Eq for CompareByRangeSize {}
632impl Deref for CompareByRangeSize {
633 type Target = ToRepartition;
634 fn deref(&self) -> &Self::Target {
635 &self.0
636 }
637}
638impl DerefMut for CompareByRangeSize {
639 fn deref_mut(&mut self) -> &mut Self::Target {
640 &mut self.0
641 }
642}
643
644#[cfg(test)]
645mod test {
646 use super::*;
647 use datafusion_physical_expr::RangePartitioning;
648 use datafusion_physical_expr::expressions::Column;
649 use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
650
651 #[test]
653 fn repartition_empty_file_only() {
654 let partitioned_file_empty = pfile("empty", 0);
655 let file_group = vec![FileGroup::new(vec![partitioned_file_empty])];
656
657 let partitioned_files = FileGroupPartitioner::new()
658 .with_target_partitions(4)
659 .with_repartition_file_min_size(0)
660 .repartition_file_groups(&file_group);
661
662 assert_partitioned_files(None, partitioned_files);
663 }
664
665 #[test]
667 fn repartition_empty_files() {
668 let pfile_a = pfile("a", 10);
669 let pfile_b = pfile("b", 10);
670 let pfile_empty = pfile("empty", 0);
671
672 let empty_first = vec![
673 FileGroup::new(vec![pfile_empty.clone()]),
674 FileGroup::new(vec![pfile_a.clone()]),
675 FileGroup::new(vec![pfile_b.clone()]),
676 ];
677 let empty_middle = vec![
678 FileGroup::new(vec![pfile_a.clone()]),
679 FileGroup::new(vec![pfile_empty.clone()]),
680 FileGroup::new(vec![pfile_b.clone()]),
681 ];
682 let empty_last = vec![
683 FileGroup::new(vec![pfile_a]),
684 FileGroup::new(vec![pfile_b]),
685 FileGroup::new(vec![pfile_empty]),
686 ];
687
688 let expected_2 = vec![
690 FileGroup::new(vec![pfile("a", 10).with_range(0, 10)]),
691 FileGroup::new(vec![pfile("b", 10).with_range(0, 10)]),
692 ];
693 let expected_3 = vec![
694 FileGroup::new(vec![pfile("a", 10).with_range(0, 7)]),
695 FileGroup::new(vec![
696 pfile("a", 10).with_range(7, 10),
697 pfile("b", 10).with_range(0, 4),
698 ]),
699 FileGroup::new(vec![pfile("b", 10).with_range(4, 10)]),
700 ];
701
702 let file_groups_tests = [empty_first, empty_middle, empty_last];
703
704 for fg in file_groups_tests {
705 let all_expected = [(2, expected_2.clone()), (3, expected_3.clone())];
706 for (n_partition, expected) in all_expected {
707 let actual = FileGroupPartitioner::new()
708 .with_target_partitions(n_partition)
709 .with_repartition_file_min_size(10)
710 .repartition_file_groups(&fg);
711
712 assert_partitioned_files(Some(expected), actual);
713 }
714 }
715 }
716
717 #[test]
718 fn repartition_single_file() {
719 let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
721
722 let actual = FileGroupPartitioner::new()
723 .with_target_partitions(4)
724 .with_repartition_file_min_size(10)
725 .repartition_file_groups(&single_partition);
726
727 let expected = Some(vec![
728 FileGroup::new(vec![pfile("a", 123).with_range(0, 31)]),
729 FileGroup::new(vec![pfile("a", 123).with_range(31, 62)]),
730 FileGroup::new(vec![pfile("a", 123).with_range(62, 93)]),
731 FileGroup::new(vec![pfile("a", 123).with_range(93, 123)]),
732 ]);
733 assert_partitioned_files(expected, actual);
734 }
735
736 #[test]
737 fn repartition_single_file_with_range() {
738 let single_partition =
740 vec![FileGroup::new(vec![pfile("a", 123).with_range(0, 123)])];
741
742 let actual = FileGroupPartitioner::new()
743 .with_target_partitions(4)
744 .with_repartition_file_min_size(10)
745 .repartition_file_groups(&single_partition);
746
747 let expected = Some(vec![
748 FileGroup::new(vec![pfile("a", 123).with_range(0, 31)]),
749 FileGroup::new(vec![pfile("a", 123).with_range(31, 62)]),
750 FileGroup::new(vec![pfile("a", 123).with_range(62, 93)]),
751 FileGroup::new(vec![pfile("a", 123).with_range(93, 123)]),
752 ]);
753 assert_partitioned_files(expected, actual);
754 }
755
756 #[test]
757 fn repartition_single_file_with_incomplete_range() {
758 let single_partition =
760 vec![FileGroup::new(vec![pfile("a", 123).with_range(10, 100)])];
761
762 let actual = FileGroupPartitioner::new()
763 .with_target_partitions(4)
764 .with_repartition_file_min_size(10)
765 .repartition_file_groups(&single_partition);
766
767 let expected = Some(vec![
768 FileGroup::new(vec![pfile("a", 123).with_range(10, 33)]),
769 FileGroup::new(vec![pfile("a", 123).with_range(33, 56)]),
770 FileGroup::new(vec![pfile("a", 123).with_range(56, 79)]),
771 FileGroup::new(vec![pfile("a", 123).with_range(79, 100)]),
772 ]);
773 assert_partitioned_files(expected, actual);
774 }
775
776 #[test]
777 fn repartition_single_file_duplicated_with_range() {
778 let single_partition = vec![FileGroup::new(vec![
780 pfile("a", 100).with_range(0, 50),
781 pfile("a", 100).with_range(50, 100),
782 ])];
783
784 let actual = FileGroupPartitioner::new()
785 .with_target_partitions(4)
786 .with_repartition_file_min_size(10)
787 .repartition_file_groups(&single_partition);
788
789 let expected = Some(vec![
790 FileGroup::new(vec![pfile("a", 100).with_range(0, 25)]),
791 FileGroup::new(vec![pfile("a", 100).with_range(25, 50)]),
792 FileGroup::new(vec![pfile("a", 100).with_range(50, 75)]),
793 FileGroup::new(vec![pfile("a", 100).with_range(75, 100)]),
794 ]);
795 assert_partitioned_files(expected, actual);
796 }
797
798 #[test]
799 fn repartition_too_much_partitions() {
800 let partitioned_file = pfile("a", 8);
802 let single_partition = vec![FileGroup::new(vec![partitioned_file])];
803
804 let actual = FileGroupPartitioner::new()
805 .with_target_partitions(96)
806 .with_repartition_file_min_size(5)
807 .repartition_file_groups(&single_partition);
808
809 let expected = Some(vec![
810 FileGroup::new(vec![pfile("a", 8).with_range(0, 1)]),
811 FileGroup::new(vec![pfile("a", 8).with_range(1, 2)]),
812 FileGroup::new(vec![pfile("a", 8).with_range(2, 3)]),
813 FileGroup::new(vec![pfile("a", 8).with_range(3, 4)]),
814 FileGroup::new(vec![pfile("a", 8).with_range(4, 5)]),
815 FileGroup::new(vec![pfile("a", 8).with_range(5, 6)]),
816 FileGroup::new(vec![pfile("a", 8).with_range(6, 7)]),
817 FileGroup::new(vec![pfile("a", 8).with_range(7, 8)]),
818 ]);
819
820 assert_partitioned_files(expected, actual);
821 }
822
823 #[test]
824 fn repartition_multiple_partitions() {
825 let source_partitions = vec![
827 FileGroup::new(vec![pfile("a", 40)]),
828 FileGroup::new(vec![pfile("b", 60)]),
829 ];
830
831 let actual = FileGroupPartitioner::new()
832 .with_target_partitions(3)
833 .with_repartition_file_min_size(10)
834 .repartition_file_groups(&source_partitions);
835
836 let expected = Some(vec![
837 FileGroup::new(vec![pfile("a", 40).with_range(0, 34)]),
838 FileGroup::new(vec![
839 pfile("a", 40).with_range(34, 40),
840 pfile("b", 60).with_range(0, 28),
841 ]),
842 FileGroup::new(vec![pfile("b", 60).with_range(28, 60)]),
843 ]);
844 assert_partitioned_files(expected, actual);
845 }
846
847 #[test]
848 fn repartition_same_num_partitions() {
849 let source_partitions = vec![
851 FileGroup::new(vec![pfile("a", 40)]),
852 FileGroup::new(vec![pfile("b", 60)]),
853 ];
854
855 let actual = FileGroupPartitioner::new()
856 .with_target_partitions(2)
857 .with_repartition_file_min_size(10)
858 .repartition_file_groups(&source_partitions);
859
860 let expected = Some(vec![
861 FileGroup::new(vec![
862 pfile("a", 40).with_range(0, 40),
863 pfile("b", 60).with_range(0, 10),
864 ]),
865 FileGroup::new(vec![pfile("b", 60).with_range(10, 60)]),
866 ]);
867 assert_partitioned_files(expected, actual);
868 }
869
870 #[test]
871 fn repartition_no_action_min_size() {
872 let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
874
875 let actual = FileGroupPartitioner::new()
876 .with_target_partitions(65)
877 .with_repartition_file_min_size(500)
878 .repartition_file_groups(&single_partition);
879
880 assert_partitioned_files(None, actual)
881 }
882
883 #[test]
884 fn repartition_no_action_zero_files() {
885 let empty_partition = vec![];
887
888 let partitioner = FileGroupPartitioner::new()
889 .with_target_partitions(65)
890 .with_repartition_file_min_size(500);
891
892 assert_partitioned_files(None, repartition_test(partitioner, empty_partition))
893 }
894
895 #[test]
896 fn repartition_ordered_no_action_too_few_partitions() {
897 let input_partitions = vec![
899 FileGroup::new(vec![pfile("a", 100)]),
900 FileGroup::new(vec![pfile("b", 200)]),
901 ];
902
903 let actual = FileGroupPartitioner::new()
904 .with_preserve_order_within_groups(true)
905 .with_target_partitions(2)
906 .with_repartition_file_min_size(10)
907 .repartition_file_groups(&input_partitions);
908
909 assert_partitioned_files(None, actual)
910 }
911
912 #[test]
913 fn repartition_ordered_no_action_file_too_small() {
914 let single_partition = vec![FileGroup::new(vec![pfile("a", 100)])];
916
917 let actual = FileGroupPartitioner::new()
918 .with_preserve_order_within_groups(true)
919 .with_target_partitions(2)
920 .with_repartition_file_min_size(1000)
922 .repartition_file_groups(&single_partition);
923
924 assert_partitioned_files(None, actual)
925 }
926
927 #[test]
928 fn repartition_ordered_one_large_file() {
929 let source_partitions = vec![FileGroup::new(vec![pfile("a", 100)])];
931
932 let actual = FileGroupPartitioner::new()
933 .with_preserve_order_within_groups(true)
934 .with_target_partitions(3)
935 .with_repartition_file_min_size(10)
936 .repartition_file_groups(&source_partitions);
937
938 let expected = Some(vec![
939 FileGroup::new(vec![pfile("a", 100).with_range(0, 34)]),
940 FileGroup::new(vec![pfile("a", 100).with_range(34, 68)]),
941 FileGroup::new(vec![pfile("a", 100).with_range(68, 100)]),
942 ]);
943 assert_partitioned_files(expected, actual);
944 }
945
946 #[test]
947 fn repartition_ordered_one_large_file_with_range() {
948 let source_partitions =
950 vec![FileGroup::new(vec![pfile("a", 100).with_range(0, 100)])];
951
952 let actual = FileGroupPartitioner::new()
953 .with_preserve_order_within_groups(true)
954 .with_target_partitions(3)
955 .with_repartition_file_min_size(10)
956 .repartition_file_groups(&source_partitions);
957
958 let expected = Some(vec![
959 FileGroup::new(vec![pfile("a", 100).with_range(0, 34)]),
960 FileGroup::new(vec![pfile("a", 100).with_range(34, 68)]),
961 FileGroup::new(vec![pfile("a", 100).with_range(68, 100)]),
962 ]);
963 assert_partitioned_files(expected, actual);
964 }
965
966 #[test]
967 fn repartition_ordered_one_large_one_small_file() {
968 let source_partitions = vec![
971 FileGroup::new(vec![pfile("a", 100)]),
972 FileGroup::new(vec![pfile("b", 30)]),
973 ];
974
975 let actual = FileGroupPartitioner::new()
976 .with_preserve_order_within_groups(true)
977 .with_target_partitions(4)
978 .with_repartition_file_min_size(10)
979 .repartition_file_groups(&source_partitions);
980
981 let expected = Some(vec![
982 FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
984 FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
986 FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
988 FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
990 ]);
991 assert_partitioned_files(expected, actual);
992 }
993
994 #[test]
995 fn repartition_ordered_one_large_one_small_file_with_full_range() {
996 let source_partitions = vec![
999 FileGroup::new(vec![pfile("a", 100).with_range(0, 100)]),
1000 FileGroup::new(vec![pfile("b", 30)]),
1001 ];
1002
1003 let actual = FileGroupPartitioner::new()
1004 .with_preserve_order_within_groups(true)
1005 .with_target_partitions(4)
1006 .with_repartition_file_min_size(10)
1007 .repartition_file_groups(&source_partitions);
1008
1009 let expected = Some(vec![
1010 FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1012 FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1014 FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1016 FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
1018 ]);
1019 assert_partitioned_files(expected, actual);
1020 }
1021
1022 #[test]
1023 fn repartition_ordered_one_large_one_small_file_with_split_range() {
1024 let source_partitions = vec![
1027 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1028 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1029 FileGroup::new(vec![pfile("b", 30)]),
1030 ];
1031
1032 let actual = FileGroupPartitioner::new()
1033 .with_preserve_order_within_groups(true)
1034 .with_target_partitions(4)
1035 .with_repartition_file_min_size(10)
1036 .repartition_file_groups(&source_partitions);
1037
1038 let expected = Some(vec![
1039 FileGroup::new(vec![pfile("a", 100).with_range(0, 25)]),
1041 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1043 FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1045 FileGroup::new(vec![pfile("a", 100).with_range(25, 50)]),
1047 ]);
1048 assert_partitioned_files(expected, actual);
1049 }
1050
1051 #[test]
1052 fn repartition_ordered_one_large_one_small_file_with_non_full_range() {
1053 let source_partitions = vec![
1056 FileGroup::new(vec![pfile("a", 100).with_range(20, 80)]),
1057 FileGroup::new(vec![pfile("b", 30).with_range(5, 25)]),
1058 ];
1059
1060 let actual = FileGroupPartitioner::new()
1061 .with_preserve_order_within_groups(true)
1062 .with_target_partitions(4)
1063 .with_repartition_file_min_size(10)
1064 .repartition_file_groups(&source_partitions);
1065
1066 let expected = Some(vec![
1067 FileGroup::new(vec![pfile("a", 100).with_range(20, 40)]),
1069 FileGroup::new(vec![pfile("b", 30).with_range(5, 25)]),
1071 FileGroup::new(vec![pfile("a", 100).with_range(40, 60)]),
1073 FileGroup::new(vec![pfile("a", 100).with_range(60, 80)]),
1075 ]);
1076 assert_partitioned_files(expected, actual);
1077 }
1078
1079 #[test]
1080 fn repartition_ordered_two_large_files() {
1081 let source_partitions = vec![
1083 FileGroup::new(vec![pfile("a", 100)]),
1084 FileGroup::new(vec![pfile("b", 100)]),
1085 ];
1086
1087 let actual = FileGroupPartitioner::new()
1088 .with_preserve_order_within_groups(true)
1089 .with_target_partitions(4)
1090 .with_repartition_file_min_size(10)
1091 .repartition_file_groups(&source_partitions);
1092
1093 let expected = Some(vec![
1094 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1096 FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1098 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1100 FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
1102 ]);
1103 assert_partitioned_files(expected, actual);
1104 }
1105
1106 #[test]
1107 fn repartition_ordered_two_large_one_small_files() {
1108 let source_partitions = vec![
1110 FileGroup::new(vec![pfile("a", 100)]),
1111 FileGroup::new(vec![pfile("b", 100)]),
1112 FileGroup::new(vec![pfile("c", 30)]),
1113 ];
1114
1115 let partitioner = FileGroupPartitioner::new()
1116 .with_preserve_order_within_groups(true)
1117 .with_repartition_file_min_size(10);
1118
1119 let actual = partitioner
1121 .with_target_partitions(4)
1122 .repartition_file_groups(&source_partitions);
1123
1124 let expected = Some(vec![
1125 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1127 FileGroup::new(vec![pfile("b", 100).with_range(0, 100)]),
1129 FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1131 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1133 ]);
1134 assert_partitioned_files(expected, actual);
1135
1136 let actual = partitioner
1138 .with_target_partitions(5)
1139 .repartition_file_groups(&source_partitions);
1140
1141 let expected = Some(vec![
1142 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1144 FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1146 FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1148 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1150 FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
1152 ]);
1153 assert_partitioned_files(expected, actual);
1154 }
1155
1156 #[test]
1157 fn repartition_ordered_one_large_one_small_existing_empty() {
1158 let source_partitions = vec![
1160 FileGroup::new(vec![pfile("a", 100)]),
1161 FileGroup::default(),
1162 FileGroup::new(vec![pfile("b", 40)]),
1163 FileGroup::default(),
1164 ];
1165
1166 let actual = FileGroupPartitioner::new()
1167 .with_preserve_order_within_groups(true)
1168 .with_target_partitions(5)
1169 .with_repartition_file_min_size(10)
1170 .repartition_file_groups(&source_partitions);
1171
1172 let expected = Some(vec![
1175 FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1177 FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1178 FileGroup::new(vec![pfile("b", 40).with_range(0, 20)]),
1180 FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
1182 FileGroup::new(vec![pfile("b", 40).with_range(20, 40)]),
1184 ]);
1185 assert_partitioned_files(expected, actual);
1186 }
1187 #[test]
1188 fn repartition_ordered_existing_group_multiple_files() {
1189 let source_partitions = vec![
1191 FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
1193 FileGroup::new(vec![pfile("c", 40)]),
1194 ];
1195
1196 let actual = FileGroupPartitioner::new()
1197 .with_preserve_order_within_groups(true)
1198 .with_target_partitions(3)
1199 .with_repartition_file_min_size(10)
1200 .repartition_file_groups(&source_partitions);
1201
1202 let expected = Some(vec![
1205 FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
1209 FileGroup::new(vec![pfile("c", 40).with_range(0, 20)]),
1211 FileGroup::new(vec![pfile("c", 40).with_range(20, 40)]),
1213 ]);
1214 assert_partitioned_files(expected, actual);
1215 }
1216
1217 fn assert_partitioned_files(
1220 expected: Option<Vec<FileGroup>>,
1221 actual: Option<Vec<FileGroup>>,
1222 ) {
1223 match (expected, actual) {
1224 (None, None) => {}
1225 (Some(_), None) => panic!("Expected Some, got None"),
1226 (None, Some(_)) => panic!("Expected None, got Some"),
1227 (Some(expected), Some(actual)) => {
1228 let expected_string = format!("{expected:#?}");
1229 let actual_string = format!("{actual:#?}");
1230 assert_eq!(expected_string, actual_string);
1231 }
1232 }
1233 }
1234
1235 fn pfile(path: impl Into<String>, file_size: u64) -> PartitionedFile {
1237 PartitionedFile::new(path, file_size)
1238 }
1239
1240 fn pfile_with_pv(path: &str, pv: &str) -> PartitionedFile {
1242 let mut file = pfile(path, 10);
1243 file.partition_values = vec![ScalarValue::from(pv)];
1244 file
1245 }
1246
1247 fn repartition_test(
1250 partitioner: FileGroupPartitioner,
1251 file_groups: Vec<FileGroup>,
1252 ) -> Option<Vec<FileGroup>> {
1253 let repartitioned = partitioner.repartition_file_groups(&file_groups);
1254
1255 let repartitioned_preserving_sort = partitioner
1256 .with_preserve_order_within_groups(true)
1257 .repartition_file_groups(&file_groups);
1258
1259 assert_partitioned_files(repartitioned.clone(), repartitioned_preserving_sort);
1260 repartitioned
1261 }
1262
1263 #[test]
1264 fn test_group_by_partition_values_edge_cases() {
1265 assert!(FileGroup::default().group_by_partition_values(4).is_empty());
1267 assert!(
1268 FileGroup::new(vec![pfile("a", 100)])
1269 .group_by_partition_values(0)
1270 .is_empty()
1271 );
1272 }
1273
1274 #[test]
1275 fn test_group_by_partition_values_less_groups_than_target() {
1276 let fg = FileGroup::new(vec![
1281 pfile_with_pv("a", "p1"),
1282 pfile_with_pv("b", "p1"),
1283 pfile_with_pv("c", "p2"),
1284 ]);
1285 let groups = fg.group_by_partition_values(4);
1286 assert_eq!(groups.len(), 2);
1287 assert_eq!(groups[0].len(), 2);
1288 assert_eq!(groups[1].len(), 1);
1289 }
1290
1291 #[test]
1292 fn test_group_by_partition_values_more_groups_than_target() {
1293 let fg = FileGroup::new(vec![
1296 pfile_with_pv("a", "p1"),
1297 pfile_with_pv("b", "p2"),
1298 pfile_with_pv("c", "p3"),
1299 pfile_with_pv("d", "p4"),
1300 pfile_with_pv("e", "p5"),
1301 ]);
1302 let groups = fg.group_by_partition_values(3);
1303 assert_eq!(groups.len(), 3);
1304 assert_eq!(groups[0].len(), 1);
1305 assert_eq!(groups[1].len(), 2);
1306 assert_eq!(groups[2].len(), 2);
1307 assert_eq!(group_pvs(&groups[0]), vec!["p1"]);
1309 assert_eq!(group_pvs(&groups[1]), vec!["p2", "p3"]);
1310 assert_eq!(group_pvs(&groups[2]), vec!["p4", "p5"]);
1311 }
1312
1313 fn group_pvs(group: &FileGroup) -> Vec<String> {
1314 group
1315 .iter()
1316 .map(|f| f.partition_values[0].to_string())
1317 .collect()
1318 }
1319
1320 fn range_route(key: &[ScalarValue], split_points: &[SplitPoint]) -> usize {
1323 let sort_options = vec![SortOptions::default(); key.len()];
1324 split_points
1325 .iter()
1326 .take_while(|sp| {
1327 compare_rows(sp.values(), key, &sort_options).unwrap()
1328 != Ordering::Greater
1329 })
1330 .count()
1331 }
1332
1333 #[test]
1334 fn test_group_by_partition_values_split_points_describe_groups() {
1335 let fg = FileGroup::new(vec![
1336 pfile_with_pv("a", "p1"),
1337 pfile_with_pv("b", "p2"),
1338 pfile_with_pv("c", "p3"),
1339 pfile_with_pv("d", "p4"),
1340 pfile_with_pv("e", "p5"),
1341 pfile_with_pv("f", "p5"),
1342 ]);
1343 let (groups, split_points) = fg.group_by_partition_values_with_split_points(3);
1344 assert_eq!(groups.len(), 3);
1345 assert_eq!(split_points.len(), 2);
1346 assert_eq!(split_points[0].values(), &[ScalarValue::from("p2")]);
1347 assert_eq!(split_points[1].values(), &[ScalarValue::from("p4")]);
1348
1349 for (idx, group) in groups.iter().enumerate() {
1351 for file in group.iter() {
1352 assert_eq!(range_route(&file.partition_values, &split_points), idx);
1353 }
1354 }
1355 }
1356
1357 #[test]
1358 fn test_group_by_partition_values_split_points_fewer_values_than_target() {
1359 let fg = FileGroup::new(vec![
1360 pfile_with_pv("a", "p1"),
1361 pfile_with_pv("b", "p1"),
1362 pfile_with_pv("c", "p2"),
1363 ]);
1364 let (groups, split_points) = fg.group_by_partition_values_with_split_points(4);
1365 assert_eq!(groups.len(), 2);
1366 assert_eq!(split_points.len(), 1);
1367 assert_eq!(split_points[0].values(), &[ScalarValue::from("p2")]);
1368 for (idx, group) in groups.iter().enumerate() {
1369 for file in group.iter() {
1370 assert_eq!(range_route(&file.partition_values, &split_points), idx);
1371 }
1372 }
1373 }
1374
1375 #[test]
1376 fn test_group_by_partition_values_split_points_single_target_partition() {
1377 let fg = FileGroup::new(vec![
1379 pfile_with_pv("a", "p1"),
1380 pfile_with_pv("b", "p2"),
1381 pfile_with_pv("c", "p3"),
1382 pfile_with_pv("d", "p3"),
1383 ]);
1384 let (groups, split_points) = fg.group_by_partition_values_with_split_points(1);
1385 assert_eq!(groups.len(), 1);
1386 assert_eq!(groups[0].len(), 4);
1387 assert!(split_points.is_empty());
1388 }
1389
1390 fn pfile_with_pvs(path: &str, pvs: &[Option<&str>]) -> PartitionedFile {
1391 let mut file = pfile(path, 10);
1392 file.partition_values = pvs
1393 .iter()
1394 .map(|v| ScalarValue::Utf8(v.map(str::to_string)))
1395 .collect();
1396 file
1397 }
1398
1399 fn compound_key_file_group() -> FileGroup {
1401 FileGroup::new(vec![
1402 pfile_with_pvs("a", &[Some("2026"), Some("09")]),
1403 pfile_with_pvs("b", &[Some("2026"), Some("10")]),
1404 pfile_with_pvs("c", &[None, Some("09")]),
1405 pfile_with_pvs("d", &[Some("2025"), None]),
1406 pfile_with_pvs("e", &[Some("2025"), Some("12")]),
1407 ])
1408 }
1409
1410 #[test]
1411 fn test_group_by_partition_values_split_points_null_and_compound_keys() {
1412 let fg = compound_key_file_group();
1413 let (groups, split_points) = fg.group_by_partition_values_with_split_points(2);
1414 assert_eq!(groups.len(), 2);
1415 assert_eq!(split_points.len(), 1);
1416 assert_eq!(
1417 split_points[0].values(),
1418 &[ScalarValue::from("2025"), ScalarValue::from("12")]
1419 );
1420 for (idx, group) in groups.iter().enumerate() {
1421 for file in group.iter() {
1422 assert_eq!(range_route(&file.partition_values, &split_points), idx);
1423 }
1424 }
1425 }
1426
1427 #[test]
1428 fn test_group_by_partition_values_split_point_containing_null() {
1429 let fg = compound_key_file_group();
1430 let (groups, split_points) = fg.group_by_partition_values_with_split_points(3);
1431 assert_eq!(groups.len(), 3);
1432 assert_eq!(
1433 split_points[0].values(),
1434 &[ScalarValue::from("2025"), ScalarValue::Utf8(None)]
1435 );
1436 assert_eq!(
1437 split_points[1].values(),
1438 &[ScalarValue::from("2026"), ScalarValue::from("09")]
1439 );
1440 for (idx, group) in groups.iter().enumerate() {
1441 for file in group.iter() {
1442 assert_eq!(range_route(&file.partition_values, &split_points), idx);
1443 }
1444 }
1445 let ordering = LexOrdering::new(vec![
1446 PhysicalSortExpr::new_default(Arc::new(Column::new("year", 0))),
1447 PhysicalSortExpr::new_default(Arc::new(Column::new("month", 1))),
1448 ])
1449 .unwrap();
1450 let range = RangePartitioning::try_new(ordering, split_points).unwrap();
1451 assert_eq!(range.partition_count(), 3);
1452 }
1453}