datafusion_datasource/
file_groups.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Logic for managing groups of [`PartitionedFile`]s in DataFusion
19
20use crate::{FileRange, PartitionedFile};
21use datafusion_common::Statistics;
22use itertools::Itertools;
23use std::cmp::min;
24use std::collections::BinaryHeap;
25use std::iter::repeat_with;
26use std::mem;
27use std::ops::{Index, IndexMut};
28use std::sync::Arc;
29
30/// Repartition input files into `target_partitions` partitions, if total file size exceed
31/// `repartition_file_min_size`
32///
33/// This partitions evenly by file byte range, and does not have any knowledge
34/// of how data is laid out in specific files. The specific `FileOpener` are
35/// responsible for the actual partitioning on specific data source type. (e.g.
36/// the `CsvOpener` will read lines overlap with byte range as well as
37/// handle boundaries to ensure all lines will be read exactly once)
38///
39/// # Example
40///
41/// For example, if there are two files `A` and `B` that we wish to read with 4
42/// partitions (with 4 threads) they will be divided as follows:
43///
44/// ```text
45///                                    ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
46///                                      ┌─────────────────┐
47///                                    │ │                 │ │
48///                                      │     File A      │
49///                                    │ │  Range: 0-2MB   │ │
50///                                      │                 │
51///                                    │ └─────────────────┘ │
52///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
53/// ┌─────────────────┐                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
54/// │                 │                  ┌─────────────────┐
55/// │                 │                │ │                 │ │
56/// │                 │                  │     File A      │
57/// │                 │                │ │   Range 2-4MB   │ │
58/// │                 │                  │                 │
59/// │                 │                │ └─────────────────┘ │
60/// │  File A (7MB)   │   ────────▶     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
61/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
62/// │                 │                  ┌─────────────────┐
63/// │                 │                │ │                 │ │
64/// │                 │                  │     File A      │
65/// │                 │                │ │  Range: 4-6MB   │ │
66/// │                 │                  │                 │
67/// │                 │                │ └─────────────────┘ │
68/// └─────────────────┘                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
69/// ┌─────────────────┐                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
70/// │  File B (1MB)   │                  ┌─────────────────┐
71/// │                 │                │ │     File A      │ │
72/// └─────────────────┘                  │  Range: 6-7MB   │
73///                                    │ └─────────────────┘ │
74///                                      ┌─────────────────┐
75///                                    │ │  File B (1MB)   │ │
76///                                      │                 │
77///                                    │ └─────────────────┘ │
78///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
79///
80///                                    If target_partitions = 4,
81///                                      divides into 4 groups
82/// ```
83///
84/// # Maintaining Order
85///
86/// Within each group files are read sequentially. Thus, if the overall order of
87/// tuples must be preserved, multiple files can not be mixed in the same group.
88///
89/// In this case, the code will split the largest files evenly into any
90/// available empty groups, but the overall distribution may not be as even
91/// as if the order did not need to be preserved.
92///
93/// ```text
94///                                   ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
95///                                      ┌─────────────────┐
96///                                    │ │                 │ │
97///                                      │     File A      │
98///                                    │ │  Range: 0-2MB   │ │
99///                                      │                 │
100/// ┌─────────────────┐                │ └─────────────────┘ │
101/// │                 │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
102/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
103/// │                 │                  ┌─────────────────┐
104/// │                 │                │ │                 │ │
105/// │                 │                  │     File A      │
106/// │                 │                │ │   Range 2-4MB   │ │
107/// │  File A (6MB)   │   ────────▶      │                 │
108/// │    (ordered)    │                │ └─────────────────┘ │
109/// │                 │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
110/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
111/// │                 │                  ┌─────────────────┐
112/// │                 │                │ │                 │ │
113/// │                 │                  │     File A      │
114/// │                 │                │ │  Range: 4-6MB   │ │
115/// └─────────────────┘                  │                 │
116/// ┌─────────────────┐                │ └─────────────────┘ │
117/// │  File B (1MB)   │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
118/// │    (ordered)    │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
119/// └─────────────────┘                  ┌─────────────────┐
120///                                    │ │  File B (1MB)   │ │
121///                                      │                 │
122///                                    │ └─────────────────┘ │
123///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
124///
125///                                    If target_partitions = 4,
126///                                      divides into 4 groups
127/// ```
128#[derive(Debug, Clone, Copy)]
129pub struct FileGroupPartitioner {
130    /// how many partitions should be created
131    target_partitions: usize,
132    /// the minimum size for a file to be repartitioned.
133    repartition_file_min_size: usize,
134    /// if the order when reading the files must be preserved
135    preserve_order_within_groups: bool,
136}
137
138impl Default for FileGroupPartitioner {
139    fn default() -> Self {
140        Self::new()
141    }
142}
143
144impl FileGroupPartitioner {
145    /// Creates a new [`FileGroupPartitioner`] with default values:
146    /// 1. `target_partitions = 1`
147    /// 2. `repartition_file_min_size = 10MB`
148    /// 3. `preserve_order_within_groups = false`
149    pub fn new() -> Self {
150        Self {
151            target_partitions: 1,
152            repartition_file_min_size: 10 * 1024 * 1024,
153            preserve_order_within_groups: false,
154        }
155    }
156
157    /// Set the target partitions
158    pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
159        self.target_partitions = target_partitions;
160        self
161    }
162
163    /// Set the minimum size at which to repartition a file
164    pub fn with_repartition_file_min_size(
165        mut self,
166        repartition_file_min_size: usize,
167    ) -> Self {
168        self.repartition_file_min_size = repartition_file_min_size;
169        self
170    }
171
172    /// Set whether the order of tuples within a file must be preserved
173    pub fn with_preserve_order_within_groups(
174        mut self,
175        preserve_order_within_groups: bool,
176    ) -> Self {
177        self.preserve_order_within_groups = preserve_order_within_groups;
178        self
179    }
180
181    /// Repartition input files according to the settings on this [`FileGroupPartitioner`].
182    ///
183    /// If no repartitioning is needed or possible, return `None`.
184    pub fn repartition_file_groups(
185        &self,
186        file_groups: &[FileGroup],
187    ) -> Option<Vec<FileGroup>> {
188        if file_groups.is_empty() {
189            return None;
190        }
191
192        // Perform redistribution only in case all files should be read from beginning to end
193        let has_ranges = file_groups
194            .iter()
195            .flat_map(FileGroup::iter)
196            .any(|f| f.range.is_some());
197        if has_ranges {
198            return None;
199        }
200
201        //  special case when order must be preserved
202        if self.preserve_order_within_groups {
203            self.repartition_preserving_order(file_groups)
204        } else {
205            self.repartition_evenly_by_size(file_groups)
206        }
207    }
208
209    /// Evenly repartition files across partitions by size, ignoring any
210    /// existing grouping / ordering
211    fn repartition_evenly_by_size(
212        &self,
213        file_groups: &[FileGroup],
214    ) -> Option<Vec<FileGroup>> {
215        let target_partitions = self.target_partitions;
216        let repartition_file_min_size = self.repartition_file_min_size;
217        let flattened_files = file_groups.iter().flat_map(FileGroup::iter).collect_vec();
218
219        let total_size = flattened_files
220            .iter()
221            .map(|f| f.object_meta.size as i64)
222            .sum::<i64>();
223        if total_size < (repartition_file_min_size as i64) || total_size == 0 {
224            return None;
225        }
226
227        let target_partition_size =
228            (total_size as u64).div_ceil(target_partitions as u64);
229
230        let current_partition_index: usize = 0;
231        let current_partition_size: u64 = 0;
232
233        // Partition byte range evenly for all `PartitionedFile`s
234        let repartitioned_files = flattened_files
235            .into_iter()
236            .scan(
237                (current_partition_index, current_partition_size),
238                |state, source_file| {
239                    let mut produced_files = vec![];
240                    let mut range_start = 0;
241                    while range_start < source_file.object_meta.size {
242                        let range_end = min(
243                            range_start + (target_partition_size - state.1),
244                            source_file.object_meta.size,
245                        );
246
247                        let mut produced_file = source_file.clone();
248                        produced_file.range = Some(FileRange {
249                            start: range_start as i64,
250                            end: range_end as i64,
251                        });
252                        produced_files.push((state.0, produced_file));
253
254                        if state.1 + (range_end - range_start) >= target_partition_size {
255                            state.0 += 1;
256                            state.1 = 0;
257                        } else {
258                            state.1 += range_end - range_start;
259                        }
260                        range_start = range_end;
261                    }
262                    Some(produced_files)
263                },
264            )
265            .flatten()
266            .chunk_by(|(partition_idx, _)| *partition_idx)
267            .into_iter()
268            .map(|(_, group)| FileGroup::new(group.map(|(_, vals)| vals).collect_vec()))
269            .collect_vec();
270
271        Some(repartitioned_files)
272    }
273
274    /// Redistribute file groups across size preserving order
275    fn repartition_preserving_order(
276        &self,
277        file_groups: &[FileGroup],
278    ) -> Option<Vec<FileGroup>> {
279        // Can't repartition and preserve order if there are more groups
280        // than partitions
281        if file_groups.len() >= self.target_partitions {
282            return None;
283        }
284        let num_new_groups = self.target_partitions - file_groups.len();
285
286        // If there is only a single file
287        if file_groups.len() == 1 && file_groups[0].len() == 1 {
288            return self.repartition_evenly_by_size(file_groups);
289        }
290
291        // Find which files could be split (single file groups)
292        let mut heap: BinaryHeap<_> = file_groups
293            .iter()
294            .enumerate()
295            .filter_map(|(group_index, group)| {
296                // ignore groups that do not have exactly 1 file
297                if group.len() == 1 {
298                    Some(ToRepartition {
299                        source_index: group_index,
300                        file_size: group[0].object_meta.size,
301                        new_groups: vec![group_index],
302                    })
303                } else {
304                    None
305                }
306            })
307            .collect();
308
309        // No files can be redistributed
310        if heap.is_empty() {
311            return None;
312        }
313
314        // Add new empty groups to which we will redistribute ranges of existing files
315        // Add new empty groups to which we will redistribute ranges of existing files
316        let mut file_groups: Vec<_> = file_groups
317            .iter()
318            .cloned()
319            .chain(repeat_with(|| FileGroup::new(Vec::new())).take(num_new_groups))
320            .collect();
321
322        // Divide up empty groups
323        for (group_index, group) in file_groups.iter().enumerate() {
324            if !group.is_empty() {
325                continue;
326            }
327            // Pick the file that has the largest ranges to read so far
328            let mut largest_group = heap.pop().unwrap();
329            largest_group.new_groups.push(group_index);
330            heap.push(largest_group);
331        }
332
333        // Distribute files to their newly assigned groups
334        while let Some(to_repartition) = heap.pop() {
335            let range_size = to_repartition.range_size() as i64;
336            let ToRepartition {
337                source_index,
338                file_size,
339                new_groups,
340            } = to_repartition;
341            assert_eq!(file_groups[source_index].len(), 1);
342            let original_file = file_groups[source_index].pop().unwrap();
343
344            let last_group = new_groups.len() - 1;
345            let mut range_start: i64 = 0;
346            let mut range_end: i64 = range_size;
347            for (i, group_index) in new_groups.into_iter().enumerate() {
348                let target_group = &mut file_groups[group_index];
349                assert!(target_group.is_empty());
350
351                // adjust last range to include the entire file
352                if i == last_group {
353                    range_end = file_size as i64;
354                }
355                target_group
356                    .push(original_file.clone().with_range(range_start, range_end));
357                range_start = range_end;
358                range_end += range_size;
359            }
360        }
361
362        Some(file_groups)
363    }
364}
365
366/// Represents a group of partitioned files that'll be processed by a single thread.
367/// Maintains optional statistics across all files in the group.
368#[derive(Debug, Clone)]
369pub struct FileGroup {
370    /// The files in this group
371    files: Vec<PartitionedFile>,
372    /// Optional statistics for the data across all files in the group
373    statistics: Option<Arc<Statistics>>,
374}
375
376impl FileGroup {
377    /// Creates a new FileGroup from a vector of PartitionedFile objects
378    pub fn new(files: Vec<PartitionedFile>) -> Self {
379        Self {
380            files,
381            statistics: None,
382        }
383    }
384
385    /// Returns the number of files in this group
386    pub fn len(&self) -> usize {
387        self.files.len()
388    }
389
390    /// Set the statistics for this group
391    pub fn with_statistics(mut self, statistics: Arc<Statistics>) -> Self {
392        self.statistics = Some(statistics);
393        self
394    }
395
396    /// Returns a slice of the files in this group
397    pub fn files(&self) -> &[PartitionedFile] {
398        &self.files
399    }
400
401    pub fn iter(&self) -> impl Iterator<Item = &PartitionedFile> {
402        self.files.iter()
403    }
404
405    pub fn into_inner(self) -> Vec<PartitionedFile> {
406        self.files
407    }
408
409    pub fn is_empty(&self) -> bool {
410        self.files.is_empty()
411    }
412
413    /// Removes the last element from the files vector and returns it, or None if empty
414    pub fn pop(&mut self) -> Option<PartitionedFile> {
415        self.files.pop()
416    }
417
418    /// Adds a file to the group
419    pub fn push(&mut self, file: PartitionedFile) {
420        self.files.push(file);
421    }
422
423    /// Get the statistics for this group
424    pub fn statistics(&self) -> Option<&Statistics> {
425        self.statistics.as_deref()
426    }
427
428    /// Partition the list of files into `n` groups
429    pub fn split_files(mut self, n: usize) -> Vec<FileGroup> {
430        if self.is_empty() {
431            return vec![];
432        }
433
434        // ObjectStore::list does not guarantee any consistent order and for some
435        // implementations such as LocalFileSystem, it may be inconsistent. Thus
436        // Sort files by path to ensure consistent plans when run more than once.
437        self.files.sort_by(|a, b| a.path().cmp(b.path()));
438
439        // effectively this is div with rounding up instead of truncating
440        let chunk_size = self.len().div_ceil(n);
441        let mut chunks = Vec::with_capacity(n);
442        let mut current_chunk = Vec::with_capacity(chunk_size);
443        for file in self.files.drain(..) {
444            current_chunk.push(file);
445            if current_chunk.len() == chunk_size {
446                let full_chunk = FileGroup::new(mem::replace(
447                    &mut current_chunk,
448                    Vec::with_capacity(chunk_size),
449                ));
450                chunks.push(full_chunk);
451            }
452        }
453
454        if !current_chunk.is_empty() {
455            chunks.push(FileGroup::new(current_chunk))
456        }
457
458        chunks
459    }
460}
461
462impl Index<usize> for FileGroup {
463    type Output = PartitionedFile;
464
465    fn index(&self, index: usize) -> &Self::Output {
466        &self.files[index]
467    }
468}
469
470impl IndexMut<usize> for FileGroup {
471    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
472        &mut self.files[index]
473    }
474}
475
476impl FromIterator<PartitionedFile> for FileGroup {
477    fn from_iter<I: IntoIterator<Item = PartitionedFile>>(iter: I) -> Self {
478        let files = iter.into_iter().collect();
479        FileGroup::new(files)
480    }
481}
482
483impl From<Vec<PartitionedFile>> for FileGroup {
484    fn from(files: Vec<PartitionedFile>) -> Self {
485        FileGroup::new(files)
486    }
487}
488
489impl Default for FileGroup {
490    fn default() -> Self {
491        Self::new(Vec::new())
492    }
493}
494
495/// Tracks how a individual file will be repartitioned
496#[derive(Debug, Clone, PartialEq, Eq)]
497struct ToRepartition {
498    /// the index from which the original file will be taken
499    source_index: usize,
500    /// the size of the original file
501    file_size: u64,
502    /// indexes of which group(s) will this be distributed to (including `source_index`)
503    new_groups: Vec<usize>,
504}
505
506impl ToRepartition {
507    /// How big will each file range be when this file is read in its new groups?
508    fn range_size(&self) -> u64 {
509        self.file_size / (self.new_groups.len() as u64)
510    }
511}
512
513impl PartialOrd for ToRepartition {
514    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
515        Some(self.cmp(other))
516    }
517}
518
519/// Order based on individual range
520impl Ord for ToRepartition {
521    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
522        self.range_size().cmp(&other.range_size())
523    }
524}
525
526#[cfg(test)]
527mod test {
528    use super::*;
529
530    /// Empty file won't get partitioned
531    #[test]
532    fn repartition_empty_file_only() {
533        let partitioned_file_empty = pfile("empty", 0);
534        let file_group = vec![FileGroup::new(vec![partitioned_file_empty])];
535
536        let partitioned_files = FileGroupPartitioner::new()
537            .with_target_partitions(4)
538            .with_repartition_file_min_size(0)
539            .repartition_file_groups(&file_group);
540
541        assert_partitioned_files(None, partitioned_files);
542    }
543
544    /// Repartition when there is a empty file in file groups
545    #[test]
546    fn repartition_empty_files() {
547        let pfile_a = pfile("a", 10);
548        let pfile_b = pfile("b", 10);
549        let pfile_empty = pfile("empty", 0);
550
551        let empty_first = vec![
552            FileGroup::new(vec![pfile_empty.clone()]),
553            FileGroup::new(vec![pfile_a.clone()]),
554            FileGroup::new(vec![pfile_b.clone()]),
555        ];
556        let empty_middle = vec![
557            FileGroup::new(vec![pfile_a.clone()]),
558            FileGroup::new(vec![pfile_empty.clone()]),
559            FileGroup::new(vec![pfile_b.clone()]),
560        ];
561        let empty_last = vec![
562            FileGroup::new(vec![pfile_a]),
563            FileGroup::new(vec![pfile_b]),
564            FileGroup::new(vec![pfile_empty]),
565        ];
566
567        // Repartition file groups into x partitions
568        let expected_2 = vec![
569            FileGroup::new(vec![pfile("a", 10).with_range(0, 10)]),
570            FileGroup::new(vec![pfile("b", 10).with_range(0, 10)]),
571        ];
572        let expected_3 = vec![
573            FileGroup::new(vec![pfile("a", 10).with_range(0, 7)]),
574            FileGroup::new(vec![
575                pfile("a", 10).with_range(7, 10),
576                pfile("b", 10).with_range(0, 4),
577            ]),
578            FileGroup::new(vec![pfile("b", 10).with_range(4, 10)]),
579        ];
580
581        let file_groups_tests = [empty_first, empty_middle, empty_last];
582
583        for fg in file_groups_tests {
584            let all_expected = [(2, expected_2.clone()), (3, expected_3.clone())];
585            for (n_partition, expected) in all_expected {
586                let actual = FileGroupPartitioner::new()
587                    .with_target_partitions(n_partition)
588                    .with_repartition_file_min_size(10)
589                    .repartition_file_groups(&fg);
590
591                assert_partitioned_files(Some(expected), actual);
592            }
593        }
594    }
595
596    #[test]
597    fn repartition_single_file() {
598        // Single file, single partition into multiple partitions
599        let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
600
601        let actual = FileGroupPartitioner::new()
602            .with_target_partitions(4)
603            .with_repartition_file_min_size(10)
604            .repartition_file_groups(&single_partition);
605
606        let expected = Some(vec![
607            FileGroup::new(vec![pfile("a", 123).with_range(0, 31)]),
608            FileGroup::new(vec![pfile("a", 123).with_range(31, 62)]),
609            FileGroup::new(vec![pfile("a", 123).with_range(62, 93)]),
610            FileGroup::new(vec![pfile("a", 123).with_range(93, 123)]),
611        ]);
612        assert_partitioned_files(expected, actual);
613    }
614
615    #[test]
616    fn repartition_too_much_partitions() {
617        // Single file, single partition into 96 partitions
618        let partitioned_file = pfile("a", 8);
619        let single_partition = vec![FileGroup::new(vec![partitioned_file])];
620
621        let actual = FileGroupPartitioner::new()
622            .with_target_partitions(96)
623            .with_repartition_file_min_size(5)
624            .repartition_file_groups(&single_partition);
625
626        let expected = Some(vec![
627            FileGroup::new(vec![pfile("a", 8).with_range(0, 1)]),
628            FileGroup::new(vec![pfile("a", 8).with_range(1, 2)]),
629            FileGroup::new(vec![pfile("a", 8).with_range(2, 3)]),
630            FileGroup::new(vec![pfile("a", 8).with_range(3, 4)]),
631            FileGroup::new(vec![pfile("a", 8).with_range(4, 5)]),
632            FileGroup::new(vec![pfile("a", 8).with_range(5, 6)]),
633            FileGroup::new(vec![pfile("a", 8).with_range(6, 7)]),
634            FileGroup::new(vec![pfile("a", 8).with_range(7, 8)]),
635        ]);
636
637        assert_partitioned_files(expected, actual);
638    }
639
640    #[test]
641    fn repartition_multiple_partitions() {
642        // Multiple files in single partition after redistribution
643        let source_partitions = vec![
644            FileGroup::new(vec![pfile("a", 40)]),
645            FileGroup::new(vec![pfile("b", 60)]),
646        ];
647
648        let actual = FileGroupPartitioner::new()
649            .with_target_partitions(3)
650            .with_repartition_file_min_size(10)
651            .repartition_file_groups(&source_partitions);
652
653        let expected = Some(vec![
654            FileGroup::new(vec![pfile("a", 40).with_range(0, 34)]),
655            FileGroup::new(vec![
656                pfile("a", 40).with_range(34, 40),
657                pfile("b", 60).with_range(0, 28),
658            ]),
659            FileGroup::new(vec![pfile("b", 60).with_range(28, 60)]),
660        ]);
661        assert_partitioned_files(expected, actual);
662    }
663
664    #[test]
665    fn repartition_same_num_partitions() {
666        // "Rebalance" files across partitions
667        let source_partitions = vec![
668            FileGroup::new(vec![pfile("a", 40)]),
669            FileGroup::new(vec![pfile("b", 60)]),
670        ];
671
672        let actual = FileGroupPartitioner::new()
673            .with_target_partitions(2)
674            .with_repartition_file_min_size(10)
675            .repartition_file_groups(&source_partitions);
676
677        let expected = Some(vec![
678            FileGroup::new(vec![
679                pfile("a", 40).with_range(0, 40),
680                pfile("b", 60).with_range(0, 10),
681            ]),
682            FileGroup::new(vec![pfile("b", 60).with_range(10, 60)]),
683        ]);
684        assert_partitioned_files(expected, actual);
685    }
686
687    #[test]
688    fn repartition_no_action_ranges() {
689        // No action due to Some(range) in second file
690        let source_partitions = vec![
691            FileGroup::new(vec![pfile("a", 123)]),
692            FileGroup::new(vec![pfile("b", 144).with_range(1, 50)]),
693        ];
694
695        let actual = FileGroupPartitioner::new()
696            .with_target_partitions(65)
697            .with_repartition_file_min_size(10)
698            .repartition_file_groups(&source_partitions);
699
700        assert_partitioned_files(None, actual)
701    }
702
703    #[test]
704    fn repartition_no_action_min_size() {
705        // No action due to target_partition_size
706        let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
707
708        let actual = FileGroupPartitioner::new()
709            .with_target_partitions(65)
710            .with_repartition_file_min_size(500)
711            .repartition_file_groups(&single_partition);
712
713        assert_partitioned_files(None, actual)
714    }
715
716    #[test]
717    fn repartition_no_action_zero_files() {
718        // No action due to no files
719        let empty_partition = vec![];
720
721        let partitioner = FileGroupPartitioner::new()
722            .with_target_partitions(65)
723            .with_repartition_file_min_size(500);
724
725        assert_partitioned_files(None, repartition_test(partitioner, empty_partition))
726    }
727
728    #[test]
729    fn repartition_ordered_no_action_too_few_partitions() {
730        // No action as there are no new groups to redistribute to
731        let input_partitions = vec![
732            FileGroup::new(vec![pfile("a", 100)]),
733            FileGroup::new(vec![pfile("b", 200)]),
734        ];
735
736        let actual = FileGroupPartitioner::new()
737            .with_preserve_order_within_groups(true)
738            .with_target_partitions(2)
739            .with_repartition_file_min_size(10)
740            .repartition_file_groups(&input_partitions);
741
742        assert_partitioned_files(None, actual)
743    }
744
745    #[test]
746    fn repartition_ordered_no_action_file_too_small() {
747        // No action as there are no new groups to redistribute to
748        let single_partition = vec![FileGroup::new(vec![pfile("a", 100)])];
749
750        let actual = FileGroupPartitioner::new()
751            .with_preserve_order_within_groups(true)
752            .with_target_partitions(2)
753            // file is too small to repartition
754            .with_repartition_file_min_size(1000)
755            .repartition_file_groups(&single_partition);
756
757        assert_partitioned_files(None, actual)
758    }
759
760    #[test]
761    fn repartition_ordered_one_large_file() {
762        // "Rebalance" the single large file across partitions
763        let source_partitions = vec![FileGroup::new(vec![pfile("a", 100)])];
764
765        let actual = FileGroupPartitioner::new()
766            .with_preserve_order_within_groups(true)
767            .with_target_partitions(3)
768            .with_repartition_file_min_size(10)
769            .repartition_file_groups(&source_partitions);
770
771        let expected = Some(vec![
772            FileGroup::new(vec![pfile("a", 100).with_range(0, 34)]),
773            FileGroup::new(vec![pfile("a", 100).with_range(34, 68)]),
774            FileGroup::new(vec![pfile("a", 100).with_range(68, 100)]),
775        ]);
776        assert_partitioned_files(expected, actual);
777    }
778
779    #[test]
780    fn repartition_ordered_one_large_one_small_file() {
781        // "Rebalance" the single large file across empty partitions, but can't split
782        // small file
783        let source_partitions = vec![
784            FileGroup::new(vec![pfile("a", 100)]),
785            FileGroup::new(vec![pfile("b", 30)]),
786        ];
787
788        let actual = FileGroupPartitioner::new()
789            .with_preserve_order_within_groups(true)
790            .with_target_partitions(4)
791            .with_repartition_file_min_size(10)
792            .repartition_file_groups(&source_partitions);
793
794        let expected = Some(vec![
795            // scan first third of "a"
796            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
797            // only b in this group (can't do this)
798            FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
799            // second third of "a"
800            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
801            // final third of "a"
802            FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
803        ]);
804        assert_partitioned_files(expected, actual);
805    }
806
807    #[test]
808    fn repartition_ordered_two_large_files() {
809        // "Rebalance" two large files across empty partitions, but can't mix them
810        let source_partitions = vec![
811            FileGroup::new(vec![pfile("a", 100)]),
812            FileGroup::new(vec![pfile("b", 100)]),
813        ];
814
815        let actual = FileGroupPartitioner::new()
816            .with_preserve_order_within_groups(true)
817            .with_target_partitions(4)
818            .with_repartition_file_min_size(10)
819            .repartition_file_groups(&source_partitions);
820
821        let expected = Some(vec![
822            // scan first half of "a"
823            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
824            // scan first half of "b"
825            FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
826            // second half of "a"
827            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
828            // second half of "b"
829            FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
830        ]);
831        assert_partitioned_files(expected, actual);
832    }
833
834    #[test]
835    fn repartition_ordered_two_large_one_small_files() {
836        // "Rebalance" two large files and one small file across empty partitions
837        let source_partitions = vec![
838            FileGroup::new(vec![pfile("a", 100)]),
839            FileGroup::new(vec![pfile("b", 100)]),
840            FileGroup::new(vec![pfile("c", 30)]),
841        ];
842
843        let partitioner = FileGroupPartitioner::new()
844            .with_preserve_order_within_groups(true)
845            .with_repartition_file_min_size(10);
846
847        // with 4 partitions, can only split the first large file "a"
848        let actual = partitioner
849            .with_target_partitions(4)
850            .repartition_file_groups(&source_partitions);
851
852        let expected = Some(vec![
853            // scan first half of "a"
854            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
855            // All of "b"
856            FileGroup::new(vec![pfile("b", 100).with_range(0, 100)]),
857            // All of "c"
858            FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
859            // second half of "a"
860            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
861        ]);
862        assert_partitioned_files(expected, actual);
863
864        // With 5 partitions, we can split both "a" and "b", but they can't be intermixed
865        let actual = partitioner
866            .with_target_partitions(5)
867            .repartition_file_groups(&source_partitions);
868
869        let expected = Some(vec![
870            // scan first half of "a"
871            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
872            // scan first half of "b"
873            FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
874            // All of "c"
875            FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
876            // second half of "a"
877            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
878            // second half of "b"
879            FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
880        ]);
881        assert_partitioned_files(expected, actual);
882    }
883
884    #[test]
885    fn repartition_ordered_one_large_one_small_existing_empty() {
886        // "Rebalance" files using existing empty partition
887        let source_partitions = vec![
888            FileGroup::new(vec![pfile("a", 100)]),
889            FileGroup::default(),
890            FileGroup::new(vec![pfile("b", 40)]),
891            FileGroup::default(),
892        ];
893
894        let actual = FileGroupPartitioner::new()
895            .with_preserve_order_within_groups(true)
896            .with_target_partitions(5)
897            .with_repartition_file_min_size(10)
898            .repartition_file_groups(&source_partitions);
899
900        // Of the three available groups (2 original empty and 1 new from the
901        // target partitions), assign two to "a" and one to "b"
902        let expected = Some(vec![
903            // Scan of "a" across three groups
904            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
905            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
906            // scan first half of "b"
907            FileGroup::new(vec![pfile("b", 40).with_range(0, 20)]),
908            // final third of "a"
909            FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
910            // second half of "b"
911            FileGroup::new(vec![pfile("b", 40).with_range(20, 40)]),
912        ]);
913        assert_partitioned_files(expected, actual);
914    }
915    #[test]
916    fn repartition_ordered_existing_group_multiple_files() {
917        // groups with multiple files in a group can not be changed, but can divide others
918        let source_partitions = vec![
919            // two files in an existing partition
920            FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
921            FileGroup::new(vec![pfile("c", 40)]),
922        ];
923
924        let actual = FileGroupPartitioner::new()
925            .with_preserve_order_within_groups(true)
926            .with_target_partitions(3)
927            .with_repartition_file_min_size(10)
928            .repartition_file_groups(&source_partitions);
929
930        // Of the three available groups (2 original empty and 1 new from the
931        // target partitions), assign two to "a" and one to "b"
932        let expected = Some(vec![
933            // don't try and rearrange files in the existing partition
934            // assuming that the caller had a good reason to put them that way.
935            // (it is technically possible to split off ranges from the files if desired)
936            FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
937            // first half of "c"
938            FileGroup::new(vec![pfile("c", 40).with_range(0, 20)]),
939            // second half of "c"
940            FileGroup::new(vec![pfile("c", 40).with_range(20, 40)]),
941        ]);
942        assert_partitioned_files(expected, actual);
943    }
944
945    /// Asserts that the two groups of [`PartitionedFile`] are the same
946    /// (PartitionedFile doesn't implement PartialEq)
947    fn assert_partitioned_files(
948        expected: Option<Vec<FileGroup>>,
949        actual: Option<Vec<FileGroup>>,
950    ) {
951        match (expected, actual) {
952            (None, None) => {}
953            (Some(_), None) => panic!("Expected Some, got None"),
954            (None, Some(_)) => panic!("Expected None, got Some"),
955            (Some(expected), Some(actual)) => {
956                let expected_string = format!("{:#?}", expected);
957                let actual_string = format!("{:#?}", actual);
958                assert_eq!(expected_string, actual_string);
959            }
960        }
961    }
962
963    /// returns a partitioned file with the specified path and size
964    fn pfile(path: impl Into<String>, file_size: u64) -> PartitionedFile {
965        PartitionedFile::new(path, file_size)
966    }
967
968    /// repartition the file groups both with and without preserving order
969    /// asserting they return the same value and returns that value
970    fn repartition_test(
971        partitioner: FileGroupPartitioner,
972        file_groups: Vec<FileGroup>,
973    ) -> Option<Vec<FileGroup>> {
974        let repartitioned = partitioner.repartition_file_groups(&file_groups);
975
976        let repartitioned_preserving_sort = partitioner
977            .with_preserve_order_within_groups(true)
978            .repartition_file_groups(&file_groups);
979
980        assert_partitioned_files(repartitioned.clone(), repartitioned_preserving_sort);
981        repartitioned
982    }
983}