1use crate::{FileRange, PartitionedFile};
21use arrow::compute::SortOptions;
22use datafusion_common::Statistics;
23use datafusion_common::utils::compare_rows;
24use itertools::Itertools;
25use std::cmp::{Ordering, min};
26use std::collections::{BinaryHeap, HashMap};
27use std::iter::repeat_with;
28use std::mem;
29use std::ops::{Deref, DerefMut, Index, IndexMut};
30use std::sync::Arc;
31
32#[derive(Debug, Clone, Copy)]
131pub struct FileGroupPartitioner {
132 target_partitions: usize,
134 repartition_file_min_size: usize,
136 preserve_order_within_groups: bool,
138}
139
140impl Default for FileGroupPartitioner {
141 fn default() -> Self {
142 Self::new()
143 }
144}
145
146impl FileGroupPartitioner {
147 pub fn new() -> Self {
152 Self {
153 target_partitions: 1,
154 repartition_file_min_size: 10 * 1024 * 1024,
155 preserve_order_within_groups: false,
156 }
157 }
158
159 pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
161 self.target_partitions = target_partitions;
162 self
163 }
164
165 pub fn with_repartition_file_min_size(
167 mut self,
168 repartition_file_min_size: usize,
169 ) -> Self {
170 self.repartition_file_min_size = repartition_file_min_size;
171 self
172 }
173
174 pub fn with_preserve_order_within_groups(
176 mut self,
177 preserve_order_within_groups: bool,
178 ) -> Self {
179 self.preserve_order_within_groups = preserve_order_within_groups;
180 self
181 }
182
183 pub fn repartition_file_groups(
187 &self,
188 file_groups: &[FileGroup],
189 ) -> Option<Vec<FileGroup>> {
190 if file_groups.is_empty() {
191 return None;
192 }
193
194 if self.preserve_order_within_groups {
196 self.repartition_preserving_order(file_groups)
197 } else {
198 self.repartition_evenly_by_size(file_groups)
199 }
200 }
201
202 fn repartition_evenly_by_size(
205 &self,
206 file_groups: &[FileGroup],
207 ) -> Option<Vec<FileGroup>> {
208 let target_partitions = self.target_partitions;
209 let repartition_file_min_size = self.repartition_file_min_size;
210 let flattened_files = file_groups.iter().flat_map(FileGroup::iter).collect_vec();
211
212 let total_size = flattened_files
213 .iter()
214 .map(|f| f.effective_size())
215 .sum::<u64>();
216 if total_size < (repartition_file_min_size as u64) || total_size == 0 {
217 return None;
218 }
219
220 let target_partition_size = total_size.div_ceil(target_partitions as u64);
221
222 let current_partition_index: usize = 0;
223 let current_partition_size: u64 = 0;
224
225 let repartitioned_files = flattened_files
227 .into_iter()
228 .scan(
229 (current_partition_index, current_partition_size),
230 |(current_partition_index, current_partition_size), source_file| {
231 let mut produced_files = vec![];
232 let (mut range_start, file_end) = source_file.range();
233 while range_start < file_end {
234 let range_end = min(
235 range_start
236 + (target_partition_size - *current_partition_size),
237 file_end,
238 );
239
240 let mut produced_file = source_file.clone();
241 produced_file.range = Some(FileRange {
242 start: range_start as i64,
243 end: range_end as i64,
244 });
245 produced_files.push((*current_partition_index, produced_file));
246
247 if *current_partition_size + (range_end - range_start)
248 >= target_partition_size
249 {
250 *current_partition_index += 1;
251 *current_partition_size = 0;
252 } else {
253 *current_partition_size += range_end - range_start;
254 }
255 range_start = range_end;
256 }
257 Some(produced_files)
258 },
259 )
260 .flatten()
261 .chunk_by(|(partition_idx, _)| *partition_idx)
262 .into_iter()
263 .map(|(_, group)| FileGroup::new(group.map(|(_, vals)| vals).collect_vec()))
264 .collect_vec();
265
266 Some(repartitioned_files)
267 }
268
269 fn repartition_preserving_order(
271 &self,
272 file_groups: &[FileGroup],
273 ) -> Option<Vec<FileGroup>> {
274 if file_groups.len() >= self.target_partitions {
277 return None;
278 }
279 let num_new_groups = self.target_partitions - file_groups.len();
280
281 if file_groups.len() == 1 && file_groups[0].len() == 1 {
283 return self.repartition_evenly_by_size(file_groups);
284 }
285
286 let mut heap: BinaryHeap<_> = file_groups
288 .iter()
289 .enumerate()
290 .filter_map(|(group_index, group)| {
291 if group.len() == 1 {
293 Some(ToRepartition {
294 source_index: group_index,
295 file_size: group[0].effective_size(),
296 new_groups: vec![group_index],
297 })
298 } else {
299 None
300 }
301 })
302 .map(CompareByRangeSize)
303 .collect();
304
305 if heap.is_empty() {
307 return None;
308 }
309
310 let mut file_groups: Vec<_> = file_groups
313 .iter()
314 .cloned()
315 .chain(repeat_with(|| FileGroup::new(Vec::new())).take(num_new_groups))
316 .collect();
317
318 for (group_index, group) in file_groups.iter().enumerate() {
320 if !group.is_empty() {
321 continue;
322 }
323 let mut largest_group = heap.pop().unwrap();
325 largest_group.new_groups.push(group_index);
326 heap.push(largest_group);
327 }
328
329 while let Some(to_repartition) = heap.pop() {
331 let range_size = to_repartition.range_size();
332 let ToRepartition {
333 source_index,
334 file_size: _,
335 new_groups,
336 } = to_repartition.into_inner();
337 assert_eq!(file_groups[source_index].len(), 1);
338 let original_file = file_groups[source_index].pop().unwrap();
339
340 let last_group = new_groups.len() - 1;
341 let (mut range_start, file_end) = original_file.range();
342 let mut range_end = range_start + range_size;
343 for (i, group_index) in new_groups.into_iter().enumerate() {
344 let target_group = &mut file_groups[group_index];
345 assert!(target_group.is_empty());
346
347 if i == last_group {
349 range_end = file_end;
350 }
351 target_group.push(
352 original_file
353 .clone()
354 .with_range(range_start as i64, range_end as i64),
355 );
356 range_start = range_end;
357 range_end += range_size;
358 }
359 }
360
361 Some(file_groups)
362 }
363}
364
365#[derive(Debug, Clone)]
382pub struct FileGroup {
383 files: Vec<PartitionedFile>,
385 statistics: Option<Arc<Statistics>>,
391}
392
393impl FileGroup {
394 pub fn new(files: Vec<PartitionedFile>) -> Self {
396 Self {
397 files,
398 statistics: None,
399 }
400 }
401
402 pub fn len(&self) -> usize {
404 self.files.len()
405 }
406
407 pub fn with_statistics(mut self, statistics: Arc<Statistics>) -> Self {
409 self.statistics = Some(statistics);
410 self
411 }
412
413 pub fn files(&self) -> &[PartitionedFile] {
415 &self.files
416 }
417
418 pub fn iter(&self) -> impl Iterator<Item = &PartitionedFile> {
419 self.files.iter()
420 }
421
422 pub fn into_inner(self) -> Vec<PartitionedFile> {
423 self.files
424 }
425
426 pub fn is_empty(&self) -> bool {
427 self.files.is_empty()
428 }
429
430 pub fn pop(&mut self) -> Option<PartitionedFile> {
432 self.files.pop()
433 }
434
435 pub fn push(&mut self, partitioned_file: PartitionedFile) {
437 self.files.push(partitioned_file);
438 }
439
440 pub fn file_statistics(&self, index: Option<usize>) -> Option<&Statistics> {
443 if let Some(index) = index {
444 self.files.get(index).and_then(|f| f.statistics.as_deref())
445 } else {
446 self.statistics.as_deref()
447 }
448 }
449
450 pub fn statistics_mut(&mut self) -> Option<&mut Statistics> {
452 self.statistics.as_mut().map(Arc::make_mut)
453 }
454
455 pub fn split_files(mut self, n: usize) -> Vec<FileGroup> {
457 if self.is_empty() {
458 return vec![];
459 }
460
461 self.files.sort_by(|a, b| a.path().cmp(b.path()));
465
466 let chunk_size = self.len().div_ceil(n);
468 let mut chunks = Vec::with_capacity(n);
469 let mut current_chunk = Vec::with_capacity(chunk_size);
470 for file in self.files.drain(..) {
471 current_chunk.push(file);
472 if current_chunk.len() == chunk_size {
473 let full_chunk = FileGroup::new(mem::replace(
474 &mut current_chunk,
475 Vec::with_capacity(chunk_size),
476 ));
477 chunks.push(full_chunk);
478 }
479 }
480
481 if !current_chunk.is_empty() {
482 chunks.push(FileGroup::new(current_chunk))
483 }
484
485 chunks
486 }
487
488 #[allow(clippy::allow_attributes, clippy::mutable_key_type)] pub fn group_by_partition_values(
495 self,
496 max_target_partitions: usize,
497 ) -> Vec<FileGroup> {
498 if self.is_empty() || max_target_partitions == 0 {
499 return vec![];
500 }
501
502 let mut partition_groups: HashMap<
503 Vec<datafusion_common::ScalarValue>,
504 Vec<PartitionedFile>,
505 > = HashMap::new();
506
507 for file in self.files {
508 partition_groups
509 .entry(file.partition_values.clone())
510 .or_default()
511 .push(file);
512 }
513
514 let num_unique_partitions = partition_groups.len();
515
516 let mut sorted_partitions: Vec<_> = partition_groups.into_iter().collect();
518 let sort_options =
519 vec![
520 SortOptions::default();
521 sorted_partitions.first().map(|(k, _)| k.len()).unwrap_or(0)
522 ];
523 sorted_partitions.sort_by(|a, b| {
524 compare_rows(&a.0, &b.0, &sort_options).unwrap_or(Ordering::Equal)
525 });
526
527 if num_unique_partitions <= max_target_partitions {
528 sorted_partitions
529 .into_iter()
530 .map(|(_, files)| FileGroup::new(files))
531 .collect()
532 } else {
533 let mut target_groups = vec![vec![]; max_target_partitions];
537
538 for (idx, (_, files)) in sorted_partitions.into_iter().enumerate() {
539 let bucket = idx % max_target_partitions;
540 target_groups[bucket].extend(files);
541 }
542
543 target_groups.into_iter().map(FileGroup::new).collect()
544 }
545 }
546}
547
548impl Index<usize> for FileGroup {
549 type Output = PartitionedFile;
550
551 fn index(&self, index: usize) -> &Self::Output {
552 &self.files[index]
553 }
554}
555
556impl IndexMut<usize> for FileGroup {
557 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
558 &mut self.files[index]
559 }
560}
561
562impl FromIterator<PartitionedFile> for FileGroup {
563 fn from_iter<I: IntoIterator<Item = PartitionedFile>>(iter: I) -> Self {
564 let files = iter.into_iter().collect();
565 FileGroup::new(files)
566 }
567}
568
569impl From<Vec<PartitionedFile>> for FileGroup {
570 fn from(files: Vec<PartitionedFile>) -> Self {
571 FileGroup::new(files)
572 }
573}
574
575impl Default for FileGroup {
576 fn default() -> Self {
577 Self::new(Vec::new())
578 }
579}
580
581#[derive(Debug, Clone)]
583struct ToRepartition {
584 source_index: usize,
586 file_size: u64,
588 new_groups: Vec<usize>,
590}
591
592impl ToRepartition {
593 fn range_size(&self) -> u64 {
595 self.file_size / (self.new_groups.len() as u64)
596 }
597}
598
599struct CompareByRangeSize(ToRepartition);
600impl CompareByRangeSize {
601 fn into_inner(self) -> ToRepartition {
602 self.0
603 }
604}
605impl Ord for CompareByRangeSize {
606 fn cmp(&self, other: &Self) -> Ordering {
607 self.0.range_size().cmp(&other.0.range_size())
608 }
609}
610impl PartialOrd for CompareByRangeSize {
611 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
612 Some(self.cmp(other))
613 }
614}
615impl PartialEq for CompareByRangeSize {
616 fn eq(&self, other: &Self) -> bool {
617 self.cmp(other) == Ordering::Equal
619 }
620}
621impl Eq for CompareByRangeSize {}
622impl Deref for CompareByRangeSize {
623 type Target = ToRepartition;
624 fn deref(&self) -> &Self::Target {
625 &self.0
626 }
627}
628impl DerefMut for CompareByRangeSize {
629 fn deref_mut(&mut self) -> &mut Self::Target {
630 &mut self.0
631 }
632}
633
634#[cfg(test)]
635mod test {
636 use super::*;
637 use datafusion_common::ScalarValue;
638
639 #[test]
641 fn repartition_empty_file_only() {
642 let partitioned_file_empty = pfile("empty", 0);
643 let file_group = vec![FileGroup::new(vec![partitioned_file_empty])];
644
645 let partitioned_files = FileGroupPartitioner::new()
646 .with_target_partitions(4)
647 .with_repartition_file_min_size(0)
648 .repartition_file_groups(&file_group);
649
650 assert_partitioned_files(None, partitioned_files);
651 }
652
653 #[test]
655 fn repartition_empty_files() {
656 let pfile_a = pfile("a", 10);
657 let pfile_b = pfile("b", 10);
658 let pfile_empty = pfile("empty", 0);
659
660 let empty_first = vec![
661 FileGroup::new(vec![pfile_empty.clone()]),
662 FileGroup::new(vec![pfile_a.clone()]),
663 FileGroup::new(vec![pfile_b.clone()]),
664 ];
665 let empty_middle = vec![
666 FileGroup::new(vec![pfile_a.clone()]),
667 FileGroup::new(vec![pfile_empty.clone()]),
668 FileGroup::new(vec![pfile_b.clone()]),
669 ];
670 let empty_last = vec![
671 FileGroup::new(vec![pfile_a]),
672 FileGroup::new(vec![pfile_b]),
673 FileGroup::new(vec![pfile_empty]),
674 ];
675
676 let expected_2 = vec![
678 FileGroup::new(vec![pfile("a", 10).with_range(0, 10)]),
679 FileGroup::new(vec![pfile("b", 10).with_range(0, 10)]),
680 ];
681 let expected_3 = vec![
682 FileGroup::new(vec![pfile("a", 10).with_range(0, 7)]),
683 FileGroup::new(vec![
684 pfile("a", 10).with_range(7, 10),
685 pfile("b", 10).with_range(0, 4),
686 ]),
687 FileGroup::new(vec![pfile("b", 10).with_range(4, 10)]),
688 ];
689
690 let file_groups_tests = [empty_first, empty_middle, empty_last];
691
692 for fg in file_groups_tests {
693 let all_expected = [(2, expected_2.clone()), (3, expected_3.clone())];
694 for (n_partition, expected) in all_expected {
695 let actual = FileGroupPartitioner::new()
696 .with_target_partitions(n_partition)
697 .with_repartition_file_min_size(10)
698 .repartition_file_groups(&fg);
699
700 assert_partitioned_files(Some(expected), actual);
701 }
702 }
703 }
704
705 #[test]
706 fn repartition_single_file() {
707 let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
709
710 let actual = FileGroupPartitioner::new()
711 .with_target_partitions(4)
712 .with_repartition_file_min_size(10)
713 .repartition_file_groups(&single_partition);
714
715 let expected = Some(vec![
716 FileGroup::new(vec![pfile("a", 123).with_range(0, 31)]),
717 FileGroup::new(vec![pfile("a", 123).with_range(31, 62)]),
718 FileGroup::new(vec![pfile("a", 123).with_range(62, 93)]),
719 FileGroup::new(vec![pfile("a", 123).with_range(93, 123)]),
720 ]);
721 assert_partitioned_files(expected, actual);
722 }
723
724 #[test]
725 fn repartition_single_file_with_range() {
726 let single_partition =
728 vec![FileGroup::new(vec![pfile("a", 123).with_range(0, 123)])];
729
730 let actual = FileGroupPartitioner::new()
731 .with_target_partitions(4)
732 .with_repartition_file_min_size(10)
733 .repartition_file_groups(&single_partition);
734
735 let expected = Some(vec![
736 FileGroup::new(vec![pfile("a", 123).with_range(0, 31)]),
737 FileGroup::new(vec![pfile("a", 123).with_range(31, 62)]),
738 FileGroup::new(vec![pfile("a", 123).with_range(62, 93)]),
739 FileGroup::new(vec![pfile("a", 123).with_range(93, 123)]),
740 ]);
741 assert_partitioned_files(expected, actual);
742 }
743
744 #[test]
745 fn repartition_single_file_with_incomplete_range() {
746 let single_partition =
748 vec![FileGroup::new(vec![pfile("a", 123).with_range(10, 100)])];
749
750 let actual = FileGroupPartitioner::new()
751 .with_target_partitions(4)
752 .with_repartition_file_min_size(10)
753 .repartition_file_groups(&single_partition);
754
755 let expected = Some(vec![
756 FileGroup::new(vec![pfile("a", 123).with_range(10, 33)]),
757 FileGroup::new(vec![pfile("a", 123).with_range(33, 56)]),
758 FileGroup::new(vec![pfile("a", 123).with_range(56, 79)]),
759 FileGroup::new(vec![pfile("a", 123).with_range(79, 100)]),
760 ]);
761 assert_partitioned_files(expected, actual);
762 }
763
764 #[test]
765 fn repartition_single_file_duplicated_with_range() {
766 let single_partition = vec![FileGroup::new(vec![
768 pfile("a", 100).with_range(0, 50),
769 pfile("a", 100).with_range(50, 100),
770 ])];
771
772 let actual = FileGroupPartitioner::new()
773 .with_target_partitions(4)
774 .with_repartition_file_min_size(10)
775 .repartition_file_groups(&single_partition);
776
777 let expected = Some(vec![
778 FileGroup::new(vec![pfile("a", 100).with_range(0, 25)]),
779 FileGroup::new(vec![pfile("a", 100).with_range(25, 50)]),
780 FileGroup::new(vec![pfile("a", 100).with_range(50, 75)]),
781 FileGroup::new(vec![pfile("a", 100).with_range(75, 100)]),
782 ]);
783 assert_partitioned_files(expected, actual);
784 }
785
786 #[test]
787 fn repartition_too_much_partitions() {
788 let partitioned_file = pfile("a", 8);
790 let single_partition = vec![FileGroup::new(vec![partitioned_file])];
791
792 let actual = FileGroupPartitioner::new()
793 .with_target_partitions(96)
794 .with_repartition_file_min_size(5)
795 .repartition_file_groups(&single_partition);
796
797 let expected = Some(vec![
798 FileGroup::new(vec![pfile("a", 8).with_range(0, 1)]),
799 FileGroup::new(vec![pfile("a", 8).with_range(1, 2)]),
800 FileGroup::new(vec![pfile("a", 8).with_range(2, 3)]),
801 FileGroup::new(vec![pfile("a", 8).with_range(3, 4)]),
802 FileGroup::new(vec![pfile("a", 8).with_range(4, 5)]),
803 FileGroup::new(vec![pfile("a", 8).with_range(5, 6)]),
804 FileGroup::new(vec![pfile("a", 8).with_range(6, 7)]),
805 FileGroup::new(vec![pfile("a", 8).with_range(7, 8)]),
806 ]);
807
808 assert_partitioned_files(expected, actual);
809 }
810
811 #[test]
812 fn repartition_multiple_partitions() {
813 let source_partitions = vec![
815 FileGroup::new(vec![pfile("a", 40)]),
816 FileGroup::new(vec![pfile("b", 60)]),
817 ];
818
819 let actual = FileGroupPartitioner::new()
820 .with_target_partitions(3)
821 .with_repartition_file_min_size(10)
822 .repartition_file_groups(&source_partitions);
823
824 let expected = Some(vec![
825 FileGroup::new(vec![pfile("a", 40).with_range(0, 34)]),
826 FileGroup::new(vec![
827 pfile("a", 40).with_range(34, 40),
828 pfile("b", 60).with_range(0, 28),
829 ]),
830 FileGroup::new(vec![pfile("b", 60).with_range(28, 60)]),
831 ]);
832 assert_partitioned_files(expected, actual);
833 }
834
835 #[test]
836 fn repartition_same_num_partitions() {
837 let source_partitions = vec![
839 FileGroup::new(vec![pfile("a", 40)]),
840 FileGroup::new(vec![pfile("b", 60)]),
841 ];
842
843 let actual = FileGroupPartitioner::new()
844 .with_target_partitions(2)
845 .with_repartition_file_min_size(10)
846 .repartition_file_groups(&source_partitions);
847
848 let expected = Some(vec![
849 FileGroup::new(vec![
850 pfile("a", 40).with_range(0, 40),
851 pfile("b", 60).with_range(0, 10),
852 ]),
853 FileGroup::new(vec![pfile("b", 60).with_range(10, 60)]),
854 ]);
855 assert_partitioned_files(expected, actual);
856 }
857
858 #[test]
859 fn repartition_no_action_min_size() {
860 let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
862
863 let actual = FileGroupPartitioner::new()
864 .with_target_partitions(65)
865 .with_repartition_file_min_size(500)
866 .repartition_file_groups(&single_partition);
867
868 assert_partitioned_files(None, actual)
869 }
870
871 #[test]
872 fn repartition_no_action_zero_files() {
873 let empty_partition = vec![];
875
876 let partitioner = FileGroupPartitioner::new()
877 .with_target_partitions(65)
878 .with_repartition_file_min_size(500);
879
880 assert_partitioned_files(None, repartition_test(partitioner, empty_partition))
881 }
882
883 #[test]
884 fn repartition_ordered_no_action_too_few_partitions() {
885 let input_partitions = vec![
887 FileGroup::new(vec![pfile("a", 100)]),
888 FileGroup::new(vec![pfile("b", 200)]),
889 ];
890
891 let actual = FileGroupPartitioner::new()
892 .with_preserve_order_within_groups(true)
893 .with_target_partitions(2)
894 .with_repartition_file_min_size(10)
895 .repartition_file_groups(&input_partitions);
896
897 assert_partitioned_files(None, actual)
898 }
899
900 #[test]
901 fn repartition_ordered_no_action_file_too_small() {
902 let single_partition = vec![FileGroup::new(vec![pfile("a", 100)])];
904
905 let actual = FileGroupPartitioner::new()
906 .with_preserve_order_within_groups(true)
907 .with_target_partitions(2)
908 .with_repartition_file_min_size(1000)
910 .repartition_file_groups(&single_partition);
911
912 assert_partitioned_files(None, actual)
913 }
914
915 #[test]
916 fn repartition_ordered_one_large_file() {
917 let source_partitions = vec![FileGroup::new(vec![pfile("a", 100)])];
919
920 let actual = FileGroupPartitioner::new()
921 .with_preserve_order_within_groups(true)
922 .with_target_partitions(3)
923 .with_repartition_file_min_size(10)
924 .repartition_file_groups(&source_partitions);
925
926 let expected = Some(vec![
927 FileGroup::new(vec![pfile("a", 100).with_range(0, 34)]),
928 FileGroup::new(vec![pfile("a", 100).with_range(34, 68)]),
929 FileGroup::new(vec![pfile("a", 100).with_range(68, 100)]),
930 ]);
931 assert_partitioned_files(expected, actual);
932 }
933
934 #[test]
935 fn repartition_ordered_one_large_file_with_range() {
936 let source_partitions =
938 vec![FileGroup::new(vec![pfile("a", 100).with_range(0, 100)])];
939
940 let actual = FileGroupPartitioner::new()
941 .with_preserve_order_within_groups(true)
942 .with_target_partitions(3)
943 .with_repartition_file_min_size(10)
944 .repartition_file_groups(&source_partitions);
945
946 let expected = Some(vec![
947 FileGroup::new(vec![pfile("a", 100).with_range(0, 34)]),
948 FileGroup::new(vec![pfile("a", 100).with_range(34, 68)]),
949 FileGroup::new(vec![pfile("a", 100).with_range(68, 100)]),
950 ]);
951 assert_partitioned_files(expected, actual);
952 }
953
954 #[test]
955 fn repartition_ordered_one_large_one_small_file() {
956 let source_partitions = vec![
959 FileGroup::new(vec![pfile("a", 100)]),
960 FileGroup::new(vec![pfile("b", 30)]),
961 ];
962
963 let actual = FileGroupPartitioner::new()
964 .with_preserve_order_within_groups(true)
965 .with_target_partitions(4)
966 .with_repartition_file_min_size(10)
967 .repartition_file_groups(&source_partitions);
968
969 let expected = Some(vec![
970 FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
972 FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
974 FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
976 FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
978 ]);
979 assert_partitioned_files(expected, actual);
980 }
981
982 #[test]
983 fn repartition_ordered_one_large_one_small_file_with_full_range() {
984 let source_partitions = vec![
987 FileGroup::new(vec![pfile("a", 100).with_range(0, 100)]),
988 FileGroup::new(vec![pfile("b", 30)]),
989 ];
990
991 let actual = FileGroupPartitioner::new()
992 .with_preserve_order_within_groups(true)
993 .with_target_partitions(4)
994 .with_repartition_file_min_size(10)
995 .repartition_file_groups(&source_partitions);
996
997 let expected = Some(vec![
998 FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1000 FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1002 FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1004 FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
1006 ]);
1007 assert_partitioned_files(expected, actual);
1008 }
1009
1010 #[test]
1011 fn repartition_ordered_one_large_one_small_file_with_split_range() {
1012 let source_partitions = vec![
1015 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1016 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1017 FileGroup::new(vec![pfile("b", 30)]),
1018 ];
1019
1020 let actual = FileGroupPartitioner::new()
1021 .with_preserve_order_within_groups(true)
1022 .with_target_partitions(4)
1023 .with_repartition_file_min_size(10)
1024 .repartition_file_groups(&source_partitions);
1025
1026 let expected = Some(vec![
1027 FileGroup::new(vec![pfile("a", 100).with_range(0, 25)]),
1029 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1031 FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1033 FileGroup::new(vec![pfile("a", 100).with_range(25, 50)]),
1035 ]);
1036 assert_partitioned_files(expected, actual);
1037 }
1038
1039 #[test]
1040 fn repartition_ordered_one_large_one_small_file_with_non_full_range() {
1041 let source_partitions = vec![
1044 FileGroup::new(vec![pfile("a", 100).with_range(20, 80)]),
1045 FileGroup::new(vec![pfile("b", 30).with_range(5, 25)]),
1046 ];
1047
1048 let actual = FileGroupPartitioner::new()
1049 .with_preserve_order_within_groups(true)
1050 .with_target_partitions(4)
1051 .with_repartition_file_min_size(10)
1052 .repartition_file_groups(&source_partitions);
1053
1054 let expected = Some(vec![
1055 FileGroup::new(vec![pfile("a", 100).with_range(20, 40)]),
1057 FileGroup::new(vec![pfile("b", 30).with_range(5, 25)]),
1059 FileGroup::new(vec![pfile("a", 100).with_range(40, 60)]),
1061 FileGroup::new(vec![pfile("a", 100).with_range(60, 80)]),
1063 ]);
1064 assert_partitioned_files(expected, actual);
1065 }
1066
1067 #[test]
1068 fn repartition_ordered_two_large_files() {
1069 let source_partitions = vec![
1071 FileGroup::new(vec![pfile("a", 100)]),
1072 FileGroup::new(vec![pfile("b", 100)]),
1073 ];
1074
1075 let actual = FileGroupPartitioner::new()
1076 .with_preserve_order_within_groups(true)
1077 .with_target_partitions(4)
1078 .with_repartition_file_min_size(10)
1079 .repartition_file_groups(&source_partitions);
1080
1081 let expected = Some(vec![
1082 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1084 FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1086 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1088 FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
1090 ]);
1091 assert_partitioned_files(expected, actual);
1092 }
1093
1094 #[test]
1095 fn repartition_ordered_two_large_one_small_files() {
1096 let source_partitions = vec![
1098 FileGroup::new(vec![pfile("a", 100)]),
1099 FileGroup::new(vec![pfile("b", 100)]),
1100 FileGroup::new(vec![pfile("c", 30)]),
1101 ];
1102
1103 let partitioner = FileGroupPartitioner::new()
1104 .with_preserve_order_within_groups(true)
1105 .with_repartition_file_min_size(10);
1106
1107 let actual = partitioner
1109 .with_target_partitions(4)
1110 .repartition_file_groups(&source_partitions);
1111
1112 let expected = Some(vec![
1113 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1115 FileGroup::new(vec![pfile("b", 100).with_range(0, 100)]),
1117 FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1119 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1121 ]);
1122 assert_partitioned_files(expected, actual);
1123
1124 let actual = partitioner
1126 .with_target_partitions(5)
1127 .repartition_file_groups(&source_partitions);
1128
1129 let expected = Some(vec![
1130 FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1132 FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1134 FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1136 FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1138 FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
1140 ]);
1141 assert_partitioned_files(expected, actual);
1142 }
1143
1144 #[test]
1145 fn repartition_ordered_one_large_one_small_existing_empty() {
1146 let source_partitions = vec![
1148 FileGroup::new(vec![pfile("a", 100)]),
1149 FileGroup::default(),
1150 FileGroup::new(vec![pfile("b", 40)]),
1151 FileGroup::default(),
1152 ];
1153
1154 let actual = FileGroupPartitioner::new()
1155 .with_preserve_order_within_groups(true)
1156 .with_target_partitions(5)
1157 .with_repartition_file_min_size(10)
1158 .repartition_file_groups(&source_partitions);
1159
1160 let expected = Some(vec![
1163 FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1165 FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1166 FileGroup::new(vec![pfile("b", 40).with_range(0, 20)]),
1168 FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
1170 FileGroup::new(vec![pfile("b", 40).with_range(20, 40)]),
1172 ]);
1173 assert_partitioned_files(expected, actual);
1174 }
1175 #[test]
1176 fn repartition_ordered_existing_group_multiple_files() {
1177 let source_partitions = vec![
1179 FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
1181 FileGroup::new(vec![pfile("c", 40)]),
1182 ];
1183
1184 let actual = FileGroupPartitioner::new()
1185 .with_preserve_order_within_groups(true)
1186 .with_target_partitions(3)
1187 .with_repartition_file_min_size(10)
1188 .repartition_file_groups(&source_partitions);
1189
1190 let expected = Some(vec![
1193 FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
1197 FileGroup::new(vec![pfile("c", 40).with_range(0, 20)]),
1199 FileGroup::new(vec![pfile("c", 40).with_range(20, 40)]),
1201 ]);
1202 assert_partitioned_files(expected, actual);
1203 }
1204
1205 fn assert_partitioned_files(
1208 expected: Option<Vec<FileGroup>>,
1209 actual: Option<Vec<FileGroup>>,
1210 ) {
1211 match (expected, actual) {
1212 (None, None) => {}
1213 (Some(_), None) => panic!("Expected Some, got None"),
1214 (None, Some(_)) => panic!("Expected None, got Some"),
1215 (Some(expected), Some(actual)) => {
1216 let expected_string = format!("{expected:#?}");
1217 let actual_string = format!("{actual:#?}");
1218 assert_eq!(expected_string, actual_string);
1219 }
1220 }
1221 }
1222
1223 fn pfile(path: impl Into<String>, file_size: u64) -> PartitionedFile {
1225 PartitionedFile::new(path, file_size)
1226 }
1227
1228 fn pfile_with_pv(path: &str, pv: &str) -> PartitionedFile {
1230 let mut file = pfile(path, 10);
1231 file.partition_values = vec![ScalarValue::from(pv)];
1232 file
1233 }
1234
1235 fn repartition_test(
1238 partitioner: FileGroupPartitioner,
1239 file_groups: Vec<FileGroup>,
1240 ) -> Option<Vec<FileGroup>> {
1241 let repartitioned = partitioner.repartition_file_groups(&file_groups);
1242
1243 let repartitioned_preserving_sort = partitioner
1244 .with_preserve_order_within_groups(true)
1245 .repartition_file_groups(&file_groups);
1246
1247 assert_partitioned_files(repartitioned.clone(), repartitioned_preserving_sort);
1248 repartitioned
1249 }
1250
1251 #[test]
1252 fn test_group_by_partition_values_edge_cases() {
1253 assert!(FileGroup::default().group_by_partition_values(4).is_empty());
1255 assert!(
1256 FileGroup::new(vec![pfile("a", 100)])
1257 .group_by_partition_values(0)
1258 .is_empty()
1259 );
1260 }
1261
1262 #[test]
1263 fn test_group_by_partition_values_less_groups_than_target() {
1264 let fg = FileGroup::new(vec![
1269 pfile_with_pv("a", "p1"),
1270 pfile_with_pv("b", "p1"),
1271 pfile_with_pv("c", "p2"),
1272 ]);
1273 let groups = fg.group_by_partition_values(4);
1274 assert_eq!(groups.len(), 2);
1275 assert_eq!(groups[0].len(), 2);
1276 assert_eq!(groups[1].len(), 1);
1277 }
1278
1279 #[test]
1280 fn test_group_by_partition_values_more_groups_than_target() {
1281 let fg = FileGroup::new(vec![
1284 pfile_with_pv("a", "p1"),
1285 pfile_with_pv("b", "p2"),
1286 pfile_with_pv("c", "p3"),
1287 pfile_with_pv("d", "p4"),
1288 pfile_with_pv("e", "p5"),
1289 ]);
1290 let groups = fg.group_by_partition_values(3);
1291 assert_eq!(groups.len(), 3);
1292 assert_eq!(groups[0].len(), 2);
1293 assert_eq!(groups[1].len(), 2);
1294 assert_eq!(groups[2].len(), 1);
1295 }
1296}