Skip to main content

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 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/// Repartition input files into `target_partitions` partitions, if total file size exceed
33/// `repartition_file_min_size`
34///
35/// This partitions evenly by file byte range, and does not have any knowledge
36/// of how data is laid out in specific files. The specific `FileOpener` are
37/// responsible for the actual partitioning on specific data source type. (e.g.
38/// the `CsvOpener` will read lines overlap with byte range as well as
39/// handle boundaries to ensure all lines will be read exactly once)
40///
41/// # Example
42///
43/// For example, if there are two files `A` and `B` that we wish to read with 4
44/// partitions (with 4 threads) they will be divided as follows:
45///
46/// ```text
47///                                    ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
48///                                      ┌─────────────────┐
49///                                    │ │                 │ │
50///                                      │     File A      │
51///                                    │ │  Range: 0-2MB   │ │
52///                                      │                 │
53///                                    │ └─────────────────┘ │
54///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
55/// ┌─────────────────┐                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
56/// │                 │                  ┌─────────────────┐
57/// │                 │                │ │                 │ │
58/// │                 │                  │     File A      │
59/// │                 │                │ │   Range 2-4MB   │ │
60/// │                 │                  │                 │
61/// │                 │                │ └─────────────────┘ │
62/// │  File A (7MB)   │   ────────▶     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
63/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
64/// │                 │                  ┌─────────────────┐
65/// │                 │                │ │                 │ │
66/// │                 │                  │     File A      │
67/// │                 │                │ │  Range: 4-6MB   │ │
68/// │                 │                  │                 │
69/// │                 │                │ └─────────────────┘ │
70/// └─────────────────┘                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
71/// ┌─────────────────┐                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
72/// │  File B (1MB)   │                  ┌─────────────────┐
73/// │                 │                │ │     File A      │ │
74/// └─────────────────┘                  │  Range: 6-7MB   │
75///                                    │ └─────────────────┘ │
76///                                      ┌─────────────────┐
77///                                    │ │  File B (1MB)   │ │
78///                                      │                 │
79///                                    │ └─────────────────┘ │
80///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
81///
82///                                    If target_partitions = 4,
83///                                      divides into 4 groups
84/// ```
85///
86/// # Maintaining Order
87///
88/// Within each group files are read sequentially. Thus, if the overall order of
89/// tuples must be preserved, multiple files can not be mixed in the same group.
90///
91/// In this case, the code will split the largest files evenly into any
92/// available empty groups, but the overall distribution may not be as even
93/// as if the order did not need to be preserved.
94///
95/// ```text
96///                                   ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
97///                                      ┌─────────────────┐
98///                                    │ │                 │ │
99///                                      │     File A      │
100///                                    │ │  Range: 0-2MB   │ │
101///                                      │                 │
102/// ┌─────────────────┐                │ └─────────────────┘ │
103/// │                 │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
104/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
105/// │                 │                  ┌─────────────────┐
106/// │                 │                │ │                 │ │
107/// │                 │                  │     File A      │
108/// │                 │                │ │   Range 2-4MB   │ │
109/// │  File A (6MB)   │   ────────▶      │                 │
110/// │    (ordered)    │                │ └─────────────────┘ │
111/// │                 │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
112/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
113/// │                 │                  ┌─────────────────┐
114/// │                 │                │ │                 │ │
115/// │                 │                  │     File A      │
116/// │                 │                │ │  Range: 4-6MB   │ │
117/// └─────────────────┘                  │                 │
118/// ┌─────────────────┐                │ └─────────────────┘ │
119/// │  File B (1MB)   │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
120/// │    (ordered)    │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
121/// └─────────────────┘                  ┌─────────────────┐
122///                                    │ │  File B (1MB)   │ │
123///                                      │                 │
124///                                    │ └─────────────────┘ │
125///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
126///
127///                                    If target_partitions = 4,
128///                                      divides into 4 groups
129/// ```
130#[derive(Debug, Clone, Copy)]
131pub struct FileGroupPartitioner {
132    /// how many partitions should be created
133    target_partitions: usize,
134    /// the minimum size for a file to be repartitioned.
135    repartition_file_min_size: usize,
136    /// if the order when reading the files must be preserved
137    preserve_order_within_groups: bool,
138}
139
140impl Default for FileGroupPartitioner {
141    fn default() -> Self {
142        Self::new()
143    }
144}
145
146impl FileGroupPartitioner {
147    /// Creates a new [`FileGroupPartitioner`] with default values:
148    /// 1. `target_partitions = 1`
149    /// 2. `repartition_file_min_size = 10MB`
150    /// 3. `preserve_order_within_groups = false`
151    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    /// Set the target partitions
160    pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
161        self.target_partitions = target_partitions;
162        self
163    }
164
165    /// Set the minimum size at which to repartition a file
166    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    /// Set whether the order of tuples within a file must be preserved
175    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    /// Repartition input files according to the settings on this [`FileGroupPartitioner`].
184    ///
185    /// If no repartitioning is needed or possible, return `None`.
186    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        //  special case when order must be preserved
195        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    /// Evenly repartition files across partitions by size, ignoring any
203    /// existing grouping / ordering
204    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        // Partition byte range evenly for all `PartitionedFile`s
226        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    /// Redistribute file groups across size preserving order
270    fn repartition_preserving_order(
271        &self,
272        file_groups: &[FileGroup],
273    ) -> Option<Vec<FileGroup>> {
274        // Can't repartition and preserve order if there are more groups
275        // than partitions
276        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 there is only a single file
282        if file_groups.len() == 1 && file_groups[0].len() == 1 {
283            return self.repartition_evenly_by_size(file_groups);
284        }
285
286        // Find which files could be split (single file groups)
287        let mut heap: BinaryHeap<_> = file_groups
288            .iter()
289            .enumerate()
290            .filter_map(|(group_index, group)| {
291                // ignore groups that do not have exactly 1 file
292                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        // No files can be redistributed
306        if heap.is_empty() {
307            return None;
308        }
309
310        // Add new empty groups to which we will redistribute ranges of existing files
311        // Add new empty groups to which we will redistribute ranges of existing files
312        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        // Divide up empty groups
319        for (group_index, group) in file_groups.iter().enumerate() {
320            if !group.is_empty() {
321                continue;
322            }
323            // Pick the file that has the largest ranges to read so far
324            let mut largest_group = heap.pop().unwrap();
325            largest_group.new_groups.push(group_index);
326            heap.push(largest_group);
327        }
328
329        // Distribute files to their newly assigned groups
330        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                // adjust last range to include the entire file
348                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/// Represents a group of partitioned files that'll be processed by a single thread.
366/// Maintains optional statistics across all files in the group.
367///
368/// # Statistics
369///
370/// The group-level [`FileGroup::file_statistics`] field contains merged statistics from all files
371/// in the group for the **full table schema** (file columns + partition columns).
372///
373/// Partition column statistics are derived from the individual file partition values:
374/// - `min` = minimum partition value across all files in the group, or absent if any
375///   file in the group has a null partition value (see #26748)
376/// - `max` = maximum partition value across all files in the group, or absent if any
377///   file in the group has a null partition value
378/// - `null_count` = the number of rows in files with a null partition value
379///
380/// This allows query optimizers to prune entire file groups based on partition bounds.
381#[derive(Debug, Clone)]
382pub struct FileGroup {
383    /// The files in this group
384    files: Vec<PartitionedFile>,
385    /// Optional statistics for the data across all files in the group.
386    ///
387    /// These statistics cover the full table schema: file columns plus partition columns.
388    /// Partition column statistics are merged from individual [`PartitionedFile::statistics`],
389    /// which compute exact values from [`PartitionedFile::partition_values`].
390    statistics: Option<Arc<Statistics>>,
391}
392
393impl FileGroup {
394    /// Creates a new FileGroup from a vector of PartitionedFile objects
395    pub fn new(files: Vec<PartitionedFile>) -> Self {
396        Self {
397            files,
398            statistics: None,
399        }
400    }
401
402    /// Returns the number of files in this group
403    pub fn len(&self) -> usize {
404        self.files.len()
405    }
406
407    /// Set the statistics for this group
408    pub fn with_statistics(mut self, statistics: Arc<Statistics>) -> Self {
409        self.statistics = Some(statistics);
410        self
411    }
412
413    /// Returns a slice of the files in this group
414    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    /// Removes the last element from the files vector and returns it, or None if empty
431    pub fn pop(&mut self) -> Option<PartitionedFile> {
432        self.files.pop()
433    }
434
435    /// Adds a file to the group
436    pub fn push(&mut self, partitioned_file: PartitionedFile) {
437        self.files.push(partitioned_file);
438    }
439
440    /// Get the specific file statistics for the given index
441    /// If the index is None, return the `FileGroup` statistics
442    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    /// Get the mutable reference to the statistics for this group
451    pub fn statistics_mut(&mut self) -> Option<&mut Statistics> {
452        self.statistics.as_mut().map(Arc::make_mut)
453    }
454
455    /// Partition the list of files into `n` groups
456    pub fn split_files(mut self, n: usize) -> Vec<FileGroup> {
457        if self.is_empty() {
458            return vec![];
459        }
460
461        // ObjectStore::list does not guarantee any consistent order and for some
462        // implementations such as LocalFileSystem, it may be inconsistent. Thus
463        // Sort files by path to ensure consistent plans when run more than once.
464        self.files.sort_by(|a, b| a.path().cmp(b.path()));
465
466        // effectively this is div with rounding up instead of truncating
467        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    /// Groups files by their partition values, ensuring all files with same
489    /// partition values are in the same group.
490    ///
491    /// Note: May return fewer groups than `max_target_partitions` when the
492    /// number of unique partition values is less than the target.
493    #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key
494    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        // Sort for deterministic bucket assignment across query executions.
517        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            // Merge into max_target_partitions buckets using round-robin.
534            // This maintains grouping by partition value as we are merging groups which already
535            // contain all values for a partition key.
536            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/// Tracks how a individual file will be repartitioned
582#[derive(Debug, Clone)]
583struct ToRepartition {
584    /// the index from which the original file will be taken
585    source_index: usize,
586    /// the size of the original file
587    file_size: u64,
588    /// indexes of which group(s) will this be distributed to (including `source_index`)
589    new_groups: Vec<usize>,
590}
591
592impl ToRepartition {
593    /// How big will each file range be when this file is read in its new groups?
594    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        // PartialEq must be consistent with PartialOrd
618        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    /// Empty file won't get partitioned
640    #[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    /// Repartition when there is a empty file in file groups
654    #[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        // Repartition file groups into x partitions
677        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        // Single file, single partition into multiple partitions
708        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        // Single file, single partition into multiple partitions
727        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        // Single file, single partition into multiple partitions
747        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        // Single file, two partitions into multiple partitions
767        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        // Single file, single partition into 96 partitions
789        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        // Multiple files in single partition after redistribution
814        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        // "Rebalance" files across partitions
838        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        // No action due to target_partition_size
861        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        // No action due to no files
874        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        // No action as there are no new groups to redistribute to
886        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        // No action as there are no new groups to redistribute to
903        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            // file is too small to repartition
909            .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        // "Rebalance" the single large file across partitions
918        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        // "Rebalance" the single large file across partitions
937        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        // "Rebalance" the single large file across empty partitions, but can't split
957        // small file
958        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            // scan first third of "a"
971            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
972            // only b in this group (can't do this)
973            FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
974            // second third of "a"
975            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
976            // final third of "a"
977            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        // "Rebalance" the single large file across empty partitions, but can't split
985        // small file
986        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            // scan first third of "a"
999            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1000            // only b in this group (can't do this)
1001            FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1002            // second third of "a"
1003            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1004            // final third of "a"
1005            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        // "Rebalance" the single large file across empty partitions, but can't split
1013        // small file
1014        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            // scan first half of first "a"
1028            FileGroup::new(vec![pfile("a", 100).with_range(0, 25)]),
1029            // second "a" fully (not split)
1030            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1031            // only b in this group (can't do this)
1032            FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1033            // second half of first "a"
1034            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        // "Rebalance" the single large file across empty partitions, but can't split
1042        // small file
1043        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            // scan first third of "a"
1056            FileGroup::new(vec![pfile("a", 100).with_range(20, 40)]),
1057            // only b in this group (can't split this)
1058            FileGroup::new(vec![pfile("b", 30).with_range(5, 25)]),
1059            // second third of "a"
1060            FileGroup::new(vec![pfile("a", 100).with_range(40, 60)]),
1061            // final third of "a"
1062            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        // "Rebalance" two large files across empty partitions, but can't mix them
1070        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            // scan first half of "a"
1083            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1084            // scan first half of "b"
1085            FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1086            // second half of "a"
1087            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1088            // second half of "b"
1089            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        // "Rebalance" two large files and one small file across empty partitions
1097        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        // with 4 partitions, can only split the first large file "a"
1108        let actual = partitioner
1109            .with_target_partitions(4)
1110            .repartition_file_groups(&source_partitions);
1111
1112        let expected = Some(vec![
1113            // scan first half of "a"
1114            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1115            // All of "b"
1116            FileGroup::new(vec![pfile("b", 100).with_range(0, 100)]),
1117            // All of "c"
1118            FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1119            // second half of "a"
1120            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1121        ]);
1122        assert_partitioned_files(expected, actual);
1123
1124        // With 5 partitions, we can split both "a" and "b", but they can't be intermixed
1125        let actual = partitioner
1126            .with_target_partitions(5)
1127            .repartition_file_groups(&source_partitions);
1128
1129        let expected = Some(vec![
1130            // scan first half of "a"
1131            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1132            // scan first half of "b"
1133            FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1134            // All of "c"
1135            FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1136            // second half of "a"
1137            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1138            // second half of "b"
1139            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        // "Rebalance" files using existing empty partition
1147        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        // Of the three available groups (2 original empty and 1 new from the
1161        // target partitions), assign two to "a" and one to "b"
1162        let expected = Some(vec![
1163            // Scan of "a" across three groups
1164            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1165            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1166            // scan first half of "b"
1167            FileGroup::new(vec![pfile("b", 40).with_range(0, 20)]),
1168            // final third of "a"
1169            FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
1170            // second half of "b"
1171            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        // groups with multiple files in a group can not be changed, but can divide others
1178        let source_partitions = vec![
1179            // two files in an existing partition
1180            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        // Of the three available groups (2 original empty and 1 new from the
1191        // target partitions), assign two to "a" and one to "b"
1192        let expected = Some(vec![
1193            // don't try and rearrange files in the existing partition
1194            // assuming that the caller had a good reason to put them that way.
1195            // (it is technically possible to split off ranges from the files if desired)
1196            FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
1197            // first half of "c"
1198            FileGroup::new(vec![pfile("c", 40).with_range(0, 20)]),
1199            // second half of "c"
1200            FileGroup::new(vec![pfile("c", 40).with_range(20, 40)]),
1201        ]);
1202        assert_partitioned_files(expected, actual);
1203    }
1204
1205    /// Asserts that the two groups of [`PartitionedFile`] are the same
1206    /// (PartitionedFile doesn't implement PartialEq)
1207    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    /// returns a partitioned file with the specified path and size
1224    fn pfile(path: impl Into<String>, file_size: u64) -> PartitionedFile {
1225        PartitionedFile::new(path, file_size)
1226    }
1227
1228    /// Creates a file with partition value with a static size of 10.
1229    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    /// repartition the file groups both with and without preserving order
1236    /// asserting they return the same value and returns that value
1237    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        // Edge cases: empty and zero target
1254        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        // File a and b have partition value p1.
1265        // File c has partition value p2.
1266        // Grouping by partition value should not redistribute any files since the number of partition
1267        // values <= max_target_partitions.
1268        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        // Each file has a single partition value. The number of partition values > max_target_partitions, so
1282        // they should be round-robin distributed into groups.
1283        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}