Skip to main content

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/// The returned selection intentionally stops at the end of the last matched range and may omit a
558/// trailing `skip` that would extend it to `total_row_count`. That is fine when the selection is
559/// used directly by the parquet reader, which simply stops once the selectors are exhausted.
560///
561/// Note: overlapping ranges are not supported and will result in an incorrect selection.
562pub(crate) fn row_selection_from_row_ranges(
563    row_ranges: impl Iterator<Item = Range<usize>>,
564    total_row_count: usize,
565) -> RowSelection {
566    let (selectors, _) = build_selectors_from_row_ranges(row_ranges, total_row_count);
567    RowSelection::from(selectors)
568}
569
570fn build_selectors_from_row_ranges(
571    row_ranges: impl Iterator<Item = Range<usize>>,
572    total_row_count: usize,
573) -> (Vec<RowSelector>, usize) {
574    let mut selectors: Vec<RowSelector> = Vec::new();
575    let mut last_processed_end = 0;
576
577    for Range { start, end } in row_ranges {
578        let end = end.min(total_row_count);
579        if start > last_processed_end {
580            add_or_merge_selector(&mut selectors, start - last_processed_end, true);
581        }
582
583        add_or_merge_selector(&mut selectors, end - start, false);
584        last_processed_end = end;
585    }
586
587    (selectors, last_processed_end)
588}
589
590/// Converts an iterator of sorted row IDs into a `RowSelection`.
591///
592/// Note: the input iterator must be sorted in ascending order and
593///       contain unique row IDs in the range [0, total_row_count).
594pub(crate) fn row_selection_from_sorted_row_ids(
595    row_ids: impl Iterator<Item = usize>,
596    total_row_count: usize,
597) -> RowSelection {
598    let mut selectors: Vec<RowSelector> = Vec::new();
599    let mut last_processed_end = 0;
600
601    for row_id in row_ids {
602        let start = row_id;
603        let end = start + 1;
604
605        if start > last_processed_end {
606            add_or_merge_selector(&mut selectors, start - last_processed_end, true);
607        }
608
609        add_or_merge_selector(&mut selectors, end - start, false);
610        last_processed_end = end;
611    }
612
613    if last_processed_end < total_row_count {
614        add_or_merge_selector(&mut selectors, total_row_count - last_processed_end, true);
615    }
616
617    RowSelection::from(selectors)
618}
619
620/// Helper function to either add a new `RowSelector` to `selectors` or merge it with the last one
621/// if they are of the same type (both skip or both select).
622fn add_or_merge_selector(selectors: &mut Vec<RowSelector>, count: usize, is_skip: bool) {
623    if let Some(last) = selectors.last_mut() {
624        // Merge with last if both actions are same
625        if last.skip == is_skip {
626            last.row_count += count;
627            return;
628        }
629    }
630    // Add new selector otherwise
631    let new_selector = if is_skip {
632        RowSelector::skip(count)
633    } else {
634        RowSelector::select(count)
635    };
636    selectors.push(new_selector);
637}
638
639/// Returns the length of the selectors in the selection.
640fn selector_len(selection: &RowSelection) -> usize {
641    selection.iter().size_hint().0
642}
643
644#[cfg(test)]
645#[allow(clippy::single_range_in_vec_init)]
646mod tests {
647    use super::*;
648
649    #[test]
650    fn test_selector_len() {
651        let selection = RowSelection::from(vec![RowSelector::skip(5), RowSelector::select(5)]);
652        assert_eq!(selector_len(&selection), 2);
653
654        let selection = RowSelection::from(vec![
655            RowSelector::select(5),
656            RowSelector::skip(5),
657            RowSelector::select(5),
658        ]);
659        assert_eq!(selector_len(&selection), 3);
660
661        let selection = RowSelection::from(vec![]);
662        assert_eq!(selector_len(&selection), 0);
663    }
664
665    #[test]
666    fn test_single_contiguous_range() {
667        let selection = row_selection_from_row_ranges(Some(5..10).into_iter(), 10);
668        let expected = RowSelection::from(vec![RowSelector::skip(5), RowSelector::select(5)]);
669        assert_eq!(selection, expected);
670    }
671
672    #[test]
673    fn test_non_contiguous_ranges() {
674        let ranges = [1..3, 5..8];
675        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10);
676        let expected = RowSelection::from(vec![
677            RowSelector::skip(1),
678            RowSelector::select(2),
679            RowSelector::skip(2),
680            RowSelector::select(3),
681        ]);
682        assert_eq!(selection, expected);
683    }
684
685    #[test]
686    fn test_empty_range() {
687        let ranges = [];
688        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10);
689        let expected = RowSelection::from(vec![]);
690        assert_eq!(selection, expected);
691    }
692
693    #[test]
694    fn test_adjacent_ranges() {
695        let ranges = [1..2, 2..3];
696        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10);
697        let expected = RowSelection::from(vec![RowSelector::skip(1), RowSelector::select(2)]);
698        assert_eq!(selection, expected);
699    }
700
701    #[test]
702    fn test_large_gap_between_ranges() {
703        let ranges = [1..2, 100..101];
704        let selection = row_selection_from_row_ranges(ranges.iter().cloned(), 10240);
705        let expected = RowSelection::from(vec![
706            RowSelector::skip(1),
707            RowSelector::select(1),
708            RowSelector::skip(98),
709            RowSelector::select(1),
710        ]);
711        assert_eq!(selection, expected);
712    }
713
714    #[test]
715    fn test_range_end_over_total_row_count() {
716        let ranges = Some(1..10);
717        let selection = row_selection_from_row_ranges(ranges.into_iter(), 5);
718        let expected = RowSelection::from(vec![RowSelector::skip(1), RowSelector::select(4)]);
719        assert_eq!(selection, expected);
720    }
721
722    #[test]
723    fn test_row_ids_to_selection() {
724        let row_ids = [1, 3, 5, 7, 9].into_iter();
725        let selection = row_selection_from_sorted_row_ids(row_ids, 10);
726        let expected = RowSelection::from(vec![
727            RowSelector::skip(1),
728            RowSelector::select(1),
729            RowSelector::skip(1),
730            RowSelector::select(1),
731            RowSelector::skip(1),
732            RowSelector::select(1),
733            RowSelector::skip(1),
734            RowSelector::select(1),
735            RowSelector::skip(1),
736            RowSelector::select(1),
737        ]);
738        assert_eq!(selection, expected);
739    }
740
741    #[test]
742    fn test_row_ids_to_selection_full() {
743        let row_ids = 0..10;
744        let selection = row_selection_from_sorted_row_ids(row_ids, 10);
745        let expected = RowSelection::from(vec![RowSelector::select(10)]);
746        assert_eq!(selection, expected);
747    }
748
749    #[test]
750    fn test_row_ids_to_selection_empty() {
751        let selection = row_selection_from_sorted_row_ids(None.into_iter(), 10);
752        let expected = RowSelection::from(vec![RowSelector::skip(10)]);
753        assert_eq!(selection, expected);
754    }
755
756    #[test]
757    fn test_group_row_ids() {
758        let row_ids = [0, 1, 2, 5, 6, 7, 8, 12].into_iter().collect();
759        let row_group_size = 5;
760        let num_row_groups = 3;
761
762        let row_group_to_row_ids =
763            RowGroupSelection::group_row_ids_by_row_group(row_ids, row_group_size, num_row_groups);
764
765        assert_eq!(
766            row_group_to_row_ids,
767            vec![(0, vec![0, 1, 2]), (1, vec![0, 1, 2, 3]), (2, vec![2])]
768        );
769    }
770
771    #[test]
772    fn test_row_group_selection_new() {
773        // Test with regular case
774        let selection = RowGroupSelection::new(100, 250);
775        assert_eq!(selection.row_count(), 250);
776        assert_eq!(selection.row_group_count(), 3);
777
778        // Check content of each row group
779        let row_selection = selection.get(0).unwrap();
780        assert_eq!(row_selection.row_count(), 100);
781
782        let row_selection = selection.get(1).unwrap();
783        assert_eq!(row_selection.row_count(), 100);
784
785        let row_selection = selection.get(2).unwrap();
786        assert_eq!(row_selection.row_count(), 50);
787
788        // Test with empty selection
789        let selection = RowGroupSelection::new(100, 0);
790        assert_eq!(selection.row_count(), 0);
791        assert_eq!(selection.row_group_count(), 0);
792        assert!(selection.get(0).is_none());
793
794        // Test with single row group
795        let selection = RowGroupSelection::new(100, 50);
796        assert_eq!(selection.row_count(), 50);
797        assert_eq!(selection.row_group_count(), 1);
798
799        let row_selection = selection.get(0).unwrap();
800        assert_eq!(row_selection.row_count(), 50);
801
802        // Test with row count that doesn't divide evenly
803        let selection = RowGroupSelection::new(100, 150);
804        assert_eq!(selection.row_count(), 150);
805        assert_eq!(selection.row_group_count(), 2);
806
807        let row_selection = selection.get(0).unwrap();
808        assert_eq!(row_selection.row_count(), 100);
809
810        let row_selection = selection.get(1).unwrap();
811        assert_eq!(row_selection.row_count(), 50);
812
813        // Test with row count that's just over a multiple of row_group_size
814        let selection = RowGroupSelection::new(100, 101);
815        assert_eq!(selection.row_count(), 101);
816        assert_eq!(selection.row_group_count(), 2);
817
818        let row_selection = selection.get(0).unwrap();
819        assert_eq!(row_selection.row_count(), 100);
820
821        let row_selection = selection.get(1).unwrap();
822        assert_eq!(row_selection.row_count(), 1);
823    }
824
825    #[test]
826    fn test_from_full_row_group_ids_dedup_duplicates() {
827        let selection = RowGroupSelection::from_full_row_group_ids([0, 0, 2, 2], 10, 25);
828        assert_eq!(selection.row_group_count(), 2);
829        assert_eq!(selection.row_count(), 15);
830
831        assert_eq!(selection.get(0).unwrap().row_count(), 10);
832        assert_eq!(selection.get(2).unwrap().row_count(), 5);
833    }
834
835    #[test]
836    fn test_from_row_ids() {
837        let row_group_size = 100;
838        let num_row_groups = 3;
839
840        // Test with regular case
841        let row_ids: BTreeSet<u32> = vec![5, 15, 25, 35, 105, 115, 205, 215]
842            .into_iter()
843            .collect();
844        let selection = RowGroupSelection::from_row_ids(row_ids, row_group_size, num_row_groups);
845        assert_eq!(selection.row_count(), 8);
846        assert_eq!(selection.row_group_count(), 3);
847
848        // Check content of each row group
849        let row_selection = selection.get(0).unwrap();
850        assert_eq!(row_selection.row_count(), 4); // 5, 15, 25, 35
851
852        let row_selection = selection.get(1).unwrap();
853        assert_eq!(row_selection.row_count(), 2); // 105, 115
854
855        let row_selection = selection.get(2).unwrap();
856        assert_eq!(row_selection.row_count(), 2); // 205, 215
857
858        // Test with empty row IDs
859        let empty_row_ids: BTreeSet<u32> = BTreeSet::new();
860        let selection =
861            RowGroupSelection::from_row_ids(empty_row_ids, row_group_size, num_row_groups);
862        assert_eq!(selection.row_count(), 0);
863        assert_eq!(selection.row_group_count(), 3);
864
865        // Test with consecutive row IDs
866        let consecutive_row_ids: BTreeSet<u32> = vec![5, 6, 7, 8, 9].into_iter().collect();
867        let selection =
868            RowGroupSelection::from_row_ids(consecutive_row_ids, row_group_size, num_row_groups);
869        assert_eq!(selection.row_count(), 5);
870        assert_eq!(selection.row_group_count(), 3);
871
872        let row_selection = selection.get(0).unwrap();
873        assert_eq!(row_selection.row_count(), 5); // 5, 6, 7, 8, 9
874
875        // Test with row IDs at row group boundaries
876        let boundary_row_ids: BTreeSet<u32> = vec![0, 99, 100, 199, 200, 249].into_iter().collect();
877        let selection =
878            RowGroupSelection::from_row_ids(boundary_row_ids, row_group_size, num_row_groups);
879        assert_eq!(selection.row_count(), 6);
880        assert_eq!(selection.row_group_count(), 3);
881
882        let row_selection = selection.get(0).unwrap();
883        assert_eq!(row_selection.row_count(), 2); // 0, 99
884
885        let row_selection = selection.get(1).unwrap();
886        assert_eq!(row_selection.row_count(), 2); // 100, 199
887
888        let row_selection = selection.get(2).unwrap();
889        assert_eq!(row_selection.row_count(), 2); // 200, 249
890
891        // Test with single row group
892        let single_group_row_ids: BTreeSet<u32> = vec![5, 10, 15].into_iter().collect();
893        let selection = RowGroupSelection::from_row_ids(single_group_row_ids, row_group_size, 1);
894        assert_eq!(selection.row_count(), 3);
895        assert_eq!(selection.row_group_count(), 1);
896
897        let row_selection = selection.get(0).unwrap();
898        assert_eq!(row_selection.row_count(), 3); // 5, 10, 15
899    }
900
901    #[test]
902    fn test_from_row_ranges() {
903        let row_group_size = 100;
904
905        // Test with regular case
906        let ranges = vec![
907            (0, vec![5..15, 25..35]), // Within [0, 100)
908            (1, vec![5..15]),         // Within [0, 100)
909            (2, vec![0..5, 10..15]),  // Within [0, 50) for last row group
910        ];
911        let selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
912        assert_eq!(selection.row_count(), 40);
913        assert_eq!(selection.row_group_count(), 3);
914
915        // Check content of each row group
916        let row_selection = selection.get(0).unwrap();
917        assert_eq!(row_selection.row_count(), 20); // 5..15 (10) + 25..35 (10)
918
919        let row_selection = selection.get(1).unwrap();
920        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
921
922        let row_selection = selection.get(2).unwrap();
923        assert_eq!(row_selection.row_count(), 10); // 0..5 (5) + 10..15 (5)
924
925        // Test with empty ranges
926        let empty_ranges: Vec<(usize, Vec<Range<usize>>)> = vec![];
927        let selection = RowGroupSelection::from_row_ranges(empty_ranges, row_group_size);
928        assert_eq!(selection.row_count(), 0);
929        assert_eq!(selection.row_group_count(), 0);
930        assert!(selection.get(0).is_none());
931
932        // Test with adjacent ranges within same row group
933        let adjacent_ranges = vec![
934            (0, vec![5..15, 15..25]), // Adjacent ranges within [0, 100)
935        ];
936        let selection = RowGroupSelection::from_row_ranges(adjacent_ranges, row_group_size);
937        assert_eq!(selection.row_count(), 20);
938        assert_eq!(selection.row_group_count(), 1);
939
940        let row_selection = selection.get(0).unwrap();
941        assert_eq!(row_selection.row_count(), 20); // 5..15 (10) + 15..25 (10)
942
943        // Test with ranges at row group boundaries
944        let boundary_ranges = vec![
945            (0, vec![0..10, 90..100]), // Ranges at start and end of first row group
946            (1, vec![0..100]),         // Full range of second row group
947            (2, vec![0..50]),          // Full range of last row group
948        ];
949        let selection = RowGroupSelection::from_row_ranges(boundary_ranges, row_group_size);
950        assert_eq!(selection.row_count(), 170);
951        assert_eq!(selection.row_group_count(), 3);
952
953        let row_selection = selection.get(0).unwrap();
954        assert_eq!(row_selection.row_count(), 20); // 0..10 (10) + 90..100 (10)
955
956        let row_selection = selection.get(1).unwrap();
957        assert_eq!(row_selection.row_count(), 100); // 0..100 (100)
958
959        let row_selection = selection.get(2).unwrap();
960        assert_eq!(row_selection.row_count(), 50); // 0..50 (50)
961
962        // Test with single row group
963        let single_group_ranges = vec![
964            (0, vec![0..50]), // Half of first row group
965        ];
966        let selection = RowGroupSelection::from_row_ranges(single_group_ranges, row_group_size);
967        assert_eq!(selection.row_count(), 50);
968        assert_eq!(selection.row_group_count(), 1);
969
970        let row_selection = selection.get(0).unwrap();
971        assert_eq!(row_selection.row_count(), 50); // 0..50 (50)
972    }
973
974    #[test]
975    fn test_intersect() {
976        let row_group_size = 100;
977
978        // Test case 1: Regular intersection with partial overlap
979        let ranges1 = vec![
980            (0, vec![5..15, 25..35]), // Within [0, 100)
981            (1, vec![5..15]),         // Within [0, 100)
982        ];
983        let selection1 = RowGroupSelection::from_row_ranges(ranges1, row_group_size);
984
985        let ranges2 = vec![
986            (0, vec![10..20]), // Within [0, 100)
987            (1, vec![10..20]), // Within [0, 100)
988            (2, vec![0..10]),  // Within [0, 50) for last row group
989        ];
990        let selection2 = RowGroupSelection::from_row_ranges(ranges2, row_group_size);
991
992        let intersection = selection1.intersect(&selection2);
993        assert_eq!(intersection.row_count(), 10);
994        assert_eq!(intersection.row_group_count(), 2);
995
996        let row_selection = intersection.get(0).unwrap();
997        assert_eq!(row_selection.row_count(), 5); // 10..15 (5)
998
999        let row_selection = intersection.get(1).unwrap();
1000        assert_eq!(row_selection.row_count(), 5); // 10..15 (5)
1001
1002        // Test case 2: Empty intersection with empty selection
1003        let empty_ranges: Vec<(usize, Vec<Range<usize>>)> = vec![];
1004        let empty_selection = RowGroupSelection::from_row_ranges(empty_ranges, row_group_size);
1005        let intersection = selection1.intersect(&empty_selection);
1006        assert_eq!(intersection.row_count(), 0);
1007        assert_eq!(intersection.row_group_count(), 0);
1008        assert!(intersection.get(0).is_none());
1009
1010        // Test case 3: No overlapping row groups
1011        let non_overlapping_ranges = vec![
1012            (3, vec![0..10]), // Within [0, 50) for last row group
1013        ];
1014        let non_overlapping_selection =
1015            RowGroupSelection::from_row_ranges(non_overlapping_ranges, row_group_size);
1016        let intersection = selection1.intersect(&non_overlapping_selection);
1017        assert_eq!(intersection.row_count(), 0);
1018        assert_eq!(intersection.row_group_count(), 0);
1019        assert!(intersection.get(0).is_none());
1020
1021        // Test case 4: Full overlap within same row group
1022        let full_overlap_ranges1 = vec![
1023            (0, vec![0..50]), // Within [0, 100)
1024        ];
1025        let full_overlap_ranges2 = vec![
1026            (0, vec![0..50]), // Within [0, 100)
1027        ];
1028        let selection1 = RowGroupSelection::from_row_ranges(full_overlap_ranges1, row_group_size);
1029        let selection2 = RowGroupSelection::from_row_ranges(full_overlap_ranges2, row_group_size);
1030        let intersection = selection1.intersect(&selection2);
1031        assert_eq!(intersection.row_count(), 50);
1032        assert_eq!(intersection.row_group_count(), 1);
1033
1034        let row_selection = intersection.get(0).unwrap();
1035        assert_eq!(row_selection.row_count(), 50); // 0..50 (50)
1036
1037        // Test case 5: Partial overlap at row group boundaries
1038        let boundary_ranges1 = vec![
1039            (0, vec![0..10, 90..100]), // Within [0, 100)
1040            (1, vec![0..100]),         // Within [0, 100)
1041        ];
1042        let boundary_ranges2 = vec![
1043            (0, vec![5..15, 95..100]), // Within [0, 100)
1044            (1, vec![50..100]),        // Within [0, 100)
1045        ];
1046        let selection1 = RowGroupSelection::from_row_ranges(boundary_ranges1, row_group_size);
1047        let selection2 = RowGroupSelection::from_row_ranges(boundary_ranges2, row_group_size);
1048        let intersection = selection1.intersect(&selection2);
1049        assert_eq!(intersection.row_count(), 60);
1050        assert_eq!(intersection.row_group_count(), 2);
1051
1052        let row_selection = intersection.get(0).unwrap();
1053        assert_eq!(row_selection.row_count(), 10); // 5..10 (5) + 95..100 (5)
1054
1055        let row_selection = intersection.get(1).unwrap();
1056        assert_eq!(row_selection.row_count(), 50); // 50..100 (50)
1057
1058        // Test case 6: Multiple ranges with complex overlap
1059        let complex_ranges1 = vec![
1060            (0, vec![5..15, 25..35, 45..55]), // Within [0, 100)
1061            (1, vec![10..20, 30..40]),        // Within [0, 100)
1062        ];
1063        let complex_ranges2 = vec![
1064            (0, vec![10..20, 30..40, 50..60]), // Within [0, 100)
1065            (1, vec![15..25, 35..45]),         // Within [0, 100)
1066        ];
1067        let selection1 = RowGroupSelection::from_row_ranges(complex_ranges1, row_group_size);
1068        let selection2 = RowGroupSelection::from_row_ranges(complex_ranges2, row_group_size);
1069        let intersection = selection1.intersect(&selection2);
1070        assert_eq!(intersection.row_count(), 25);
1071        assert_eq!(intersection.row_group_count(), 2);
1072
1073        let row_selection = intersection.get(0).unwrap();
1074        assert_eq!(row_selection.row_count(), 15); // 10..15 (5) + 30..35 (5) + 50..55 (5)
1075
1076        let row_selection = intersection.get(1).unwrap();
1077        assert_eq!(row_selection.row_count(), 10); // 15..20 (5) + 35..40 (5)
1078
1079        // Test case 7: Intersection with last row group (smaller size)
1080        let last_rg_ranges1 = vec![
1081            (2, vec![0..25, 30..40]), // Within [0, 50) for last row group
1082        ];
1083        let last_rg_ranges2 = vec![
1084            (2, vec![20..30, 35..45]), // Within [0, 50) for last row group
1085        ];
1086        let selection1 = RowGroupSelection::from_row_ranges(last_rg_ranges1, row_group_size);
1087        let selection2 = RowGroupSelection::from_row_ranges(last_rg_ranges2, row_group_size);
1088        let intersection = selection1.intersect(&selection2);
1089        assert_eq!(intersection.row_count(), 10);
1090        assert_eq!(intersection.row_group_count(), 1);
1091
1092        let row_selection = intersection.get(2).unwrap();
1093        assert_eq!(row_selection.row_count(), 10); // 20..25 (5) + 35..40 (5)
1094
1095        // Test case 8: Intersection with empty ranges in one selection
1096        let empty_ranges = vec![
1097            (0, vec![]),      // Empty ranges
1098            (1, vec![5..15]), // Within [0, 100)
1099        ];
1100        let selection1 = RowGroupSelection::from_row_ranges(empty_ranges, row_group_size);
1101        let ranges2 = vec![
1102            (0, vec![5..15, 25..35]), // Within [0, 100)
1103            (1, vec![5..15]),         // Within [0, 100)
1104        ];
1105        let selection2 = RowGroupSelection::from_row_ranges(ranges2, row_group_size);
1106        let intersection = selection1.intersect(&selection2);
1107        assert_eq!(intersection.row_count(), 10);
1108        assert_eq!(intersection.row_group_count(), 1);
1109
1110        let row_selection = intersection.get(1).unwrap();
1111        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1112    }
1113
1114    #[test]
1115    fn test_pop_first() {
1116        let row_group_size = 100;
1117        let ranges = vec![
1118            (0, vec![5..15]), // Within [0, 100)
1119            (1, vec![5..15]), // Within [0, 100)
1120            (2, vec![0..5]),  // Within [0, 50) for last row group
1121        ];
1122        let mut selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
1123
1124        // Test popping first row group
1125        let (rg_id, row_selection) = selection.pop_first().unwrap();
1126        assert_eq!(rg_id, 0);
1127        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1128        assert_eq!(selection.row_count(), 15);
1129        assert_eq!(selection.row_group_count(), 2);
1130
1131        // Verify remaining row groups' content
1132        let row_selection = selection.get(1).unwrap();
1133        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1134
1135        let row_selection = selection.get(2).unwrap();
1136        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1137
1138        // Test popping second row group
1139        let (rg_id, row_selection) = selection.pop_first().unwrap();
1140        assert_eq!(rg_id, 1);
1141        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1142        assert_eq!(selection.row_count(), 5);
1143        assert_eq!(selection.row_group_count(), 1);
1144
1145        // Verify remaining row group's content
1146        let row_selection = selection.get(2).unwrap();
1147        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1148
1149        // Test popping last row group
1150        let (rg_id, row_selection) = selection.pop_first().unwrap();
1151        assert_eq!(rg_id, 2);
1152        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1153        assert_eq!(selection.row_count(), 0);
1154        assert_eq!(selection.row_group_count(), 0);
1155        assert!(selection.is_empty());
1156
1157        // Test popping from empty selection
1158        let mut empty_selection = RowGroupSelection::from_row_ranges(vec![], row_group_size);
1159        assert!(empty_selection.pop_first().is_none());
1160        assert_eq!(empty_selection.row_count(), 0);
1161        assert_eq!(empty_selection.row_group_count(), 0);
1162        assert!(empty_selection.is_empty());
1163    }
1164
1165    #[test]
1166    fn test_remove_row_group() {
1167        let row_group_size = 100;
1168        let ranges = vec![
1169            (0, vec![5..15]), // Within [0, 100)
1170            (1, vec![5..15]), // Within [0, 100)
1171            (2, vec![0..5]),  // Within [0, 50) for last row group
1172        ];
1173        let mut selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
1174
1175        // Test removing existing row group
1176        selection.remove_row_group(1);
1177        assert_eq!(selection.row_count(), 15);
1178        assert_eq!(selection.row_group_count(), 2);
1179        assert!(!selection.contains_row_group(1));
1180
1181        // Verify remaining row groups' content
1182        let row_selection = selection.get(0).unwrap();
1183        assert_eq!(row_selection.row_count(), 10); // 5..15 (10)
1184
1185        let row_selection = selection.get(2).unwrap();
1186        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1187
1188        // Test removing non-existent row group
1189        selection.remove_row_group(5);
1190        assert_eq!(selection.row_count(), 15);
1191        assert_eq!(selection.row_group_count(), 2);
1192
1193        // Test removing all row groups
1194        selection.remove_row_group(0);
1195        assert_eq!(selection.row_count(), 5);
1196        assert_eq!(selection.row_group_count(), 1);
1197
1198        let row_selection = selection.get(2).unwrap();
1199        assert_eq!(row_selection.row_count(), 5); // 0..5 (5)
1200
1201        selection.remove_row_group(2);
1202        assert_eq!(selection.row_count(), 0);
1203        assert_eq!(selection.row_group_count(), 0);
1204        assert!(selection.is_empty());
1205
1206        // Test removing from empty selection
1207        let mut empty_selection = RowGroupSelection::from_row_ranges(vec![], row_group_size);
1208        empty_selection.remove_row_group(0);
1209        assert_eq!(empty_selection.row_count(), 0);
1210        assert_eq!(empty_selection.row_group_count(), 0);
1211        assert!(empty_selection.is_empty());
1212    }
1213
1214    #[test]
1215    fn test_contains_row_group() {
1216        let row_group_size = 100;
1217        let ranges = vec![
1218            (0, vec![5..15]), // Within [0, 100)
1219            (1, vec![5..15]), // Within [0, 100)
1220        ];
1221        let selection = RowGroupSelection::from_row_ranges(ranges, row_group_size);
1222
1223        assert!(selection.contains_row_group(0));
1224        assert!(selection.contains_row_group(1));
1225        assert!(!selection.contains_row_group(2));
1226
1227        // Test empty selection
1228        let empty_selection = RowGroupSelection::from_row_ranges(vec![], row_group_size);
1229        assert!(!empty_selection.contains_row_group(0));
1230    }
1231
1232    #[test]
1233    fn test_concat() {
1234        let row_group_size = 100;
1235        let ranges1 = vec![
1236            (0, vec![5..15]), // Within [0, 100)
1237            (1, vec![5..15]), // Within [0, 100)
1238        ];
1239
1240        let ranges2 = vec![
1241            (2, vec![5..15]), // Within [0, 100)
1242            (3, vec![5..15]), // Within [0, 100)
1243        ];
1244
1245        let mut selection1 = RowGroupSelection::from_row_ranges(ranges1, row_group_size);
1246        let selection2 = RowGroupSelection::from_row_ranges(ranges2, row_group_size);
1247
1248        selection1.concat(&selection2);
1249        assert_eq!(selection1.row_count(), 40);
1250        assert_eq!(selection1.row_group_count(), 4);
1251    }
1252}