Skip to main content

datafusion_datasource/
file_groups.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Logic for managing groups of [`PartitionedFile`]s in DataFusion
6
7use crate::{FileRange, PartitionedFile};
8use arrow::compute::SortOptions;
9use datafusion_common::utils::compare_rows;
10use datafusion_common::{ScalarValue, SplitPoint, Statistics};
11use itertools::Itertools;
12use std::cmp::{Ordering, min};
13use std::collections::{BinaryHeap, HashMap};
14use std::iter::repeat_with;
15use std::mem;
16use std::ops::{Deref, DerefMut, Index, IndexMut};
17use std::sync::Arc;
18
19/// Repartition input files into `target_partitions` partitions, if total file size exceed
20/// `repartition_file_min_size`
21///
22/// This partitions evenly by file byte range, and does not have any knowledge
23/// of how data is laid out in specific files. The specific `FileOpener` are
24/// responsible for the actual partitioning on specific data source type. (e.g.
25/// the `CsvOpener` will read lines overlap with byte range as well as
26/// handle boundaries to ensure all lines will be read exactly once)
27///
28/// # Example
29///
30/// For example, if there are two files `A` and `B` that we wish to read with 4
31/// partitions (with 4 threads) they will be divided as follows:
32///
33/// ```text
34///                                    ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
35///                                      ┌─────────────────┐
36///                                    │ │                 │ │
37///                                      │     File A      │
38///                                    │ │  Range: 0-2MB   │ │
39///                                      │                 │
40///                                    │ └─────────────────┘ │
41///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
42/// ┌─────────────────┐                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
43/// │                 │                  ┌─────────────────┐
44/// │                 │                │ │                 │ │
45/// │                 │                  │     File A      │
46/// │                 │                │ │   Range 2-4MB   │ │
47/// │                 │                  │                 │
48/// │                 │                │ └─────────────────┘ │
49/// │  File A (7MB)   │   ────────▶     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
50/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
51/// │                 │                  ┌─────────────────┐
52/// │                 │                │ │                 │ │
53/// │                 │                  │     File A      │
54/// │                 │                │ │  Range: 4-6MB   │ │
55/// │                 │                  │                 │
56/// │                 │                │ └─────────────────┘ │
57/// └─────────────────┘                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
58/// ┌─────────────────┐                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
59/// │  File B (1MB)   │                  ┌─────────────────┐
60/// │                 │                │ │     File A      │ │
61/// └─────────────────┘                  │  Range: 6-7MB   │
62///                                    │ └─────────────────┘ │
63///                                      ┌─────────────────┐
64///                                    │ │  File B (1MB)   │ │
65///                                      │                 │
66///                                    │ └─────────────────┘ │
67///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
68///
69///                                    If target_partitions = 4,
70///                                      divides into 4 groups
71/// ```
72///
73/// # Maintaining Order
74///
75/// Within each group files are read sequentially. Thus, if the overall order of
76/// tuples must be preserved, multiple files can not be mixed in the same group.
77///
78/// In this case, the code will split the largest files evenly into any
79/// available empty groups, but the overall distribution may not be as even
80/// as if the order did not need to be preserved.
81///
82/// ```text
83///                                   ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
84///                                      ┌─────────────────┐
85///                                    │ │                 │ │
86///                                      │     File A      │
87///                                    │ │  Range: 0-2MB   │ │
88///                                      │                 │
89/// ┌─────────────────┐                │ └─────────────────┘ │
90/// │                 │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
91/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
92/// │                 │                  ┌─────────────────┐
93/// │                 │                │ │                 │ │
94/// │                 │                  │     File A      │
95/// │                 │                │ │   Range 2-4MB   │ │
96/// │  File A (6MB)   │   ────────▶      │                 │
97/// │    (ordered)    │                │ └─────────────────┘ │
98/// │                 │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
99/// │                 │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
100/// │                 │                  ┌─────────────────┐
101/// │                 │                │ │                 │ │
102/// │                 │                  │     File A      │
103/// │                 │                │ │  Range: 4-6MB   │ │
104/// └─────────────────┘                  │                 │
105/// ┌─────────────────┐                │ └─────────────────┘ │
106/// │  File B (1MB)   │                 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
107/// │    (ordered)    │                ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
108/// └─────────────────┘                  ┌─────────────────┐
109///                                    │ │  File B (1MB)   │ │
110///                                      │                 │
111///                                    │ └─────────────────┘ │
112///                                     ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
113///
114///                                    If target_partitions = 4,
115///                                      divides into 4 groups
116/// ```
117#[derive(Debug, Clone, Copy)]
118pub struct FileGroupPartitioner {
119    /// how many partitions should be created
120    target_partitions: usize,
121    /// the minimum size for a file to be repartitioned.
122    repartition_file_min_size: usize,
123    /// if the order when reading the files must be preserved
124    preserve_order_within_groups: bool,
125}
126
127impl Default for FileGroupPartitioner {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133impl FileGroupPartitioner {
134    /// Creates a new [`FileGroupPartitioner`] with default values:
135    /// 1. `target_partitions = 1`
136    /// 2. `repartition_file_min_size = 10MB`
137    /// 3. `preserve_order_within_groups = false`
138    pub fn new() -> Self {
139        Self {
140            target_partitions: 1,
141            repartition_file_min_size: 10 * 1024 * 1024,
142            preserve_order_within_groups: false,
143        }
144    }
145
146    /// Set the target partitions
147    pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
148        self.target_partitions = target_partitions;
149        self
150    }
151
152    /// Set the minimum size at which to repartition a file
153    pub fn with_repartition_file_min_size(
154        mut self,
155        repartition_file_min_size: usize,
156    ) -> Self {
157        self.repartition_file_min_size = repartition_file_min_size;
158        self
159    }
160
161    /// Set whether the order of tuples within a file must be preserved
162    pub fn with_preserve_order_within_groups(
163        mut self,
164        preserve_order_within_groups: bool,
165    ) -> Self {
166        self.preserve_order_within_groups = preserve_order_within_groups;
167        self
168    }
169
170    /// Repartition input files according to the settings on this [`FileGroupPartitioner`].
171    ///
172    /// If no repartitioning is needed or possible, return `None`.
173    pub fn repartition_file_groups(
174        &self,
175        file_groups: &[FileGroup],
176    ) -> Option<Vec<FileGroup>> {
177        if file_groups.is_empty() {
178            return None;
179        }
180
181        //  special case when order must be preserved
182        if self.preserve_order_within_groups {
183            self.repartition_preserving_order(file_groups)
184        } else {
185            self.repartition_evenly_by_size(file_groups)
186        }
187    }
188
189    /// Evenly repartition files across partitions by size, ignoring any
190    /// existing grouping / ordering
191    fn repartition_evenly_by_size(
192        &self,
193        file_groups: &[FileGroup],
194    ) -> Option<Vec<FileGroup>> {
195        let target_partitions = self.target_partitions;
196        let repartition_file_min_size = self.repartition_file_min_size;
197        let flattened_files = file_groups.iter().flat_map(FileGroup::iter).collect_vec();
198
199        let total_size = flattened_files
200            .iter()
201            .map(|f| f.effective_size())
202            .sum::<u64>();
203        if total_size < (repartition_file_min_size as u64) || total_size == 0 {
204            return None;
205        }
206
207        let target_partition_size = total_size.div_ceil(target_partitions as u64);
208
209        let current_partition_index: usize = 0;
210        let current_partition_size: u64 = 0;
211
212        // Partition byte range evenly for all `PartitionedFile`s
213        let repartitioned_files = flattened_files
214            .into_iter()
215            .scan(
216                (current_partition_index, current_partition_size),
217                |(current_partition_index, current_partition_size), source_file| {
218                    let mut produced_files = vec![];
219                    let (mut range_start, file_end) = source_file.range();
220                    while range_start < file_end {
221                        let range_end = min(
222                            range_start
223                                + (target_partition_size - *current_partition_size),
224                            file_end,
225                        );
226
227                        let mut produced_file = source_file.clone();
228                        produced_file.range = Some(FileRange {
229                            start: range_start as i64,
230                            end: range_end as i64,
231                        });
232                        produced_files.push((*current_partition_index, produced_file));
233
234                        if *current_partition_size + (range_end - range_start)
235                            >= target_partition_size
236                        {
237                            *current_partition_index += 1;
238                            *current_partition_size = 0;
239                        } else {
240                            *current_partition_size += range_end - range_start;
241                        }
242                        range_start = range_end;
243                    }
244                    Some(produced_files)
245                },
246            )
247            .flatten()
248            .chunk_by(|(partition_idx, _)| *partition_idx)
249            .into_iter()
250            .map(|(_, group)| FileGroup::new(group.map(|(_, vals)| vals).collect_vec()))
251            .collect_vec();
252
253        Some(repartitioned_files)
254    }
255
256    /// Redistribute file groups across size preserving order
257    fn repartition_preserving_order(
258        &self,
259        file_groups: &[FileGroup],
260    ) -> Option<Vec<FileGroup>> {
261        // Can't repartition and preserve order if there are more groups
262        // than partitions
263        if file_groups.len() >= self.target_partitions {
264            return None;
265        }
266        let num_new_groups = self.target_partitions - file_groups.len();
267
268        // If there is only a single file
269        if file_groups.len() == 1 && file_groups[0].len() == 1 {
270            return self.repartition_evenly_by_size(file_groups);
271        }
272
273        // Find which files could be split (single file groups)
274        let mut heap: BinaryHeap<_> = file_groups
275            .iter()
276            .enumerate()
277            .filter_map(|(group_index, group)| {
278                // ignore groups that do not have exactly 1 file
279                if group.len() == 1 {
280                    Some(ToRepartition {
281                        source_index: group_index,
282                        file_size: group[0].effective_size(),
283                        new_groups: vec![group_index],
284                    })
285                } else {
286                    None
287                }
288            })
289            .map(CompareByRangeSize)
290            .collect();
291
292        // No files can be redistributed
293        if heap.is_empty() {
294            return None;
295        }
296
297        // Add new empty groups to which we will redistribute ranges of existing files
298        // Add new empty groups to which we will redistribute ranges of existing files
299        let mut file_groups: Vec<_> = file_groups
300            .iter()
301            .cloned()
302            .chain(repeat_with(|| FileGroup::new(Vec::new())).take(num_new_groups))
303            .collect();
304
305        // Divide up empty groups
306        for (group_index, group) in file_groups.iter().enumerate() {
307            if !group.is_empty() {
308                continue;
309            }
310            // Pick the file that has the largest ranges to read so far
311            let mut largest_group = heap.pop().unwrap();
312            largest_group.new_groups.push(group_index);
313            heap.push(largest_group);
314        }
315
316        // Distribute files to their newly assigned groups
317        while let Some(to_repartition) = heap.pop() {
318            let range_size = to_repartition.range_size();
319            let ToRepartition {
320                source_index,
321                file_size: _,
322                new_groups,
323            } = to_repartition.into_inner();
324            assert_eq!(file_groups[source_index].len(), 1);
325            let original_file = file_groups[source_index].pop().unwrap();
326
327            let last_group = new_groups.len() - 1;
328            let (mut range_start, file_end) = original_file.range();
329            let mut range_end = range_start + range_size;
330            for (i, group_index) in new_groups.into_iter().enumerate() {
331                let target_group = &mut file_groups[group_index];
332                assert!(target_group.is_empty());
333
334                // adjust last range to include the entire file
335                if i == last_group {
336                    range_end = file_end;
337                }
338                target_group.push(
339                    original_file
340                        .clone()
341                        .with_range(range_start as i64, range_end as i64),
342                );
343                range_start = range_end;
344                range_end += range_size;
345            }
346        }
347
348        Some(file_groups)
349    }
350}
351
352/// Represents a group of partitioned files that'll be processed by a single thread.
353/// Maintains optional statistics across all files in the group.
354///
355/// # Statistics
356///
357/// The group-level [`FileGroup::file_statistics`] field contains merged statistics from all files
358/// in the group for the **full table schema** (file columns + partition columns).
359///
360/// Partition column statistics are derived from the individual file partition values:
361/// - `min` = minimum partition value across all files in the group, or absent if any
362///   file in the group has a null partition value (see #26748)
363/// - `max` = maximum partition value across all files in the group, or absent if any
364///   file in the group has a null partition value
365/// - `null_count` = the number of rows in files with a null partition value
366///
367/// This allows query optimizers to prune entire file groups based on partition bounds.
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    ///
374    /// These statistics cover the full table schema: file columns plus partition columns.
375    /// Partition column statistics are merged from individual [`PartitionedFile::statistics`],
376    /// which compute exact values from [`PartitionedFile::partition_values`].
377    statistics: Option<Arc<Statistics>>,
378}
379
380impl FileGroup {
381    /// Creates a new FileGroup from a vector of PartitionedFile objects
382    pub fn new(files: Vec<PartitionedFile>) -> Self {
383        Self {
384            files,
385            statistics: None,
386        }
387    }
388
389    /// Returns the number of files in this group
390    pub fn len(&self) -> usize {
391        self.files.len()
392    }
393
394    /// Set the statistics for this group
395    pub fn with_statistics(mut self, statistics: Arc<Statistics>) -> Self {
396        self.statistics = Some(statistics);
397        self
398    }
399
400    /// Returns a slice of the files in this group
401    pub fn files(&self) -> &[PartitionedFile] {
402        &self.files
403    }
404
405    pub fn iter(&self) -> impl Iterator<Item = &PartitionedFile> {
406        self.files.iter()
407    }
408
409    pub fn into_inner(self) -> Vec<PartitionedFile> {
410        self.files
411    }
412
413    pub fn is_empty(&self) -> bool {
414        self.files.is_empty()
415    }
416
417    /// Removes the last element from the files vector and returns it, or None if empty
418    pub fn pop(&mut self) -> Option<PartitionedFile> {
419        self.files.pop()
420    }
421
422    /// Adds a file to the group
423    pub fn push(&mut self, partitioned_file: PartitionedFile) {
424        self.files.push(partitioned_file);
425    }
426
427    /// Get the specific file statistics for the given index
428    /// If the index is None, return the `FileGroup` statistics
429    pub fn file_statistics(&self, index: Option<usize>) -> Option<&Statistics> {
430        if let Some(index) = index {
431            self.files.get(index).and_then(|f| f.statistics.as_deref())
432        } else {
433            self.statistics.as_deref()
434        }
435    }
436
437    /// Get the mutable reference to the statistics for this group
438    pub fn statistics_mut(&mut self) -> Option<&mut Statistics> {
439        self.statistics.as_mut().map(Arc::make_mut)
440    }
441
442    /// Partition the list of files into `n` groups
443    pub fn split_files(mut self, n: usize) -> Vec<FileGroup> {
444        if self.is_empty() {
445            return vec![];
446        }
447
448        // ObjectStore::list does not guarantee any consistent order and for some
449        // implementations such as LocalFileSystem, it may be inconsistent. Thus
450        // Sort files by path to ensure consistent plans when run more than once.
451        self.files.sort_by(|a, b| a.path().cmp(b.path()));
452
453        // effectively this is div with rounding up instead of truncating
454        let chunk_size = self.len().div_ceil(n);
455        let mut chunks = Vec::with_capacity(n);
456        let mut current_chunk = Vec::with_capacity(chunk_size);
457        for file in self.files.drain(..) {
458            current_chunk.push(file);
459            if current_chunk.len() == chunk_size {
460                let full_chunk = FileGroup::new(mem::replace(
461                    &mut current_chunk,
462                    Vec::with_capacity(chunk_size),
463                ));
464                chunks.push(full_chunk);
465            }
466        }
467
468        if !current_chunk.is_empty() {
469            chunks.push(FileGroup::new(current_chunk))
470        }
471
472        chunks
473    }
474
475    /// Groups files by their partition values, ensuring all files with same
476    /// partition values are in the same group.
477    ///
478    /// Note: May return fewer groups than `max_target_partitions` when the
479    /// number of unique partition values is less than the target.
480    ///
481    /// Wrapper around [`Self::group_by_partition_values_with_split_points`] that discards
482    /// the split points.
483    pub fn group_by_partition_values(
484        self,
485        max_target_partitions: usize,
486    ) -> Vec<FileGroup> {
487        self.group_by_partition_values_with_split_points(max_target_partitions)
488            .0
489    }
490
491    /// Groups files by partition value and returns the [`SplitPoint`]s between groups.
492    ///
493    /// Values are sorted with [`SortOptions::default()`] and cut into at most
494    /// `max_target_partitions` contiguous chunks so routing a file's `partition_values`
495    /// through the split points yields the group it was placed in.
496    #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
497    pub fn group_by_partition_values_with_split_points(
498        self,
499        max_target_partitions: usize,
500    ) -> (Vec<FileGroup>, Vec<SplitPoint>) {
501        if self.is_empty() || max_target_partitions == 0 {
502            return (vec![], vec![]);
503        }
504
505        let mut partition_groups: HashMap<Vec<ScalarValue>, Vec<PartitionedFile>> =
506            HashMap::new();
507
508        for file in self.files {
509            partition_groups
510                .entry(file.partition_values.clone())
511                .or_default()
512                .push(file);
513        }
514
515        let num_unique_partitions = partition_groups.len();
516
517        // Sort for deterministic bucket assignment across query executions. Must match
518        // the ordering the caller declares, otherwise the split points would not
519        // describe the groups.
520        let mut sorted_partitions: Vec<_> = partition_groups.into_iter().collect();
521        let sort_options =
522            vec![
523                SortOptions::default();
524                sorted_partitions.first().map(|(k, _)| k.len()).unwrap_or(0)
525            ];
526        sorted_partitions.sort_by(|a, b| {
527            compare_rows(&a.0, &b.0, &sort_options).unwrap_or(Ordering::Equal)
528        });
529
530        let bucket_count = min(num_unique_partitions, max_target_partitions);
531        let mut groups = Vec::with_capacity(bucket_count);
532        let mut split_points = Vec::with_capacity(bucket_count.saturating_sub(1));
533
534        // Every chunk is non-empty because `bucket_count <= num_unique_partitions`, so
535        // its first tuple is a well defined lower bound.
536        let mut iter = sorted_partitions.into_iter();
537        for bucket in 0..bucket_count {
538            let start = bucket * num_unique_partitions / bucket_count;
539            let end = (bucket + 1) * num_unique_partitions / bucket_count;
540            let mut files = Vec::new();
541            for offset in start..end {
542                let (values, group_files) = iter
543                    .next()
544                    .expect("contiguous chunking never runs past the sorted partitions");
545                if offset == start && bucket > 0 {
546                    split_points.push(SplitPoint::new(values));
547                }
548                files.extend(group_files);
549            }
550            groups.push(FileGroup::new(files));
551        }
552        debug_assert_eq!(split_points.len() + 1, groups.len());
553
554        (groups, split_points)
555    }
556}
557
558impl Index<usize> for FileGroup {
559    type Output = PartitionedFile;
560
561    fn index(&self, index: usize) -> &Self::Output {
562        &self.files[index]
563    }
564}
565
566impl IndexMut<usize> for FileGroup {
567    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
568        &mut self.files[index]
569    }
570}
571
572impl FromIterator<PartitionedFile> for FileGroup {
573    fn from_iter<I: IntoIterator<Item = PartitionedFile>>(iter: I) -> Self {
574        let files = iter.into_iter().collect();
575        FileGroup::new(files)
576    }
577}
578
579impl From<Vec<PartitionedFile>> for FileGroup {
580    fn from(files: Vec<PartitionedFile>) -> Self {
581        FileGroup::new(files)
582    }
583}
584
585impl Default for FileGroup {
586    fn default() -> Self {
587        Self::new(Vec::new())
588    }
589}
590
591/// Tracks how a individual file will be repartitioned
592#[derive(Debug, Clone)]
593struct ToRepartition {
594    /// the index from which the original file will be taken
595    source_index: usize,
596    /// the size of the original file
597    file_size: u64,
598    /// indexes of which group(s) will this be distributed to (including `source_index`)
599    new_groups: Vec<usize>,
600}
601
602impl ToRepartition {
603    /// How big will each file range be when this file is read in its new groups?
604    fn range_size(&self) -> u64 {
605        self.file_size / (self.new_groups.len() as u64)
606    }
607}
608
609struct CompareByRangeSize(ToRepartition);
610impl CompareByRangeSize {
611    fn into_inner(self) -> ToRepartition {
612        self.0
613    }
614}
615impl Ord for CompareByRangeSize {
616    fn cmp(&self, other: &Self) -> Ordering {
617        self.0.range_size().cmp(&other.0.range_size())
618    }
619}
620impl PartialOrd for CompareByRangeSize {
621    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
622        Some(self.cmp(other))
623    }
624}
625impl PartialEq for CompareByRangeSize {
626    fn eq(&self, other: &Self) -> bool {
627        // PartialEq must be consistent with PartialOrd
628        self.cmp(other) == Ordering::Equal
629    }
630}
631impl Eq for CompareByRangeSize {}
632impl Deref for CompareByRangeSize {
633    type Target = ToRepartition;
634    fn deref(&self) -> &Self::Target {
635        &self.0
636    }
637}
638impl DerefMut for CompareByRangeSize {
639    fn deref_mut(&mut self) -> &mut Self::Target {
640        &mut self.0
641    }
642}
643
644#[cfg(test)]
645mod test {
646    use super::*;
647    use datafusion_physical_expr::RangePartitioning;
648    use datafusion_physical_expr::expressions::Column;
649    use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
650
651    /// Empty file won't get partitioned
652    #[test]
653    fn repartition_empty_file_only() {
654        let partitioned_file_empty = pfile("empty", 0);
655        let file_group = vec![FileGroup::new(vec![partitioned_file_empty])];
656
657        let partitioned_files = FileGroupPartitioner::new()
658            .with_target_partitions(4)
659            .with_repartition_file_min_size(0)
660            .repartition_file_groups(&file_group);
661
662        assert_partitioned_files(None, partitioned_files);
663    }
664
665    /// Repartition when there is a empty file in file groups
666    #[test]
667    fn repartition_empty_files() {
668        let pfile_a = pfile("a", 10);
669        let pfile_b = pfile("b", 10);
670        let pfile_empty = pfile("empty", 0);
671
672        let empty_first = vec![
673            FileGroup::new(vec![pfile_empty.clone()]),
674            FileGroup::new(vec![pfile_a.clone()]),
675            FileGroup::new(vec![pfile_b.clone()]),
676        ];
677        let empty_middle = vec![
678            FileGroup::new(vec![pfile_a.clone()]),
679            FileGroup::new(vec![pfile_empty.clone()]),
680            FileGroup::new(vec![pfile_b.clone()]),
681        ];
682        let empty_last = vec![
683            FileGroup::new(vec![pfile_a]),
684            FileGroup::new(vec![pfile_b]),
685            FileGroup::new(vec![pfile_empty]),
686        ];
687
688        // Repartition file groups into x partitions
689        let expected_2 = vec![
690            FileGroup::new(vec![pfile("a", 10).with_range(0, 10)]),
691            FileGroup::new(vec![pfile("b", 10).with_range(0, 10)]),
692        ];
693        let expected_3 = vec![
694            FileGroup::new(vec![pfile("a", 10).with_range(0, 7)]),
695            FileGroup::new(vec![
696                pfile("a", 10).with_range(7, 10),
697                pfile("b", 10).with_range(0, 4),
698            ]),
699            FileGroup::new(vec![pfile("b", 10).with_range(4, 10)]),
700        ];
701
702        let file_groups_tests = [empty_first, empty_middle, empty_last];
703
704        for fg in file_groups_tests {
705            let all_expected = [(2, expected_2.clone()), (3, expected_3.clone())];
706            for (n_partition, expected) in all_expected {
707                let actual = FileGroupPartitioner::new()
708                    .with_target_partitions(n_partition)
709                    .with_repartition_file_min_size(10)
710                    .repartition_file_groups(&fg);
711
712                assert_partitioned_files(Some(expected), actual);
713            }
714        }
715    }
716
717    #[test]
718    fn repartition_single_file() {
719        // Single file, single partition into multiple partitions
720        let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
721
722        let actual = FileGroupPartitioner::new()
723            .with_target_partitions(4)
724            .with_repartition_file_min_size(10)
725            .repartition_file_groups(&single_partition);
726
727        let expected = Some(vec![
728            FileGroup::new(vec![pfile("a", 123).with_range(0, 31)]),
729            FileGroup::new(vec![pfile("a", 123).with_range(31, 62)]),
730            FileGroup::new(vec![pfile("a", 123).with_range(62, 93)]),
731            FileGroup::new(vec![pfile("a", 123).with_range(93, 123)]),
732        ]);
733        assert_partitioned_files(expected, actual);
734    }
735
736    #[test]
737    fn repartition_single_file_with_range() {
738        // Single file, single partition into multiple partitions
739        let single_partition =
740            vec![FileGroup::new(vec![pfile("a", 123).with_range(0, 123)])];
741
742        let actual = FileGroupPartitioner::new()
743            .with_target_partitions(4)
744            .with_repartition_file_min_size(10)
745            .repartition_file_groups(&single_partition);
746
747        let expected = Some(vec![
748            FileGroup::new(vec![pfile("a", 123).with_range(0, 31)]),
749            FileGroup::new(vec![pfile("a", 123).with_range(31, 62)]),
750            FileGroup::new(vec![pfile("a", 123).with_range(62, 93)]),
751            FileGroup::new(vec![pfile("a", 123).with_range(93, 123)]),
752        ]);
753        assert_partitioned_files(expected, actual);
754    }
755
756    #[test]
757    fn repartition_single_file_with_incomplete_range() {
758        // Single file, single partition into multiple partitions
759        let single_partition =
760            vec![FileGroup::new(vec![pfile("a", 123).with_range(10, 100)])];
761
762        let actual = FileGroupPartitioner::new()
763            .with_target_partitions(4)
764            .with_repartition_file_min_size(10)
765            .repartition_file_groups(&single_partition);
766
767        let expected = Some(vec![
768            FileGroup::new(vec![pfile("a", 123).with_range(10, 33)]),
769            FileGroup::new(vec![pfile("a", 123).with_range(33, 56)]),
770            FileGroup::new(vec![pfile("a", 123).with_range(56, 79)]),
771            FileGroup::new(vec![pfile("a", 123).with_range(79, 100)]),
772        ]);
773        assert_partitioned_files(expected, actual);
774    }
775
776    #[test]
777    fn repartition_single_file_duplicated_with_range() {
778        // Single file, two partitions into multiple partitions
779        let single_partition = vec![FileGroup::new(vec![
780            pfile("a", 100).with_range(0, 50),
781            pfile("a", 100).with_range(50, 100),
782        ])];
783
784        let actual = FileGroupPartitioner::new()
785            .with_target_partitions(4)
786            .with_repartition_file_min_size(10)
787            .repartition_file_groups(&single_partition);
788
789        let expected = Some(vec![
790            FileGroup::new(vec![pfile("a", 100).with_range(0, 25)]),
791            FileGroup::new(vec![pfile("a", 100).with_range(25, 50)]),
792            FileGroup::new(vec![pfile("a", 100).with_range(50, 75)]),
793            FileGroup::new(vec![pfile("a", 100).with_range(75, 100)]),
794        ]);
795        assert_partitioned_files(expected, actual);
796    }
797
798    #[test]
799    fn repartition_too_much_partitions() {
800        // Single file, single partition into 96 partitions
801        let partitioned_file = pfile("a", 8);
802        let single_partition = vec![FileGroup::new(vec![partitioned_file])];
803
804        let actual = FileGroupPartitioner::new()
805            .with_target_partitions(96)
806            .with_repartition_file_min_size(5)
807            .repartition_file_groups(&single_partition);
808
809        let expected = Some(vec![
810            FileGroup::new(vec![pfile("a", 8).with_range(0, 1)]),
811            FileGroup::new(vec![pfile("a", 8).with_range(1, 2)]),
812            FileGroup::new(vec![pfile("a", 8).with_range(2, 3)]),
813            FileGroup::new(vec![pfile("a", 8).with_range(3, 4)]),
814            FileGroup::new(vec![pfile("a", 8).with_range(4, 5)]),
815            FileGroup::new(vec![pfile("a", 8).with_range(5, 6)]),
816            FileGroup::new(vec![pfile("a", 8).with_range(6, 7)]),
817            FileGroup::new(vec![pfile("a", 8).with_range(7, 8)]),
818        ]);
819
820        assert_partitioned_files(expected, actual);
821    }
822
823    #[test]
824    fn repartition_multiple_partitions() {
825        // Multiple files in single partition after redistribution
826        let source_partitions = vec![
827            FileGroup::new(vec![pfile("a", 40)]),
828            FileGroup::new(vec![pfile("b", 60)]),
829        ];
830
831        let actual = FileGroupPartitioner::new()
832            .with_target_partitions(3)
833            .with_repartition_file_min_size(10)
834            .repartition_file_groups(&source_partitions);
835
836        let expected = Some(vec![
837            FileGroup::new(vec![pfile("a", 40).with_range(0, 34)]),
838            FileGroup::new(vec![
839                pfile("a", 40).with_range(34, 40),
840                pfile("b", 60).with_range(0, 28),
841            ]),
842            FileGroup::new(vec![pfile("b", 60).with_range(28, 60)]),
843        ]);
844        assert_partitioned_files(expected, actual);
845    }
846
847    #[test]
848    fn repartition_same_num_partitions() {
849        // "Rebalance" files across partitions
850        let source_partitions = vec![
851            FileGroup::new(vec![pfile("a", 40)]),
852            FileGroup::new(vec![pfile("b", 60)]),
853        ];
854
855        let actual = FileGroupPartitioner::new()
856            .with_target_partitions(2)
857            .with_repartition_file_min_size(10)
858            .repartition_file_groups(&source_partitions);
859
860        let expected = Some(vec![
861            FileGroup::new(vec![
862                pfile("a", 40).with_range(0, 40),
863                pfile("b", 60).with_range(0, 10),
864            ]),
865            FileGroup::new(vec![pfile("b", 60).with_range(10, 60)]),
866        ]);
867        assert_partitioned_files(expected, actual);
868    }
869
870    #[test]
871    fn repartition_no_action_min_size() {
872        // No action due to target_partition_size
873        let single_partition = vec![FileGroup::new(vec![pfile("a", 123)])];
874
875        let actual = FileGroupPartitioner::new()
876            .with_target_partitions(65)
877            .with_repartition_file_min_size(500)
878            .repartition_file_groups(&single_partition);
879
880        assert_partitioned_files(None, actual)
881    }
882
883    #[test]
884    fn repartition_no_action_zero_files() {
885        // No action due to no files
886        let empty_partition = vec![];
887
888        let partitioner = FileGroupPartitioner::new()
889            .with_target_partitions(65)
890            .with_repartition_file_min_size(500);
891
892        assert_partitioned_files(None, repartition_test(partitioner, empty_partition))
893    }
894
895    #[test]
896    fn repartition_ordered_no_action_too_few_partitions() {
897        // No action as there are no new groups to redistribute to
898        let input_partitions = vec![
899            FileGroup::new(vec![pfile("a", 100)]),
900            FileGroup::new(vec![pfile("b", 200)]),
901        ];
902
903        let actual = FileGroupPartitioner::new()
904            .with_preserve_order_within_groups(true)
905            .with_target_partitions(2)
906            .with_repartition_file_min_size(10)
907            .repartition_file_groups(&input_partitions);
908
909        assert_partitioned_files(None, actual)
910    }
911
912    #[test]
913    fn repartition_ordered_no_action_file_too_small() {
914        // No action as there are no new groups to redistribute to
915        let single_partition = vec![FileGroup::new(vec![pfile("a", 100)])];
916
917        let actual = FileGroupPartitioner::new()
918            .with_preserve_order_within_groups(true)
919            .with_target_partitions(2)
920            // file is too small to repartition
921            .with_repartition_file_min_size(1000)
922            .repartition_file_groups(&single_partition);
923
924        assert_partitioned_files(None, actual)
925    }
926
927    #[test]
928    fn repartition_ordered_one_large_file() {
929        // "Rebalance" the single large file across partitions
930        let source_partitions = vec![FileGroup::new(vec![pfile("a", 100)])];
931
932        let actual = FileGroupPartitioner::new()
933            .with_preserve_order_within_groups(true)
934            .with_target_partitions(3)
935            .with_repartition_file_min_size(10)
936            .repartition_file_groups(&source_partitions);
937
938        let expected = Some(vec![
939            FileGroup::new(vec![pfile("a", 100).with_range(0, 34)]),
940            FileGroup::new(vec![pfile("a", 100).with_range(34, 68)]),
941            FileGroup::new(vec![pfile("a", 100).with_range(68, 100)]),
942        ]);
943        assert_partitioned_files(expected, actual);
944    }
945
946    #[test]
947    fn repartition_ordered_one_large_file_with_range() {
948        // "Rebalance" the single large file across partitions
949        let source_partitions =
950            vec![FileGroup::new(vec![pfile("a", 100).with_range(0, 100)])];
951
952        let actual = FileGroupPartitioner::new()
953            .with_preserve_order_within_groups(true)
954            .with_target_partitions(3)
955            .with_repartition_file_min_size(10)
956            .repartition_file_groups(&source_partitions);
957
958        let expected = Some(vec![
959            FileGroup::new(vec![pfile("a", 100).with_range(0, 34)]),
960            FileGroup::new(vec![pfile("a", 100).with_range(34, 68)]),
961            FileGroup::new(vec![pfile("a", 100).with_range(68, 100)]),
962        ]);
963        assert_partitioned_files(expected, actual);
964    }
965
966    #[test]
967    fn repartition_ordered_one_large_one_small_file() {
968        // "Rebalance" the single large file across empty partitions, but can't split
969        // small file
970        let source_partitions = vec![
971            FileGroup::new(vec![pfile("a", 100)]),
972            FileGroup::new(vec![pfile("b", 30)]),
973        ];
974
975        let actual = FileGroupPartitioner::new()
976            .with_preserve_order_within_groups(true)
977            .with_target_partitions(4)
978            .with_repartition_file_min_size(10)
979            .repartition_file_groups(&source_partitions);
980
981        let expected = Some(vec![
982            // scan first third of "a"
983            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
984            // only b in this group (can't do this)
985            FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
986            // second third of "a"
987            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
988            // final third of "a"
989            FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
990        ]);
991        assert_partitioned_files(expected, actual);
992    }
993
994    #[test]
995    fn repartition_ordered_one_large_one_small_file_with_full_range() {
996        // "Rebalance" the single large file across empty partitions, but can't split
997        // small file
998        let source_partitions = vec![
999            FileGroup::new(vec![pfile("a", 100).with_range(0, 100)]),
1000            FileGroup::new(vec![pfile("b", 30)]),
1001        ];
1002
1003        let actual = FileGroupPartitioner::new()
1004            .with_preserve_order_within_groups(true)
1005            .with_target_partitions(4)
1006            .with_repartition_file_min_size(10)
1007            .repartition_file_groups(&source_partitions);
1008
1009        let expected = Some(vec![
1010            // scan first third of "a"
1011            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1012            // only b in this group (can't do this)
1013            FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1014            // second third of "a"
1015            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1016            // final third of "a"
1017            FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
1018        ]);
1019        assert_partitioned_files(expected, actual);
1020    }
1021
1022    #[test]
1023    fn repartition_ordered_one_large_one_small_file_with_split_range() {
1024        // "Rebalance" the single large file across empty partitions, but can't split
1025        // small file
1026        let source_partitions = vec![
1027            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1028            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1029            FileGroup::new(vec![pfile("b", 30)]),
1030        ];
1031
1032        let actual = FileGroupPartitioner::new()
1033            .with_preserve_order_within_groups(true)
1034            .with_target_partitions(4)
1035            .with_repartition_file_min_size(10)
1036            .repartition_file_groups(&source_partitions);
1037
1038        let expected = Some(vec![
1039            // scan first half of first "a"
1040            FileGroup::new(vec![pfile("a", 100).with_range(0, 25)]),
1041            // second "a" fully (not split)
1042            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1043            // only b in this group (can't do this)
1044            FileGroup::new(vec![pfile("b", 30).with_range(0, 30)]),
1045            // second half of first "a"
1046            FileGroup::new(vec![pfile("a", 100).with_range(25, 50)]),
1047        ]);
1048        assert_partitioned_files(expected, actual);
1049    }
1050
1051    #[test]
1052    fn repartition_ordered_one_large_one_small_file_with_non_full_range() {
1053        // "Rebalance" the single large file across empty partitions, but can't split
1054        // small file
1055        let source_partitions = vec![
1056            FileGroup::new(vec![pfile("a", 100).with_range(20, 80)]),
1057            FileGroup::new(vec![pfile("b", 30).with_range(5, 25)]),
1058        ];
1059
1060        let actual = FileGroupPartitioner::new()
1061            .with_preserve_order_within_groups(true)
1062            .with_target_partitions(4)
1063            .with_repartition_file_min_size(10)
1064            .repartition_file_groups(&source_partitions);
1065
1066        let expected = Some(vec![
1067            // scan first third of "a"
1068            FileGroup::new(vec![pfile("a", 100).with_range(20, 40)]),
1069            // only b in this group (can't split this)
1070            FileGroup::new(vec![pfile("b", 30).with_range(5, 25)]),
1071            // second third of "a"
1072            FileGroup::new(vec![pfile("a", 100).with_range(40, 60)]),
1073            // final third of "a"
1074            FileGroup::new(vec![pfile("a", 100).with_range(60, 80)]),
1075        ]);
1076        assert_partitioned_files(expected, actual);
1077    }
1078
1079    #[test]
1080    fn repartition_ordered_two_large_files() {
1081        // "Rebalance" two large files across empty partitions, but can't mix them
1082        let source_partitions = vec![
1083            FileGroup::new(vec![pfile("a", 100)]),
1084            FileGroup::new(vec![pfile("b", 100)]),
1085        ];
1086
1087        let actual = FileGroupPartitioner::new()
1088            .with_preserve_order_within_groups(true)
1089            .with_target_partitions(4)
1090            .with_repartition_file_min_size(10)
1091            .repartition_file_groups(&source_partitions);
1092
1093        let expected = Some(vec![
1094            // scan first half of "a"
1095            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1096            // scan first half of "b"
1097            FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1098            // second half of "a"
1099            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1100            // second half of "b"
1101            FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
1102        ]);
1103        assert_partitioned_files(expected, actual);
1104    }
1105
1106    #[test]
1107    fn repartition_ordered_two_large_one_small_files() {
1108        // "Rebalance" two large files and one small file across empty partitions
1109        let source_partitions = vec![
1110            FileGroup::new(vec![pfile("a", 100)]),
1111            FileGroup::new(vec![pfile("b", 100)]),
1112            FileGroup::new(vec![pfile("c", 30)]),
1113        ];
1114
1115        let partitioner = FileGroupPartitioner::new()
1116            .with_preserve_order_within_groups(true)
1117            .with_repartition_file_min_size(10);
1118
1119        // with 4 partitions, can only split the first large file "a"
1120        let actual = partitioner
1121            .with_target_partitions(4)
1122            .repartition_file_groups(&source_partitions);
1123
1124        let expected = Some(vec![
1125            // scan first half of "a"
1126            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1127            // All of "b"
1128            FileGroup::new(vec![pfile("b", 100).with_range(0, 100)]),
1129            // All of "c"
1130            FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1131            // second half of "a"
1132            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1133        ]);
1134        assert_partitioned_files(expected, actual);
1135
1136        // With 5 partitions, we can split both "a" and "b", but they can't be intermixed
1137        let actual = partitioner
1138            .with_target_partitions(5)
1139            .repartition_file_groups(&source_partitions);
1140
1141        let expected = Some(vec![
1142            // scan first half of "a"
1143            FileGroup::new(vec![pfile("a", 100).with_range(0, 50)]),
1144            // scan first half of "b"
1145            FileGroup::new(vec![pfile("b", 100).with_range(0, 50)]),
1146            // All of "c"
1147            FileGroup::new(vec![pfile("c", 30).with_range(0, 30)]),
1148            // second half of "a"
1149            FileGroup::new(vec![pfile("a", 100).with_range(50, 100)]),
1150            // second half of "b"
1151            FileGroup::new(vec![pfile("b", 100).with_range(50, 100)]),
1152        ]);
1153        assert_partitioned_files(expected, actual);
1154    }
1155
1156    #[test]
1157    fn repartition_ordered_one_large_one_small_existing_empty() {
1158        // "Rebalance" files using existing empty partition
1159        let source_partitions = vec![
1160            FileGroup::new(vec![pfile("a", 100)]),
1161            FileGroup::default(),
1162            FileGroup::new(vec![pfile("b", 40)]),
1163            FileGroup::default(),
1164        ];
1165
1166        let actual = FileGroupPartitioner::new()
1167            .with_preserve_order_within_groups(true)
1168            .with_target_partitions(5)
1169            .with_repartition_file_min_size(10)
1170            .repartition_file_groups(&source_partitions);
1171
1172        // Of the three available groups (2 original empty and 1 new from the
1173        // target partitions), assign two to "a" and one to "b"
1174        let expected = Some(vec![
1175            // Scan of "a" across three groups
1176            FileGroup::new(vec![pfile("a", 100).with_range(0, 33)]),
1177            FileGroup::new(vec![pfile("a", 100).with_range(33, 66)]),
1178            // scan first half of "b"
1179            FileGroup::new(vec![pfile("b", 40).with_range(0, 20)]),
1180            // final third of "a"
1181            FileGroup::new(vec![pfile("a", 100).with_range(66, 100)]),
1182            // second half of "b"
1183            FileGroup::new(vec![pfile("b", 40).with_range(20, 40)]),
1184        ]);
1185        assert_partitioned_files(expected, actual);
1186    }
1187    #[test]
1188    fn repartition_ordered_existing_group_multiple_files() {
1189        // groups with multiple files in a group can not be changed, but can divide others
1190        let source_partitions = vec![
1191            // two files in an existing partition
1192            FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
1193            FileGroup::new(vec![pfile("c", 40)]),
1194        ];
1195
1196        let actual = FileGroupPartitioner::new()
1197            .with_preserve_order_within_groups(true)
1198            .with_target_partitions(3)
1199            .with_repartition_file_min_size(10)
1200            .repartition_file_groups(&source_partitions);
1201
1202        // Of the three available groups (2 original empty and 1 new from the
1203        // target partitions), assign two to "a" and one to "b"
1204        let expected = Some(vec![
1205            // don't try and rearrange files in the existing partition
1206            // assuming that the caller had a good reason to put them that way.
1207            // (it is technically possible to split off ranges from the files if desired)
1208            FileGroup::new(vec![pfile("a", 100), pfile("b", 100)]),
1209            // first half of "c"
1210            FileGroup::new(vec![pfile("c", 40).with_range(0, 20)]),
1211            // second half of "c"
1212            FileGroup::new(vec![pfile("c", 40).with_range(20, 40)]),
1213        ]);
1214        assert_partitioned_files(expected, actual);
1215    }
1216
1217    /// Asserts that the two groups of [`PartitionedFile`] are the same
1218    /// (PartitionedFile doesn't implement PartialEq)
1219    fn assert_partitioned_files(
1220        expected: Option<Vec<FileGroup>>,
1221        actual: Option<Vec<FileGroup>>,
1222    ) {
1223        match (expected, actual) {
1224            (None, None) => {}
1225            (Some(_), None) => panic!("Expected Some, got None"),
1226            (None, Some(_)) => panic!("Expected None, got Some"),
1227            (Some(expected), Some(actual)) => {
1228                let expected_string = format!("{expected:#?}");
1229                let actual_string = format!("{actual:#?}");
1230                assert_eq!(expected_string, actual_string);
1231            }
1232        }
1233    }
1234
1235    /// returns a partitioned file with the specified path and size
1236    fn pfile(path: impl Into<String>, file_size: u64) -> PartitionedFile {
1237        PartitionedFile::new(path, file_size)
1238    }
1239
1240    /// Creates a file with partition value with a static size of 10.
1241    fn pfile_with_pv(path: &str, pv: &str) -> PartitionedFile {
1242        let mut file = pfile(path, 10);
1243        file.partition_values = vec![ScalarValue::from(pv)];
1244        file
1245    }
1246
1247    /// repartition the file groups both with and without preserving order
1248    /// asserting they return the same value and returns that value
1249    fn repartition_test(
1250        partitioner: FileGroupPartitioner,
1251        file_groups: Vec<FileGroup>,
1252    ) -> Option<Vec<FileGroup>> {
1253        let repartitioned = partitioner.repartition_file_groups(&file_groups);
1254
1255        let repartitioned_preserving_sort = partitioner
1256            .with_preserve_order_within_groups(true)
1257            .repartition_file_groups(&file_groups);
1258
1259        assert_partitioned_files(repartitioned.clone(), repartitioned_preserving_sort);
1260        repartitioned
1261    }
1262
1263    #[test]
1264    fn test_group_by_partition_values_edge_cases() {
1265        // Edge cases: empty and zero target
1266        assert!(FileGroup::default().group_by_partition_values(4).is_empty());
1267        assert!(
1268            FileGroup::new(vec![pfile("a", 100)])
1269                .group_by_partition_values(0)
1270                .is_empty()
1271        );
1272    }
1273
1274    #[test]
1275    fn test_group_by_partition_values_less_groups_than_target() {
1276        // File a and b have partition value p1.
1277        // File c has partition value p2.
1278        // Grouping by partition value should not redistribute any files since the number of partition
1279        // values <= max_target_partitions.
1280        let fg = FileGroup::new(vec![
1281            pfile_with_pv("a", "p1"),
1282            pfile_with_pv("b", "p1"),
1283            pfile_with_pv("c", "p2"),
1284        ]);
1285        let groups = fg.group_by_partition_values(4);
1286        assert_eq!(groups.len(), 2);
1287        assert_eq!(groups[0].len(), 2);
1288        assert_eq!(groups[1].len(), 1);
1289    }
1290
1291    #[test]
1292    fn test_group_by_partition_values_more_groups_than_target() {
1293        // More values than `max_target_partitions`, so they are cut into contiguous
1294        // chunks whose sizes differ by at most one.
1295        let fg = FileGroup::new(vec![
1296            pfile_with_pv("a", "p1"),
1297            pfile_with_pv("b", "p2"),
1298            pfile_with_pv("c", "p3"),
1299            pfile_with_pv("d", "p4"),
1300            pfile_with_pv("e", "p5"),
1301        ]);
1302        let groups = fg.group_by_partition_values(3);
1303        assert_eq!(groups.len(), 3);
1304        assert_eq!(groups[0].len(), 1);
1305        assert_eq!(groups[1].len(), 2);
1306        assert_eq!(groups[2].len(), 2);
1307        // Groups must be contiguous key intervals in sorted order.
1308        assert_eq!(group_pvs(&groups[0]), vec!["p1"]);
1309        assert_eq!(group_pvs(&groups[1]), vec!["p2", "p3"]);
1310        assert_eq!(group_pvs(&groups[2]), vec!["p4", "p5"]);
1311    }
1312
1313    fn group_pvs(group: &FileGroup) -> Vec<String> {
1314        group
1315            .iter()
1316            .map(|f| f.partition_values[0].to_string())
1317            .collect()
1318    }
1319
1320    /// Mirrors `RangeRouter` semantics: the partition index is the number of split points
1321    /// that are `<=` the key under the given sort options.
1322    fn range_route(key: &[ScalarValue], split_points: &[SplitPoint]) -> usize {
1323        let sort_options = vec![SortOptions::default(); key.len()];
1324        split_points
1325            .iter()
1326            .take_while(|sp| {
1327                compare_rows(sp.values(), key, &sort_options).unwrap()
1328                    != Ordering::Greater
1329            })
1330            .count()
1331    }
1332
1333    #[test]
1334    fn test_group_by_partition_values_split_points_describe_groups() {
1335        let fg = FileGroup::new(vec![
1336            pfile_with_pv("a", "p1"),
1337            pfile_with_pv("b", "p2"),
1338            pfile_with_pv("c", "p3"),
1339            pfile_with_pv("d", "p4"),
1340            pfile_with_pv("e", "p5"),
1341            pfile_with_pv("f", "p5"),
1342        ]);
1343        let (groups, split_points) = fg.group_by_partition_values_with_split_points(3);
1344        assert_eq!(groups.len(), 3);
1345        assert_eq!(split_points.len(), 2);
1346        assert_eq!(split_points[0].values(), &[ScalarValue::from("p2")]);
1347        assert_eq!(split_points[1].values(), &[ScalarValue::from("p4")]);
1348
1349        // Every file routes (RangeRouter semantics) to the group it was placed in.
1350        for (idx, group) in groups.iter().enumerate() {
1351            for file in group.iter() {
1352                assert_eq!(range_route(&file.partition_values, &split_points), idx);
1353            }
1354        }
1355    }
1356
1357    #[test]
1358    fn test_group_by_partition_values_split_points_fewer_values_than_target() {
1359        let fg = FileGroup::new(vec![
1360            pfile_with_pv("a", "p1"),
1361            pfile_with_pv("b", "p1"),
1362            pfile_with_pv("c", "p2"),
1363        ]);
1364        let (groups, split_points) = fg.group_by_partition_values_with_split_points(4);
1365        assert_eq!(groups.len(), 2);
1366        assert_eq!(split_points.len(), 1);
1367        assert_eq!(split_points[0].values(), &[ScalarValue::from("p2")]);
1368        for (idx, group) in groups.iter().enumerate() {
1369            for file in group.iter() {
1370                assert_eq!(range_route(&file.partition_values, &split_points), idx);
1371            }
1372        }
1373    }
1374
1375    #[test]
1376    fn test_group_by_partition_values_split_points_single_target_partition() {
1377        // One partition holds every value, so there is no boundary to describe.
1378        let fg = FileGroup::new(vec![
1379            pfile_with_pv("a", "p1"),
1380            pfile_with_pv("b", "p2"),
1381            pfile_with_pv("c", "p3"),
1382            pfile_with_pv("d", "p3"),
1383        ]);
1384        let (groups, split_points) = fg.group_by_partition_values_with_split_points(1);
1385        assert_eq!(groups.len(), 1);
1386        assert_eq!(groups[0].len(), 4);
1387        assert!(split_points.is_empty());
1388    }
1389
1390    fn pfile_with_pvs(path: &str, pvs: &[Option<&str>]) -> PartitionedFile {
1391        let mut file = pfile(path, 10);
1392        file.partition_values = pvs
1393            .iter()
1394            .map(|v| ScalarValue::Utf8(v.map(str::to_string)))
1395            .collect();
1396        file
1397    }
1398
1399    /// Two partition columns with NULLs in either position.
1400    fn compound_key_file_group() -> FileGroup {
1401        FileGroup::new(vec![
1402            pfile_with_pvs("a", &[Some("2026"), Some("09")]),
1403            pfile_with_pvs("b", &[Some("2026"), Some("10")]),
1404            pfile_with_pvs("c", &[None, Some("09")]),
1405            pfile_with_pvs("d", &[Some("2025"), None]),
1406            pfile_with_pvs("e", &[Some("2025"), Some("12")]),
1407        ])
1408    }
1409
1410    #[test]
1411    fn test_group_by_partition_values_split_points_null_and_compound_keys() {
1412        let fg = compound_key_file_group();
1413        let (groups, split_points) = fg.group_by_partition_values_with_split_points(2);
1414        assert_eq!(groups.len(), 2);
1415        assert_eq!(split_points.len(), 1);
1416        assert_eq!(
1417            split_points[0].values(),
1418            &[ScalarValue::from("2025"), ScalarValue::from("12")]
1419        );
1420        for (idx, group) in groups.iter().enumerate() {
1421            for file in group.iter() {
1422                assert_eq!(range_route(&file.partition_values, &split_points), idx);
1423            }
1424        }
1425    }
1426
1427    #[test]
1428    fn test_group_by_partition_values_split_point_containing_null() {
1429        let fg = compound_key_file_group();
1430        let (groups, split_points) = fg.group_by_partition_values_with_split_points(3);
1431        assert_eq!(groups.len(), 3);
1432        assert_eq!(
1433            split_points[0].values(),
1434            &[ScalarValue::from("2025"), ScalarValue::Utf8(None)]
1435        );
1436        assert_eq!(
1437            split_points[1].values(),
1438            &[ScalarValue::from("2026"), ScalarValue::from("09")]
1439        );
1440        for (idx, group) in groups.iter().enumerate() {
1441            for file in group.iter() {
1442                assert_eq!(range_route(&file.partition_values, &split_points), idx);
1443            }
1444        }
1445        let ordering = LexOrdering::new(vec![
1446            PhysicalSortExpr::new_default(Arc::new(Column::new("year", 0))),
1447            PhysicalSortExpr::new_default(Arc::new(Column::new("month", 1))),
1448        ])
1449        .unwrap();
1450        let range = RangePartitioning::try_new(ordering, split_points).unwrap();
1451        assert_eq!(range.partition_count(), 3);
1452    }
1453}