Skip to main content

vortex_scan/
selection.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Defines a selection mask over a scan.
5
6use std::ops::Not;
7use std::ops::Range;
8
9use vortex_buffer::BitBufferMut;
10use vortex_error::vortex_panic;
11use vortex_mask::Mask;
12
13use crate::row_mask::RowMask;
14use crate::strict_sorted_buffer::StrictSortedBuffer;
15
16/// A selection identifies a set of rows to include in the scan (in addition to applying any
17/// filter predicates).
18#[derive(Default, Clone, Debug)]
19pub enum Selection {
20    /// No selection, all rows are included.
21    #[default]
22    All,
23    /// A selection of sorted, unique rows to include by index.
24    IncludeByIndex(StrictSortedBuffer<u64>),
25    /// A selection of sorted, unique rows to exclude by index.
26    ExcludeByIndex(StrictSortedBuffer<u64>),
27    /// A selection of rows to include using a [`roaring::RoaringTreemap`].
28    IncludeRoaring(roaring::RoaringTreemap),
29    /// A selection of rows to exclude using a [`roaring::RoaringTreemap`].
30    ExcludeRoaring(roaring::RoaringTreemap),
31}
32
33impl Selection {
34    /// Return whether `index` is included in this selection.
35    pub fn contains(&self, index: u64) -> bool {
36        match self {
37            Selection::All => true,
38            Selection::IncludeByIndex(include) => include.as_slice().binary_search(&index).is_ok(),
39            Selection::ExcludeByIndex(exclude) => exclude.as_slice().binary_search(&index).is_err(),
40            Selection::IncludeRoaring(roaring) => roaring.contains(index),
41            Selection::ExcludeRoaring(roaring) => !roaring.contains(index),
42        }
43    }
44
45    /// Return the row count for this selection.
46    pub fn row_count(&self, total_rows: u64) -> u64 {
47        match self {
48            Selection::All => total_rows,
49            Selection::IncludeByIndex(include) => include.len() as u64,
50            Selection::ExcludeByIndex(exclude) => total_rows.saturating_sub(exclude.len() as u64),
51            Selection::IncludeRoaring(roaring) => roaring.len(),
52            Selection::ExcludeRoaring(roaring) => total_rows.saturating_sub(roaring.len()),
53        }
54    }
55
56    /// Count the selected rows that fall within `range`.
57    pub fn row_count_in_range(&self, range: &Range<u64>) -> u64 {
58        let range_len = range.end.saturating_sub(range.start);
59        match self {
60            Selection::All => range_len,
61            Selection::IncludeByIndex(include) => count_in_range(range, include),
62            Selection::ExcludeByIndex(exclude) => {
63                range_len.saturating_sub(count_in_range(range, exclude))
64            }
65            Selection::IncludeRoaring(roaring) => roaring.range_cardinality(range.clone()),
66            Selection::ExcludeRoaring(roaring) => {
67                range_len.saturating_sub(roaring.range_cardinality(range.clone()))
68            }
69        }
70    }
71
72    /// Extract the [`RowMask`] for the given range from this selection.
73    pub fn row_mask(&self, range: &Range<u64>) -> RowMask {
74        if range.start >= range.end {
75            return RowMask::new(0, Mask::AllFalse(0));
76        }
77
78        // Saturating subtraction to prevent underflow, though range should be valid
79        let range_diff = range.end.saturating_sub(range.start);
80        let range_len = usize::try_from(range_diff).unwrap_or_else(|_| {
81            // If the range is too large for usize, cap it at usize::MAX
82            // This is a defensive measure; in practice, ranges should be reasonable
83            tracing::warn!(
84                "Range length {} exceeds usize::MAX, capping at usize::MAX",
85                range_diff
86            );
87            usize::MAX
88        });
89
90        match self {
91            Selection::All => RowMask::new(range.start, Mask::new_true(range_len)),
92            Selection::IncludeByIndex(include) => {
93                RowMask::new(range.start, index_mask(range, range_len, include))
94            }
95            Selection::ExcludeByIndex(exclude) => {
96                RowMask::new(range.start, index_mask(range, range_len, exclude).not())
97            }
98            Selection::IncludeRoaring(roaring) => {
99                RowMask::new(range.start, roaring_mask(roaring, range, range_len))
100            }
101            Selection::ExcludeRoaring(roaring) => {
102                RowMask::new(range.start, roaring_mask(roaring, range, range_len).not())
103            }
104        }
105    }
106}
107
108/// Build the mask of positions within `range` that are set in `roaring`.
109///
110/// Seeks straight to `range` rather than intersecting the whole treemap, and short-circuits splits
111/// that are entirely outside or inside the selection.
112fn roaring_mask(roaring: &roaring::RoaringTreemap, range: &Range<u64>, range_len: usize) -> Mask {
113    let selected = roaring.range_cardinality(range.clone());
114    if selected == 0 {
115        return Mask::new_false(range_len);
116    }
117
118    if selected == range_len as u64 {
119        return Mask::new_true(range_len);
120    }
121
122    let mut bits = BitBufferMut::new_unset(range_len);
123    let mut iter = roaring.iter();
124    iter.advance_to(range.start);
125    for idx in iter.take_while(|&idx| idx < range.end) {
126        bits.set(relativize(range, idx));
127    }
128
129    Mask::from_buffer(bits.freeze())
130}
131
132/// Count the entries of the sorted `row_indices` that fall within `range`.
133fn count_in_range(range: &Range<u64>, row_indices: &[u64]) -> u64 {
134    indices_range(range, row_indices).map_or(0, |idx_range| idx_range.len() as u64)
135}
136
137/// Build the mask of positions within `range` that are named by the given sorted row indices.
138fn index_mask(range: &Range<u64>, range_len: usize, row_indices: &[u64]) -> Mask {
139    indices_range(range, row_indices)
140        .map(|idx_range| {
141            Mask::from_indices(
142                range_len,
143                row_indices[idx_range]
144                    .iter()
145                    .map(|&idx| relativize(range, idx)),
146            )
147        })
148        .unwrap_or_else(|| Mask::new_false(range_len))
149}
150
151/// Shift an absolute row index to be relative to the start of `range`.
152///
153/// Panics if the index is not a `usize`-sized offset into `range`. Callers have already narrowed
154/// the indices to `range`, whose own length had to fit in a `usize` to size the mask, so a failure
155/// here means that invariant was broken rather than that the index was merely out of bounds.
156fn relativize(range: &Range<u64>, idx: u64) -> usize {
157    idx.checked_sub(range.start)
158        .and_then(|relative| usize::try_from(relative).ok())
159        .unwrap_or_else(|| {
160            vortex_panic!(
161                "index {:?} is not a usize offset into range {:?}",
162                idx,
163                range
164            )
165        })
166}
167
168/// Find the positional range within row_indices that covers all rows in the given range.
169fn indices_range(range: &Range<u64>, row_indices: &[u64]) -> Option<Range<usize>> {
170    if row_indices.first().is_some_and(|&first| first >= range.end)
171        || row_indices.last().is_some_and(|&last| range.start > last)
172    {
173        return None;
174    }
175
176    // For the given row range, find the indices that are within the row_indices.
177    let start_idx = row_indices
178        .binary_search(&range.start)
179        .unwrap_or_else(|x| x);
180    let end_idx = row_indices.binary_search(&range.end).unwrap_or_else(|x| x);
181
182    (start_idx != end_idx).then_some(start_idx..end_idx)
183}
184
185#[cfg(test)]
186mod tests {
187    use vortex_buffer::Buffer;
188
189    use super::Selection;
190    use crate::strict_sorted_buffer::StrictSortedBuffer;
191
192    fn strict_sorted(indices: impl IntoIterator<Item = u64>) -> StrictSortedBuffer<u64> {
193        StrictSortedBuffer::try_new(Buffer::from_iter(indices))
194            .expect("test indices should be strictly increasing")
195    }
196
197    fn include(indices: impl IntoIterator<Item = u64>) -> Selection {
198        Selection::IncludeByIndex(strict_sorted(indices))
199    }
200
201    fn exclude(indices: impl IntoIterator<Item = u64>) -> Selection {
202        Selection::ExcludeByIndex(strict_sorted(indices))
203    }
204
205    #[test]
206    fn test_row_count_in_range() {
207        let range = 2..8;
208        assert_eq!(Selection::All.row_count_in_range(&range), 6);
209        // Indices 3, 5, 7 fall inside the range; 1 and 9 do not.
210        assert_eq!(include([1, 3, 5, 7, 9]).row_count_in_range(&range), 3);
211        assert_eq!(exclude([1, 3, 5, 7, 9]).row_count_in_range(&range), 3);
212        assert_eq!(include([10, 11]).row_count_in_range(&range), 0);
213        assert_eq!(include([1, 3]).row_count_in_range(&(8..8)), 0);
214    }
215
216    #[test]
217    fn test_row_count_in_range_roaring() {
218        let mut roaring = roaring::RoaringTreemap::new();
219        roaring.insert_range(1..10u64);
220
221        let range = 2..8;
222        assert_eq!(
223            Selection::IncludeRoaring(roaring.clone()).row_count_in_range(&range),
224            6
225        );
226        assert_eq!(
227            Selection::ExcludeRoaring(roaring).row_count_in_range(&range),
228            0
229        );
230    }
231
232    #[test]
233    fn test_row_count_in_range_roaring_boundaries() {
234        let roaring = [0, 3, u64::from(u32::MAX) + 1, u64::MAX - 1, u64::MAX]
235            .into_iter()
236            .collect::<roaring::RoaringTreemap>();
237        let include = Selection::IncludeRoaring(roaring.clone());
238        let exclude = Selection::ExcludeRoaring(roaring);
239
240        for (range, expected) in [
241            (0..0, 0),
242            (0..1, 1),
243            (1..3, 0),
244            (3..4, 1),
245            (u64::from(u32::MAX)..u64::from(u32::MAX) + 2, 1),
246            (u64::MAX - 1..u64::MAX, 1),
247            (0..u64::MAX, 4),
248        ] {
249            assert_eq!(include.row_count_in_range(&range), expected);
250            assert_eq!(
251                exclude.row_count_in_range(&range),
252                range.end - range.start - expected
253            );
254        }
255    }
256
257    #[test]
258    fn test_row_mask_all() {
259        let selection = include([1, 3, 5, 7]);
260        let range = 1..8;
261        let row_mask = selection.row_mask(&range);
262
263        assert_eq!(row_mask.mask().values().unwrap().indices(), &[0, 2, 4, 6]);
264    }
265
266    #[test]
267    fn test_row_mask_slice() {
268        let selection = include([1, 3, 5, 7]);
269        let range = 3..6;
270        let row_mask = selection.row_mask(&range);
271
272        assert_eq!(row_mask.mask().values().unwrap().indices(), &[0, 2]);
273    }
274
275    #[test]
276    fn test_row_mask_exclusive() {
277        let selection = include([1, 3, 5, 7]);
278        let range = 3..5;
279        let row_mask = selection.row_mask(&range);
280
281        assert_eq!(row_mask.mask().values().unwrap().indices(), &[0]);
282    }
283
284    #[test]
285    fn test_row_mask_all_false() {
286        let selection = include([1, 3, 5, 7]);
287        let range = 8..10;
288        let row_mask = selection.row_mask(&range);
289
290        assert!(row_mask.mask().all_false());
291    }
292
293    #[test]
294    fn test_row_mask_all_true() {
295        let selection = include([1, 3, 4, 5, 6]);
296        let range = 3..7;
297        let row_mask = selection.row_mask(&range);
298
299        assert!(row_mask.mask().all_true());
300    }
301
302    #[test]
303    fn test_row_mask_zero() {
304        let selection = include([0]);
305        let range = 0..5;
306        let row_mask = selection.row_mask(&range);
307
308        assert_eq!(row_mask.mask().values().unwrap().indices(), &[0]);
309    }
310
311    mod roaring_tests {
312        use roaring::RoaringTreemap;
313
314        use super::*;
315
316        #[test]
317        fn test_roaring_include_basic() {
318            let mut roaring = RoaringTreemap::new();
319            roaring.insert(1);
320            roaring.insert(3);
321            roaring.insert(5);
322            roaring.insert(7);
323
324            let selection = Selection::IncludeRoaring(roaring);
325            let range = 1..8;
326            let row_mask = selection.row_mask(&range);
327
328            assert_eq!(row_mask.mask().values().unwrap().indices(), &[0, 2, 4, 6]);
329        }
330
331        #[test]
332        fn test_roaring_include_slice() {
333            let mut roaring = RoaringTreemap::new();
334            roaring.insert(1);
335            roaring.insert(3);
336            roaring.insert(5);
337            roaring.insert(7);
338
339            let selection = Selection::IncludeRoaring(roaring);
340            let range = 3..6;
341            let row_mask = selection.row_mask(&range);
342
343            assert_eq!(row_mask.mask().values().unwrap().indices(), &[0, 2]);
344        }
345
346        #[test]
347        fn test_roaring_include_disjoint() {
348            let mut roaring = RoaringTreemap::new();
349            roaring.insert(1);
350            roaring.insert(3);
351            roaring.insert(5);
352            roaring.insert(7);
353
354            let selection = Selection::IncludeRoaring(roaring);
355            let range = 8..10;
356            let row_mask = selection.row_mask(&range);
357
358            assert!(row_mask.mask().all_false());
359        }
360
361        #[test]
362        fn test_roaring_include_large_range() {
363            let mut roaring = RoaringTreemap::new();
364            // Insert a large number of indices
365            for i in (0..1000000).step_by(2) {
366                roaring.insert(i);
367            }
368
369            let selection = Selection::IncludeRoaring(roaring);
370            let range = 1000..2000;
371            let row_mask = selection.row_mask(&range);
372
373            assert_eq!(row_mask.row_range(), range);
374            assert_eq!(
375                row_mask.mask().values().unwrap().indices(),
376                &(0..1000).step_by(2).collect::<Vec<_>>()
377            );
378        }
379
380        #[test]
381        fn test_roaring_exclude_basic() {
382            let mut roaring = RoaringTreemap::new();
383            roaring.insert(1);
384            roaring.insert(3);
385            roaring.insert(5);
386
387            let selection = Selection::ExcludeRoaring(roaring);
388            let range = 0..7;
389            let row_mask = selection.row_mask(&range);
390
391            // Should exclude indices 1, 3, 5, so we get 0, 2, 4, 6
392            assert_eq!(row_mask.mask().values().unwrap().indices(), &[0, 2, 4, 6]);
393        }
394
395        #[test]
396        fn test_roaring_exclude_all() {
397            let mut roaring = RoaringTreemap::new();
398            // Exclude all indices in range
399            for i in 10..20 {
400                roaring.insert(i);
401            }
402
403            let selection = Selection::ExcludeRoaring(roaring);
404            let range = 10..20;
405            let row_mask = selection.row_mask(&range);
406
407            assert!(row_mask.mask().all_false());
408        }
409
410        #[test]
411        fn test_roaring_exclude_none() {
412            let mut roaring = RoaringTreemap::new();
413            roaring.insert(100);
414            roaring.insert(101);
415
416            let selection = Selection::ExcludeRoaring(roaring);
417            let range = 0..10;
418            let row_mask = selection.row_mask(&range);
419
420            // Nothing to exclude in this range
421            assert!(row_mask.mask().all_true());
422        }
423
424        #[test]
425        fn test_roaring_exclude_partial() {
426            let mut roaring = RoaringTreemap::new();
427            roaring.insert(5);
428            roaring.insert(6);
429            roaring.insert(7);
430            roaring.insert(15); // Outside range
431
432            let selection = Selection::ExcludeRoaring(roaring);
433            let range = 5..10;
434            let row_mask = selection.row_mask(&range);
435
436            // Should exclude 5, 6, 7 (mapped to 0, 1, 2), keep 8, 9 (mapped to 3, 4)
437            assert_eq!(row_mask.mask().values().unwrap().indices(), &[3, 4]);
438        }
439
440        #[test]
441        fn test_roaring_include_empty() {
442            let roaring = RoaringTreemap::new();
443            let selection = Selection::IncludeRoaring(roaring);
444            let range = 0..100;
445            let row_mask = selection.row_mask(&range);
446
447            assert!(row_mask.mask().all_false());
448        }
449
450        #[test]
451        fn test_roaring_exclude_empty() {
452            let roaring = RoaringTreemap::new();
453            let selection = Selection::ExcludeRoaring(roaring);
454            let range = 0..100;
455            let row_mask = selection.row_mask(&range);
456
457            assert!(row_mask.mask().all_true());
458        }
459
460        #[test]
461        fn test_roaring_include_boundary() {
462            let mut roaring = RoaringTreemap::new();
463            roaring.insert(0);
464            roaring.insert(99);
465
466            let selection = Selection::IncludeRoaring(roaring);
467            let range = 0..100;
468            let row_mask = selection.row_mask(&range);
469
470            assert_eq!(row_mask.mask().values().unwrap().indices(), &[0, 99]);
471        }
472
473        #[test]
474        fn test_roaring_include_range_insertion() {
475            let mut roaring = RoaringTreemap::new();
476            // Use insert_range for efficiency
477            roaring.insert_range(10..20);
478            roaring.insert_range(30..40);
479
480            let selection = Selection::IncludeRoaring(roaring);
481            let range = 15..35;
482            let row_mask = selection.row_mask(&range);
483
484            // Should include 15-19 (mapped to 0-4) and 30-34 (mapped to 15-19)
485            let expected: Vec<usize> = (0..5).chain(15..20).collect();
486            assert_eq!(row_mask.mask().values().unwrap().indices(), &expected);
487        }
488
489        #[test]
490        fn test_roaring_overflow_protection() {
491            let mut roaring = RoaringTreemap::new();
492            // Insert very large indices
493            roaring.insert(u64::MAX - 1);
494            roaring.insert(u64::MAX);
495
496            let selection = Selection::IncludeRoaring(roaring);
497            let range = u64::MAX - 10..u64::MAX;
498            let row_mask = selection.row_mask(&range);
499
500            assert_eq!(row_mask.row_range(), range);
501            assert_eq!(row_mask.mask().values().unwrap().indices(), &[9]);
502        }
503
504        #[test]
505        fn test_roaring_exclude_overflow_protection() {
506            let mut roaring = RoaringTreemap::new();
507            roaring.insert(u64::MAX - 1);
508
509            let selection = Selection::ExcludeRoaring(roaring);
510            let range = u64::MAX - 10..u64::MAX;
511            let row_mask = selection.row_mask(&range);
512
513            assert_eq!(row_mask.row_range(), range);
514            assert_eq!(
515                row_mask.mask().values().unwrap().indices(),
516                &(0..9).collect::<Vec<_>>()
517            );
518        }
519
520        #[test]
521        fn test_roaring_include_vs_buffer_equivalence() {
522            // Test that RoaringTreemap and Buffer produce same results
523            let indices = vec![1, 3, 5, 7, 9];
524
525            let buffer_selection = include(indices.clone());
526
527            let mut roaring = RoaringTreemap::new();
528            for idx in &indices {
529                roaring.insert(*idx);
530            }
531            let roaring_selection = Selection::IncludeRoaring(roaring);
532
533            let range = 0..12;
534            let buffer_mask = buffer_selection.row_mask(&range);
535            let roaring_mask = roaring_selection.row_mask(&range);
536
537            for mask in [buffer_mask, roaring_mask] {
538                assert_eq!(mask.row_range(), range);
539                assert_eq!(mask.mask().values().unwrap().indices(), &[1, 3, 5, 7, 9]);
540            }
541        }
542
543        #[test]
544        fn test_roaring_exclude_vs_buffer_equivalence() {
545            // Test that ExcludeRoaring and ExcludeByIndex produce same results
546            let indices = vec![2, 4, 6, 8];
547
548            let buffer_selection = exclude(indices.clone());
549
550            let mut roaring = RoaringTreemap::new();
551            for idx in &indices {
552                roaring.insert(*idx);
553            }
554            let roaring_selection = Selection::ExcludeRoaring(roaring);
555
556            let range = 0..10;
557            let buffer_mask = buffer_selection.row_mask(&range);
558            let roaring_mask = roaring_selection.row_mask(&range);
559
560            for mask in [buffer_mask, roaring_mask] {
561                assert_eq!(mask.row_range(), range);
562                assert_eq!(mask.mask().values().unwrap().indices(), &[0, 1, 3, 5, 7, 9]);
563            }
564        }
565    }
566}