mito2/sst/parquet/
row_selection.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, BTreeSet};
16use std::ops::Range;
17
18use index::inverted_index::search::index_apply::ApplyOutput;
19use itertools::Itertools;
20use parquet::arrow::arrow_reader::{RowSelection, RowSelector};
21
22/// A selection of row groups.
23#[derive(Debug, Clone, Default)]
24pub struct RowGroupSelection {
25    /// Row group id to row selection.
26    selection_in_rg: BTreeMap<usize, RowSelectionWithCount>,
27    /// Total number of rows in the selection.
28    row_count: usize,
29    /// Total length of the selectors.
30    selector_len: usize,
31}
32
33/// A row selection with its count.
34#[derive(Debug, Clone, Default)]
35struct RowSelectionWithCount {
36    /// Row selection.
37    selection: RowSelection,
38    /// Number of rows in the selection.
39    row_count: usize,
40    /// Length of the selectors.
41    selector_len: usize,
42}
43
44impl RowGroupSelection {
45    /// Creates a new `RowGroupSelection` with all row groups selected.
46    ///
47    /// # Arguments
48    /// * `row_group_size` - The number of rows in each row group (except possibly the last one)
49    /// * `total_row_count` - Total number of rows
50    pub fn new(row_group_size: usize, total_row_count: usize) -> Self {
51        let mut selection_in_rg = BTreeMap::new();
52
53        let row_group_count = total_row_count.div_ceil(row_group_size);
54        for rg_id in 0..row_group_count {
55            // The last row group may have fewer rows than `row_group_size`
56            let row_group_size = if rg_id == row_group_count - 1 {
57                total_row_count - (row_group_count - 1) * row_group_size
58            } else {
59                row_group_size
60            };
61
62            let selection = RowSelection::from(vec![RowSelector::select(row_group_size)]);
63            selection_in_rg.insert(
64                rg_id,
65                RowSelectionWithCount {
66                    selection,
67                    row_count: row_group_size,
68                    selector_len: 1,
69                },
70            );
71        }
72
73        Self {
74            selection_in_rg,
75            row_count: total_row_count,
76            selector_len: row_group_count,
77        }
78    }
79
80    /// Creates a new `RowGroupSelection` that selects all rows in the specified row groups.
81    ///
82    /// This is useful for fast construction after coarse pruning (e.g. min-max pruning),
83    /// avoiding building and then removing a full selection of all row groups.
84    pub fn from_full_row_group_ids<I>(
85        row_group_ids: I,
86        row_group_size: usize,
87        total_row_count: usize,
88    ) -> Self
89    where
90        I: IntoIterator<Item = usize>,
91    {
92        if row_group_size == 0 || total_row_count == 0 {
93            return Self::default();
94        }
95
96        let row_group_count = total_row_count.div_ceil(row_group_size);
97        if row_group_count == 0 {
98            return Self::default();
99        }
100
101        let last_row_group_size = total_row_count - (row_group_count - 1) * row_group_size;
102
103        let mut selection_in_rg = BTreeMap::new();
104        let mut row_count = 0usize;
105        let mut selector_len = 0usize;
106
107        for rg_id in row_group_ids {
108            if rg_id >= row_group_count {
109                continue;
110            }
111
112            let rg_row_count = if rg_id == row_group_count - 1 {
113                last_row_group_size
114            } else {
115                row_group_size
116            };
117
118            let selection = RowSelection::from(vec![RowSelector::select(rg_row_count)]);
119            if selection_in_rg
120                .insert(
121                    rg_id,
122                    RowSelectionWithCount {
123                        selection,
124                        row_count: rg_row_count,
125                        selector_len: 1,
126                    },
127                )
128                .is_none()
129            {
130                row_count += rg_row_count;
131                selector_len += 1;
132            }
133        }
134
135        Self {
136            selection_in_rg,
137            row_count,
138            selector_len,
139        }
140    }
141
142    /// Returns the row selection for a given row group.
143    ///
144    /// `None` indicates not selected.
145    pub fn get(&self, rg_id: usize) -> Option<&RowSelection> {
146        self.selection_in_rg.get(&rg_id).map(|x| &x.selection)
147    }
148
149    /// Creates a new `RowGroupSelection` from the output of inverted index application.
150    ///
151    /// # Arguments
152    /// * `row_group_size` - The number of rows in each row group (except possibly the last one)
153    /// * `apply_output` - The output from applying the inverted index
154    ///
155    /// # Assumptions
156    /// * All row groups (except possibly the last one) have the same number of rows
157    /// * The last row group may have fewer rows than `row_group_size`
158    pub fn from_inverted_index_apply_output(
159        row_group_size: usize,
160        num_row_groups: usize,
161        apply_output: ApplyOutput,
162    ) -> Self {
163        // Step 1: Convert segment IDs to row ranges within row groups
164        // For each segment ID, calculate its corresponding row range in the row group
165        let segment_row_count = apply_output.segment_row_count;
166        let row_group_ranges = apply_output.matched_segment_ids.iter_ones().map(|seg_id| {
167            // Calculate the global row ID where this segment starts
168            let begin_row_id = seg_id * segment_row_count;
169            // Determine which row group this segment belongs to
170            let row_group_id = begin_row_id / row_group_size;
171            // Calculate the offset within the row group
172            let rg_begin_row_id = begin_row_id % row_group_size;
173            // Ensure the end row ID doesn't exceed the row group size
174            let rg_end_row_id = (rg_begin_row_id + segment_row_count).min(row_group_size);
175
176            (row_group_id, rg_begin_row_id..rg_end_row_id)
177        });
178
179        // Step 2: Group ranges by row group ID and create row selections
180        let mut total_row_count = 0;
181        let mut total_selector_len = 0;
182        let mut selection_in_rg = row_group_ranges
183            .chunk_by(|(row_group_id, _)| *row_group_id)
184            .into_iter()
185            .map(|(row_group_id, group)| {
186                // Extract just the ranges from the group
187                let ranges = group.map(|(_, ranges)| ranges);
188                // Create row selection from the ranges
189                // Note: We use `row_group_size` here, which is safe because:
190                // 1. For non-last row groups, it's the actual size
191                // 2. For the last row group, any ranges beyond the actual size will be clipped
192                //    by the min() operation above
193                let selection = row_selection_from_row_ranges(ranges, row_group_size);
194                let row_count = selection.row_count();
195                let selector_len = selector_len(&selection);
196                total_row_count += row_count;
197                total_selector_len += selector_len;
198                (
199                    row_group_id,
200                    RowSelectionWithCount {
201                        selection,
202                        row_count,
203                        selector_len,
204                    },
205                )
206            })
207            .collect::<BTreeMap<_, _>>();
208
209        Self::fill_missing_row_groups(&mut selection_in_rg, num_row_groups);
210
211        Self {
212            selection_in_rg,
213            row_count: total_row_count,
214            selector_len: total_selector_len,
215        }
216    }
217
218    /// Creates a new `RowGroupSelection` from a set of row IDs.
219    ///
220    /// # Arguments
221    /// * `row_ids` - Set of row IDs to select
222    /// * `row_group_size` - The number of rows in each row group (except possibly the last one)
223    /// * `num_row_groups` - Total number of row groups
224    ///
225    /// # Assumptions
226    /// * All row groups (except possibly the last one) have the same number of rows
227    /// * The last row group may have fewer rows than `row_group_size`
228    /// * All row IDs must within the range of [0, num_row_groups * row_group_size)
229    pub fn from_row_ids(
230        row_ids: BTreeSet<u32>,
231        row_group_size: usize,
232        num_row_groups: usize,
233    ) -> Self {
234        // Step 1: Group row IDs by their row group
235        let row_group_to_row_ids =
236            Self::group_row_ids_by_row_group(row_ids, row_group_size, num_row_groups);
237
238        // Step 2: Create row selections for each row group
239        let mut total_row_count = 0;
240        let mut total_selector_len = 0;
241        let mut selection_in_rg = row_group_to_row_ids
242            .into_iter()
243            .map(|(row_group_id, row_ids)| {
244                let selection =
245                    row_selection_from_sorted_row_ids(row_ids.into_iter(), row_group_size);
246                let row_count = selection.row_count();
247                let selector_len = selector_len(&selection);
248                total_row_count += row_count;
249                total_selector_len += selector_len;
250                (
251                    row_group_id,
252                    RowSelectionWithCount {
253                        selection,
254                        row_count,
255                        selector_len,
256                    },
257                )
258            })
259            .collect::<BTreeMap<_, _>>();
260
261        Self::fill_missing_row_groups(&mut selection_in_rg, num_row_groups);
262
263        Self {
264            selection_in_rg,
265            row_count: total_row_count,
266            selector_len: total_selector_len,
267        }
268    }
269
270    /// Creates a new `RowGroupSelection` from a set of row ranges.
271    ///
272    /// # Arguments
273    /// * `row_ranges` - A vector of (row_group_id, row_ranges) pairs
274    /// * `row_group_size` - The number of rows in each row group (except possibly the last one)
275    ///
276    /// # Assumptions
277    /// * All row groups (except possibly the last one) have the same number of rows
278    /// * The last row group may have fewer rows than `row_group_size`
279    /// * All ranges in `row_ranges` must be within the bounds of their respective row groups
280    ///   (i.e., for row group i, all ranges must be within [0, row_group_size) or [0, remaining_rows) for the last row group)
281    /// * Ranges within the same row group must not overlap. Overlapping ranges will result in undefined behavior.
282    pub fn from_row_ranges(
283        row_ranges: Vec<(usize, Vec<Range<usize>>)>,
284        row_group_size: usize,
285    ) -> Self {
286        let mut total_row_count = 0;
287        let mut total_selector_len = 0;
288        let selection_in_rg = row_ranges
289            .into_iter()
290            .map(|(row_group_id, ranges)| {
291                let selection = row_selection_from_row_ranges(ranges.into_iter(), row_group_size);
292                let row_count = selection.row_count();
293                let selector_len = selector_len(&selection);
294                total_row_count += row_count;
295                total_selector_len += selector_len;
296                (
297                    row_group_id,
298                    RowSelectionWithCount {
299                        selection,
300                        row_count,
301                        selector_len,
302                    },
303                )
304            })
305            .collect();
306
307        Self {
308            selection_in_rg,
309            row_count: total_row_count,
310            selector_len: total_selector_len,
311        }
312    }
313
314    /// Groups row IDs by their row group.
315    ///
316    /// # Arguments
317    /// * `row_ids` - Set of row IDs to group
318    /// * `row_group_size` - Size of each row group
319    /// * `num_row_groups` - Total number of row groups
320    ///
321    /// # Returns
322    /// A vector of (row_group_id, row_ids) pairs, where row_ids are the IDs within that row group.
323    fn group_row_ids_by_row_group(
324        row_ids: BTreeSet<u32>,
325        row_group_size: usize,
326        num_row_groups: usize,
327    ) -> Vec<(usize, Vec<usize>)> {
328        let est_rows_per_group = row_ids.len() / num_row_groups;
329        let mut row_group_to_row_ids: Vec<(usize, Vec<usize>)> = Vec::with_capacity(num_row_groups);
330
331        for row_id in row_ids {
332            let row_group_id = row_id as usize / row_group_size;
333            let row_id_in_group = row_id as usize % row_group_size;
334
335            if let Some((rg_id, row_ids)) = row_group_to_row_ids.last_mut()
336                && *rg_id == row_group_id
337            {
338                row_ids.push(row_id_in_group);
339            } else {
340                let mut row_ids = Vec::with_capacity(est_rows_per_group);
341                row_ids.push(row_id_in_group);
342                row_group_to_row_ids.push((row_group_id, row_ids));
343            }
344        }
345
346        row_group_to_row_ids
347    }
348
349    /// Intersects two `RowGroupSelection`s.
350    pub fn intersect(&self, other: &Self) -> Self {
351        let mut res = BTreeMap::new();
352        let mut total_row_count = 0;
353        let mut total_selector_len = 0;
354
355        for (rg_id, x) in other.selection_in_rg.iter() {
356            let Some(y) = self.selection_in_rg.get(rg_id) else {
357                continue;
358            };
359            let selection = intersect_row_selections(&x.selection, &y.selection);
360            let row_count = selection.row_count();
361            let selector_len = selector_len(&selection);
362            if row_count > 0 {
363                total_row_count += row_count;
364                total_selector_len += selector_len;
365                res.insert(
366                    *rg_id,
367                    RowSelectionWithCount {
368                        selection,
369                        row_count,
370                        selector_len,
371                    },
372                );
373            }
374        }
375
376        Self {
377            selection_in_rg: res,
378            row_count: total_row_count,
379            selector_len: total_selector_len,
380        }
381    }
382
383    /// Returns the number of row groups in the selection.
384    pub fn row_group_count(&self) -> usize {
385        self.selection_in_rg.len()
386    }
387
388    /// Returns the number of rows in the selection.
389    pub fn row_count(&self) -> usize {
390        self.row_count
391    }
392
393    /// Returns the first row group in the selection.
394    ///
395    /// Skip the row group if the row count is 0.
396    pub fn pop_first(&mut self) -> Option<(usize, RowSelection)> {
397        while let Some((
398            row_group_id,
399            RowSelectionWithCount {
400                selection,
401                row_count,
402                selector_len,
403            },
404        )) = self.selection_in_rg.pop_first()
405        {
406            if row_count > 0 {
407                self.row_count -= row_count;
408                self.selector_len -= selector_len;
409                return Some((row_group_id, selection));
410            }
411        }
412
413        None
414    }
415
416    /// Removes a row group from the selection.
417    pub fn remove_row_group(&mut self, row_group_id: usize) {
418        let Some(RowSelectionWithCount {
419            row_count,
420            selector_len,
421            ..
422        }) = self.selection_in_rg.remove(&row_group_id)
423        else {
424            return;
425        };
426        self.row_count -= row_count;
427        self.selector_len -= selector_len;
428    }
429
430    /// Returns true if the selection is empty.
431    pub fn is_empty(&self) -> bool {
432        self.selection_in_rg.is_empty()
433    }
434
435    /// Returns true if the selection contains a row group with the given ID.
436    pub fn contains_row_group(&self, row_group_id: usize) -> bool {
437        self.selection_in_rg.contains_key(&row_group_id)
438    }
439
440    /// Returns true if the selection contains a row group with the given ID and the row selection is not empty.
441    pub fn contains_non_empty_row_group(&self, row_group_id: usize) -> bool {
442        self.selection_in_rg
443            .get(&row_group_id)
444            .map(|r| r.row_count > 0)
445            .unwrap_or(false)
446    }
447
448    /// Returns an iterator over the row groups in the selection.
449    pub fn iter(&self) -> impl Iterator<Item = (&usize, &RowSelection)> {
450        self.selection_in_rg
451            .iter()
452            .map(|(row_group_id, x)| (row_group_id, &x.selection))
453    }
454
455    /// Returns the memory usage of the selection.
456    pub fn mem_usage(&self) -> usize {
457        self.selector_len * size_of::<RowSelector>()
458            + self.selection_in_rg.len() * size_of::<RowSelectionWithCount>()
459    }
460
461    /// Concatenates `other` into `self`. `other` must not contain row groups that `self` contains.
462    ///
463    /// Panics if `self` contains row groups that `other` contains.
464    pub fn concat(&mut self, other: &Self) {
465        for (rg_id, other_rs) in other.selection_in_rg.iter() {
466            if self.selection_in_rg.contains_key(rg_id) {
467                panic!("row group {} is already in `self`", rg_id);
468            }
469
470            self.selection_in_rg.insert(*rg_id, other_rs.clone());
471            self.row_count += other_rs.row_count;
472            self.selector_len += other_rs.selector_len;
473        }
474    }
475
476    /// Fills the missing row groups with empty selections.
477    /// This is to indicate that the row groups are searched even if no rows are found.
478    fn fill_missing_row_groups(
479        selection_in_rg: &mut BTreeMap<usize, RowSelectionWithCount>,
480        num_row_groups: usize,
481    ) {
482        for rg_id in 0..num_row_groups {
483            selection_in_rg.entry(rg_id).or_default();
484        }
485    }
486}
487
488/// Ported from `parquet` but trailing rows are removed.
489///
490/// Combine two lists of `RowSelection` return the intersection of them
491/// For example:
492/// self:      NNYYYYNNYYNYN
493/// other:     NYNNNNNNY
494///
495/// returned:  NNNNNNNNY     (modified)
496///            NNNNNNNNYYNYN (original)
497fn intersect_row_selections(left: &RowSelection, right: &RowSelection) -> RowSelection {
498    let mut l_iter = left.iter().copied().peekable();
499    let mut r_iter = right.iter().copied().peekable();
500
501    let iter = std::iter::from_fn(move || {
502        loop {
503            let l = l_iter.peek_mut();
504            let r = r_iter.peek_mut();
505
506            match (l, r) {
507                (Some(a), _) if a.row_count == 0 => {
508                    l_iter.next().unwrap();
509                }
510                (_, Some(b)) if b.row_count == 0 => {
511                    r_iter.next().unwrap();
512                }
513                (Some(l), Some(r)) => {
514                    return match (l.skip, r.skip) {
515                        // Keep both ranges
516                        (false, false) => {
517                            if l.row_count < r.row_count {
518                                r.row_count -= l.row_count;
519                                l_iter.next()
520                            } else {
521                                l.row_count -= r.row_count;
522                                r_iter.next()
523                            }
524                        }
525                        // skip at least one
526                        _ => {
527                            if l.row_count < r.row_count {
528                                let skip = l.row_count;
529                                r.row_count -= l.row_count;
530                                l_iter.next();
531                                Some(RowSelector::skip(skip))
532                            } else {
533                                let skip = r.row_count;
534                                l.row_count -= skip;
535                                r_iter.next();
536                                Some(RowSelector::skip(skip))
537                            }
538                        }
539                    };
540                }
541                (None, _) => return None,
542                (_, None) => return None,
543            }
544        }
545    });
546
547    iter.collect()
548}
549
550/// Converts an iterator of row ranges into a `RowSelection` by creating a sequence of `RowSelector`s.
551///
552/// This function processes each range in the input and either creates a new selector or merges
553/// with the existing one, depending on whether the current range is contiguous with the preceding one
554/// or if there's a gap that requires skipping rows. It handles both "select" and "skip" actions,
555/// optimizing the list of selectors by merging contiguous actions of the same type.
556///
557/// Note: overlapping ranges are not supported and will result in an incorrect selection.
558pub(crate) fn row_selection_from_row_ranges(
559    row_ranges: impl Iterator<Item = Range<usize>>,
560    total_row_count: usize,
561) -> RowSelection {
562    let mut selectors: Vec<RowSelector> = Vec::new();
563    let mut last_processed_end = 0;
564
565    for Range { start, end } in row_ranges {
566        let end = end.min(total_row_count);
567        if start > last_processed_end {
568            add_or_merge_selector(&mut selectors, start - last_processed_end, true);
569        }
570
571        add_or_merge_selector(&mut selectors, end - start, false);
572        last_processed_end = end;
573    }
574
575    RowSelection::from(selectors)
576}
577
578/// Converts an iterator of sorted row IDs into a `RowSelection`.
579///
580/// Note: the input iterator must be sorted in ascending order and
581///       contain unique row IDs in the range [0, total_row_count).
582pub(crate) fn row_selection_from_sorted_row_ids(
583    row_ids: impl Iterator<Item = usize>,
584    total_row_count: usize,
585) -> RowSelection {
586    let mut selectors: Vec<RowSelector> = Vec::new();
587    let mut last_processed_end = 0;
588
589    for row_id in row_ids {
590        let start = row_id;
591        let end = start + 1;
592
593        if start > last_processed_end {
594            add_or_merge_selector(&mut selectors, start - last_processed_end, true);
595        }
596
597        add_or_merge_selector(&mut selectors, end - start, false);
598        last_processed_end = end;
599    }
600
601    if last_processed_end < total_row_count {
602        add_or_merge_selector(&mut selectors, total_row_count - last_processed_end, true);
603    }
604
605    RowSelection::from(selectors)
606}
607
608/// Helper function to either add a new `RowSelector` to `selectors` or merge it with the last one
609/// if they are of the same type (both skip or both select).
610fn add_or_merge_selector(selectors: &mut Vec<RowSelector>, count: usize, is_skip: bool) {
611    if let Some(last) = selectors.last_mut() {
612        // Merge with last if both actions are same
613        if last.skip == is_skip {
614            last.row_count += count;
615            return;
616        }
617    }
618    // Add new selector otherwise
619    let new_selector = if is_skip {
620        RowSelector::skip(count)
621    } else {
622        RowSelector::select(count)
623    };
624    selectors.push(new_selector);
625}
626
627/// Returns the length of the selectors in the selection.
628fn selector_len(selection: &RowSelection) -> usize {
629    selection.iter().size_hint().0
630}
631
632#[cfg(test)]
633#[allow(clippy::single_range_in_vec_init)]
634mod tests {
635    use super::*;
636
637    #[test]
638    fn test_selector_len() {
639        let selection = RowSelection::from(vec![RowSelector::skip(5), RowSelector::select(5)]);
640        assert_eq!(selector_len(&selection), 2);
641
642        let selection = RowSelection::from(vec![
643            RowSelector::select(5),
644            RowSelector::skip(5),
645            RowSelector::select(5),
646        ]);
647        assert_eq!(selector_len(&selection), 3);
648
649        let selection = RowSelection::from(vec![]);
650        assert_eq!(selector_len(&selection), 0);
651    }
652
653    #[test]
654    fn test_single_contiguous_range() {
655        let selection = row_selection_from_row_ranges(Some(5..10).into_iter(), 10);
656        let expected = RowSelection::from(vec![RowSelector::skip(5), RowSelector::select(5)]);
657        assert_eq!(selection, expected);
658    }
659
660    #[test]
661    fn test_non_contiguous_ranges() {
662        let ranges = [1..3, 5..8];
663        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10);
664        let expected = RowSelection::from(vec![
665            RowSelector::skip(1),
666            RowSelector::select(2),
667            RowSelector::skip(2),
668            RowSelector::select(3),
669        ]);
670        assert_eq!(selection, expected);
671    }
672
673    #[test]
674    fn test_empty_range() {
675        let ranges = [];
676        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10);
677        let expected = RowSelection::from(vec![]);
678        assert_eq!(selection, expected);
679    }
680
681    #[test]
682    fn test_adjacent_ranges() {
683        let ranges = [1..2, 2..3];
684        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10);
685        let expected = RowSelection::from(vec![RowSelector::skip(1), RowSelector::select(2)]);
686        assert_eq!(selection, expected);
687    }
688
689    #[test]
690    fn test_large_gap_between_ranges() {
691        let ranges = [1..2, 100..101];
692        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10240);
693        let expected = RowSelection::from(vec![
694            RowSelector::skip(1),
695            RowSelector::select(1),
696            RowSelector::skip(98),
697            RowSelector::select(1),
698        ]);
699        assert_eq!(selection, expected);
700    }
701
702    #[test]
703    fn test_range_end_over_total_row_count() {
704        let ranges = Some(1..10);
705        let selection = row_selection_from_row_ranges(ranges.into_iter(), 5);
706        let expected = RowSelection::from(vec![RowSelector::skip(1), RowSelector::select(4)]);
707        assert_eq!(selection, expected);
708    }
709
710    #[test]
711    fn test_row_ids_to_selection() {
712        let row_ids = [1, 3, 5, 7, 9].into_iter();
713        let selection = row_selection_from_sorted_row_ids(row_ids, 10);
714        let expected = RowSelection::from(vec![
715            RowSelector::skip(1),
716            RowSelector::select(1),
717            RowSelector::skip(1),
718            RowSelector::select(1),
719            RowSelector::skip(1),
720            RowSelector::select(1),
721            RowSelector::skip(1),
722            RowSelector::select(1),
723            RowSelector::skip(1),
724            RowSelector::select(1),
725        ]);
726        assert_eq!(selection, expected);
727    }
728
729    #[test]
730    fn test_row_ids_to_selection_full() {
731        let row_ids = 0..10;
732        let selection = row_selection_from_sorted_row_ids(row_ids, 10);
733        let expected = RowSelection::from(vec![RowSelector::select(10)]);
734        assert_eq!(selection, expected);
735    }
736
737    #[test]
738    fn test_row_ids_to_selection_empty() {
739        let selection = row_selection_from_sorted_row_ids(None.into_iter(), 10);
740        let expected = RowSelection::from(vec![RowSelector::skip(10)]);
741        assert_eq!(selection, expected);
742    }
743
744    #[test]
745    fn test_group_row_ids() {
746        let row_ids = [0, 1, 2, 5, 6, 7, 8, 12].into_iter().collect();
747        let row_group_size = 5;
748        let num_row_groups = 3;
749
750        let row_group_to_row_ids =
751            RowGroupSelection::group_row_ids_by_row_group(row_ids, row_group_size, num_row_groups);
752
753        assert_eq!(
754            row_group_to_row_ids,
755            vec![(0, vec![0, 1, 2]), (1, vec![0, 1, 2, 3]), (2, vec![2])]
756        );
757    }
758
759    #[test]
760    fn test_row_group_selection_new() {
761        // Test with regular case
762        let selection = RowGroupSelection::new(100, 250);
763        assert_eq!(selection.row_count(), 250);
764        assert_eq!(selection.row_group_count(), 3);
765
766        // Check content of each row group
767        let row_selection = selection.get(0).unwrap();
768        assert_eq!(row_selection.row_count(), 100);
769
770        let row_selection = selection.get(1).unwrap();
771        assert_eq!(row_selection.row_count(), 100);
772
773        let row_selection = selection.get(2).unwrap();
774        assert_eq!(row_selection.row_count(), 50);
775
776        // Test with empty selection
777        let selection = RowGroupSelection::new(100, 0);
778        assert_eq!(selection.row_count(), 0);
779        assert_eq!(selection.row_group_count(), 0);
780        assert!(selection.get(0).is_none());
781
782        // Test with single row group
783        let selection = RowGroupSelection::new(100, 50);
784        assert_eq!(selection.row_count(), 50);
785        assert_eq!(selection.row_group_count(), 1);
786
787        let row_selection = selection.get(0).unwrap();
788        assert_eq!(row_selection.row_count(), 50);
789
790        // Test with row count that doesn't divide evenly
791        let selection = RowGroupSelection::new(100, 150);
792        assert_eq!(selection.row_count(), 150);
793        assert_eq!(selection.row_group_count(), 2);
794
795        let row_selection = selection.get(0).unwrap();
796        assert_eq!(row_selection.row_count(), 100);
797
798        let row_selection = selection.get(1).unwrap();
799        assert_eq!(row_selection.row_count(), 50);
800
801        // Test with row count that's just over a multiple of row_group_size
802        let selection = RowGroupSelection::new(100, 101);
803        assert_eq!(selection.row_count(), 101);
804        assert_eq!(selection.row_group_count(), 2);
805
806        let row_selection = selection.get(0).unwrap();
807        assert_eq!(row_selection.row_count(), 100);
808
809        let row_selection = selection.get(1).unwrap();
810        assert_eq!(row_selection.row_count(), 1);
811    }
812
813    #[test]
814    fn test_from_full_row_group_ids_dedup_duplicates() {
815        let selection = RowGroupSelection::from_full_row_group_ids([0, 0, 2, 2], 10, 25);
816        assert_eq!(selection.row_group_count(), 2);
817        assert_eq!(selection.row_count(), 15);
818
819        assert_eq!(selection.get(0).unwrap().row_count(), 10);
820        assert_eq!(selection.get(2).unwrap().row_count(), 5);
821    }
822
823    #[test]
824    fn test_from_row_ids() {
825        let row_group_size = 100;
826        let num_row_groups = 3;
827
828        // Test with regular case
829        let row_ids: BTreeSet<u32> = vec![5, 15, 25, 35, 105, 115, 205, 215]
830            .into_iter()
831            .collect();
832        let selection = RowGroupSelection::from_row_ids(row_ids, row_group_size, num_row_groups);
833        assert_eq!(selection.row_count(), 8);
834        assert_eq!(selection.row_group_count(), 3);
835
836        // Check content of each row group
837        let row_selection = selection.get(0).unwrap();
838        assert_eq!(row_selection.row_count(), 4); // 5, 15, 25, 35
839
840        let row_selection = selection.get(1).unwrap();
841        assert_eq!(row_selection.row_count(), 2); // 105, 115
842
843        let row_selection = selection.get(2).unwrap();
844        assert_eq!(row_selection.row_count(), 2); // 205, 215
845
846        // Test with empty row IDs
847        let empty_row_ids: BTreeSet<u32> = BTreeSet::new();
848        let selection =
849            RowGroupSelection::from_row_ids(empty_row_ids, row_group_size, num_row_groups);
850        assert_eq!(selection.row_count(), 0);
851        assert_eq!(selection.row_group_count(), 3);
852
853        // Test with consecutive row IDs
854        let consecutive_row_ids: BTreeSet<u32> = vec![5, 6, 7, 8, 9].into_iter().collect();
855        let selection =
856            RowGroupSelection::from_row_ids(consecutive_row_ids, row_group_size, num_row_groups);
857        assert_eq!(selection.row_count(), 5);
858        assert_eq!(selection.row_group_count(), 3);
859
860        let row_selection = selection.get(0).unwrap();
861        assert_eq!(row_selection.row_count(), 5); // 5, 6, 7, 8, 9
862
863        // Test with row IDs at row group boundaries
864        let boundary_row_ids: BTreeSet<u32> = vec![0, 99, 100, 199, 200, 249].into_iter().collect();
865        let selection =
866            RowGroupSelection::from_row_ids(boundary_row_ids, row_group_size, num_row_groups);
867        assert_eq!(selection.row_count(), 6);
868        assert_eq!(selection.row_group_count(), 3);
869
870        let row_selection = selection.get(0).unwrap();
871        assert_eq!(row_selection.row_count(), 2); // 0, 99
872
873        let row_selection = selection.get(1).unwrap();
874        assert_eq!(row_selection.row_count(), 2); // 100, 199
875
876        let row_selection = selection.get(2).unwrap();
877        assert_eq!(row_selection.row_count(), 2); // 200, 249
878
879        // Test with single row group
880        let single_group_row_ids: BTreeSet<u32> = vec![5, 10, 15].into_iter().collect();
881        let selection = RowGroupSelection::from_row_ids(single_group_row_ids, row_group_size, 1);
882        assert_eq!(selection.row_count(), 3);
883        assert_eq!(selection.row_group_count(), 1);
884
885        let row_selection = selection.get(0).unwrap();
886        assert_eq!(row_selection.row_count(), 3); // 5, 10, 15
887    }
888
889    #[test]
890    fn test_from_row_ranges() {
891        let row_group_size = 100;
892
893        // Test with regular case
894        let ranges = vec![
895            (0, vec![5..15, 25..35]), // Within [0, 100)
896            (1, vec![5..15]),         // Within [0, 100)
897            (2, vec![0..5, 10..15]),  // Within [0, 50) for last row group
898        ];
899        let selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
900        assert_eq!(selection.row_count(), 40);
901        assert_eq!(selection.row_group_count(), 3);
902
903        // Check content of each row group
904        let row_selection = selection.get(0).unwrap();
905        assert_eq!(row_selection.row_count(), 20); // 5..15 (10) + 25..35 (10)
906
907        let row_selection = selection.get(1).unwrap();
908        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
909
910        let row_selection = selection.get(2).unwrap();
911        assert_eq!(row_selection.row_count(), 10); // 0..5 (5) + 10..15 (5)
912
913        // Test with empty ranges
914        let empty_ranges: Vec<(usize, Vec<Range<usize>>)> = vec![];
915        let selection = RowGroupSelection::from_row_ranges(empty_ranges, row_group_size);
916        assert_eq!(selection.row_count(), 0);
917        assert_eq!(selection.row_group_count(), 0);
918        assert!(selection.get(0).is_none());
919
920        // Test with adjacent ranges within same row group
921        let adjacent_ranges = vec![
922            (0, vec![5..15, 15..25]), // Adjacent ranges within [0, 100)
923        ];
924        let selection = RowGroupSelection::from_row_ranges(adjacent_ranges, row_group_size);
925        assert_eq!(selection.row_count(), 20);
926        assert_eq!(selection.row_group_count(), 1);
927
928        let row_selection = selection.get(0).unwrap();
929        assert_eq!(row_selection.row_count(), 20); // 5..15 (10) + 15..25 (10)
930
931        // Test with ranges at row group boundaries
932        let boundary_ranges = vec![
933            (0, vec![0..10, 90..100]), // Ranges at start and end of first row group
934            (1, vec![0..100]),         // Full range of second row group
935            (2, vec![0..50]),          // Full range of last row group
936        ];
937        let selection = RowGroupSelection::from_row_ranges(boundary_ranges, row_group_size);
938        assert_eq!(selection.row_count(), 170);
939        assert_eq!(selection.row_group_count(), 3);
940
941        let row_selection = selection.get(0).unwrap();
942        assert_eq!(row_selection.row_count(), 20); // 0..10 (10) + 90..100 (10)
943
944        let row_selection = selection.get(1).unwrap();
945        assert_eq!(row_selection.row_count(), 100); // 0..100 (100)
946
947        let row_selection = selection.get(2).unwrap();
948        assert_eq!(row_selection.row_count(), 50); // 0..50 (50)
949
950        // Test with single row group
951        let single_group_ranges = vec![
952            (0, vec![0..50]), // Half of first row group
953        ];
954        let selection = RowGroupSelection::from_row_ranges(single_group_ranges, row_group_size);
955        assert_eq!(selection.row_count(), 50);
956        assert_eq!(selection.row_group_count(), 1);
957
958        let row_selection = selection.get(0).unwrap();
959        assert_eq!(row_selection.row_count(), 50); // 0..50 (50)
960    }
961
962    #[test]
963    fn test_intersect() {
964        let row_group_size = 100;
965
966        // Test case 1: Regular intersection with partial overlap
967        let ranges1 = vec![
968            (0, vec![5..15, 25..35]), // Within [0, 100)
969            (1, vec![5..15]),         // Within [0, 100)
970        ];
971        let selection1 = RowGroupSelection::from_row_ranges(ranges1, row_group_size);
972
973        let ranges2 = vec![
974            (0, vec![10..20]), // Within [0, 100)
975            (1, vec![10..20]), // Within [0, 100)
976            (2, vec![0..10]),  // Within [0, 50) for last row group
977        ];
978        let selection2 = RowGroupSelection::from_row_ranges(ranges2, row_group_size);
979
980        let intersection = selection1.intersect(&selection2);
981        assert_eq!(intersection.row_count(), 10);
982        assert_eq!(intersection.row_group_count(), 2);
983
984        let row_selection = intersection.get(0).unwrap();
985        assert_eq!(row_selection.row_count(), 5); // 10..15 (5)
986
987        let row_selection = intersection.get(1).unwrap();
988        assert_eq!(row_selection.row_count(), 5); // 10..15 (5)
989
990        // Test case 2: Empty intersection with empty selection
991        let empty_ranges: Vec<(usize, Vec<Range<usize>>)> = vec![];
992        let empty_selection = RowGroupSelection::from_row_ranges(empty_ranges, row_group_size);
993        let intersection = selection1.intersect(&empty_selection);
994        assert_eq!(intersection.row_count(), 0);
995        assert_eq!(intersection.row_group_count(), 0);
996        assert!(intersection.get(0).is_none());
997
998        // Test case 3: No overlapping row groups
999        let non_overlapping_ranges = vec![
1000            (3, vec![0..10]), // Within [0, 50) for last row group
1001        ];
1002        let non_overlapping_selection =
1003            RowGroupSelection::from_row_ranges(non_overlapping_ranges, row_group_size);
1004        let intersection = selection1.intersect(&non_overlapping_selection);
1005        assert_eq!(intersection.row_count(), 0);
1006        assert_eq!(intersection.row_group_count(), 0);
1007        assert!(intersection.get(0).is_none());
1008
1009        // Test case 4: Full overlap within same row group
1010        let full_overlap_ranges1 = vec![
1011            (0, vec![0..50]), // Within [0, 100)
1012        ];
1013        let full_overlap_ranges2 = vec![
1014            (0, vec![0..50]), // Within [0, 100)
1015        ];
1016        let selection1 = RowGroupSelection::from_row_ranges(full_overlap_ranges1, row_group_size);
1017        let selection2 = RowGroupSelection::from_row_ranges(full_overlap_ranges2, row_group_size);
1018        let intersection = selection1.intersect(&selection2);
1019        assert_eq!(intersection.row_count(), 50);
1020        assert_eq!(intersection.row_group_count(), 1);
1021
1022        let row_selection = intersection.get(0).unwrap();
1023        assert_eq!(row_selection.row_count(), 50); // 0..50 (50)
1024
1025        // Test case 5: Partial overlap at row group boundaries
1026        let boundary_ranges1 = vec![
1027            (0, vec![0..10, 90..100]), // Within [0, 100)
1028            (1, vec![0..100]),         // Within [0, 100)
1029        ];
1030        let boundary_ranges2 = vec![
1031            (0, vec![5..15, 95..100]), // Within [0, 100)
1032            (1, vec![50..100]),        // Within [0, 100)
1033        ];
1034        let selection1 = RowGroupSelection::from_row_ranges(boundary_ranges1, row_group_size);
1035        let selection2 = RowGroupSelection::from_row_ranges(boundary_ranges2, row_group_size);
1036        let intersection = selection1.intersect(&selection2);
1037        assert_eq!(intersection.row_count(), 60);
1038        assert_eq!(intersection.row_group_count(), 2);
1039
1040        let row_selection = intersection.get(0).unwrap();
1041        assert_eq!(row_selection.row_count(), 10); // 5..10 (5) + 95..100 (5)
1042
1043        let row_selection = intersection.get(1).unwrap();
1044        assert_eq!(row_selection.row_count(), 50); // 50..100 (50)
1045
1046        // Test case 6: Multiple ranges with complex overlap
1047        let complex_ranges1 = vec![
1048            (0, vec![5..15, 25..35, 45..55]), // Within [0, 100)
1049            (1, vec![10..20, 30..40]),        // Within [0, 100)
1050        ];
1051        let complex_ranges2 = vec![
1052            (0, vec![10..20, 30..40, 50..60]), // Within [0, 100)
1053            (1, vec![15..25, 35..45]),         // Within [0, 100)
1054        ];
1055        let selection1 = RowGroupSelection::from_row_ranges(complex_ranges1, row_group_size);
1056        let selection2 = RowGroupSelection::from_row_ranges(complex_ranges2, row_group_size);
1057        let intersection = selection1.intersect(&selection2);
1058        assert_eq!(intersection.row_count(), 25);
1059        assert_eq!(intersection.row_group_count(), 2);
1060
1061        let row_selection = intersection.get(0).unwrap();
1062        assert_eq!(row_selection.row_count(), 15); // 10..15 (5) + 30..35 (5) + 50..55 (5)
1063
1064        let row_selection = intersection.get(1).unwrap();
1065        assert_eq!(row_selection.row_count(), 10); // 15..20 (5) + 35..40 (5)
1066
1067        // Test case 7: Intersection with last row group (smaller size)
1068        let last_rg_ranges1 = vec![
1069            (2, vec![0..25, 30..40]), // Within [0, 50) for last row group
1070        ];
1071        let last_rg_ranges2 = vec![
1072            (2, vec![20..30, 35..45]), // Within [0, 50) for last row group
1073        ];
1074        let selection1 = RowGroupSelection::from_row_ranges(last_rg_ranges1, row_group_size);
1075        let selection2 = RowGroupSelection::from_row_ranges(last_rg_ranges2, row_group_size);
1076        let intersection = selection1.intersect(&selection2);
1077        assert_eq!(intersection.row_count(), 10);
1078        assert_eq!(intersection.row_group_count(), 1);
1079
1080        let row_selection = intersection.get(2).unwrap();
1081        assert_eq!(row_selection.row_count(), 10); // 20..25 (5) + 35..40 (5)
1082
1083        // Test case 8: Intersection with empty ranges in one selection
1084        let empty_ranges = vec![
1085            (0, vec![]),      // Empty ranges
1086            (1, vec![5..15]), // Within [0, 100)
1087        ];
1088        let selection1 = RowGroupSelection::from_row_ranges(empty_ranges, row_group_size);
1089        let ranges2 = vec![
1090            (0, vec![5..15, 25..35]), // Within [0, 100)
1091            (1, vec![5..15]),         // Within [0, 100)
1092        ];
1093        let selection2 = RowGroupSelection::from_row_ranges(ranges2, row_group_size);
1094        let intersection = selection1.intersect(&selection2);
1095        assert_eq!(intersection.row_count(), 10);
1096        assert_eq!(intersection.row_group_count(), 1);
1097
1098        let row_selection = intersection.get(1).unwrap();
1099        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1100    }
1101
1102    #[test]
1103    fn test_pop_first() {
1104        let row_group_size = 100;
1105        let ranges = vec![
1106            (0, vec![5..15]), // Within [0, 100)
1107            (1, vec![5..15]), // Within [0, 100)
1108            (2, vec![0..5]),  // Within [0, 50) for last row group
1109        ];
1110        let mut selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
1111
1112        // Test popping first row group
1113        let (rg_id, row_selection) = selection.pop_first().unwrap();
1114        assert_eq!(rg_id, 0);
1115        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1116        assert_eq!(selection.row_count(), 15);
1117        assert_eq!(selection.row_group_count(), 2);
1118
1119        // Verify remaining row groups' content
1120        let row_selection = selection.get(1).unwrap();
1121        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1122
1123        let row_selection = selection.get(2).unwrap();
1124        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1125
1126        // Test popping second row group
1127        let (rg_id, row_selection) = selection.pop_first().unwrap();
1128        assert_eq!(rg_id, 1);
1129        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1130        assert_eq!(selection.row_count(), 5);
1131        assert_eq!(selection.row_group_count(), 1);
1132
1133        // Verify remaining row group's content
1134        let row_selection = selection.get(2).unwrap();
1135        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1136
1137        // Test popping last row group
1138        let (rg_id, row_selection) = selection.pop_first().unwrap();
1139        assert_eq!(rg_id, 2);
1140        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1141        assert_eq!(selection.row_count(), 0);
1142        assert_eq!(selection.row_group_count(), 0);
1143        assert!(selection.is_empty());
1144
1145        // Test popping from empty selection
1146        let mut empty_selection = RowGroupSelection::from_row_ranges(vec![], row_group_size);
1147        assert!(empty_selection.pop_first().is_none());
1148        assert_eq!(empty_selection.row_count(), 0);
1149        assert_eq!(empty_selection.row_group_count(), 0);
1150        assert!(empty_selection.is_empty());
1151    }
1152
1153    #[test]
1154    fn test_remove_row_group() {
1155        let row_group_size = 100;
1156        let ranges = vec![
1157            (0, vec![5..15]), // Within [0, 100)
1158            (1, vec![5..15]), // Within [0, 100)
1159            (2, vec![0..5]),  // Within [0, 50) for last row group
1160        ];
1161        let mut selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
1162
1163        // Test removing existing row group
1164        selection.remove_row_group(1);
1165        assert_eq!(selection.row_count(), 15);
1166        assert_eq!(selection.row_group_count(), 2);
1167        assert!(!selection.contains_row_group(1));
1168
1169        // Verify remaining row groups' content
1170        let row_selection = selection.get(0).unwrap();
1171        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1172
1173        let row_selection = selection.get(2).unwrap();
1174        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1175
1176        // Test removing non-existent row group
1177        selection.remove_row_group(5);
1178        assert_eq!(selection.row_count(), 15);
1179        assert_eq!(selection.row_group_count(), 2);
1180
1181        // Test removing all row groups
1182        selection.remove_row_group(0);
1183        assert_eq!(selection.row_count(), 5);
1184        assert_eq!(selection.row_group_count(), 1);
1185
1186        let row_selection = selection.get(2).unwrap();
1187        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1188
1189        selection.remove_row_group(2);
1190        assert_eq!(selection.row_count(), 0);
1191        assert_eq!(selection.row_group_count(), 0);
1192        assert!(selection.is_empty());
1193
1194        // Test removing from empty selection
1195        let mut empty_selection = RowGroupSelection::from_row_ranges(vec![], row_group_size);
1196        empty_selection.remove_row_group(0);
1197        assert_eq!(empty_selection.row_count(), 0);
1198        assert_eq!(empty_selection.row_group_count(), 0);
1199        assert!(empty_selection.is_empty());
1200    }
1201
1202    #[test]
1203    fn test_contains_row_group() {
1204        let row_group_size = 100;
1205        let ranges = vec![
1206            (0, vec![5..15]), // Within [0, 100)
1207            (1, vec![5..15]), // Within [0, 100)
1208        ];
1209        let selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
1210
1211        assert!(selection.contains_row_group(0));
1212        assert!(selection.contains_row_group(1));
1213        assert!(!selection.contains_row_group(2));
1214
1215        // Test empty selection
1216        let empty_selection = RowGroupSelection::from_row_ranges(vec![], row_group_size);
1217        assert!(!empty_selection.contains_row_group(0));
1218    }
1219
1220    #[test]
1221    fn test_concat() {
1222        let row_group_size = 100;
1223        let ranges1 = vec![
1224            (0, vec![5..15]), // Within [0, 100)
1225            (1, vec![5..15]), // Within [0, 100)
1226        ];
1227
1228        let ranges2 = vec![
1229            (2, vec![5..15]), // Within [0, 100)
1230            (3, vec![5..15]), // Within [0, 100)
1231        ];
1232
1233        let mut selection1 = RowGroupSelection::from_row_ranges(ranges1, row_group_size);
1234        let selection2 = RowGroupSelection::from_row_ranges(ranges2, row_group_size);
1235
1236        selection1.concat(&selection2);
1237        assert_eq!(selection1.row_count(), 40);
1238        assert_eq!(selection1.row_group_count(), 4);
1239    }
1240}