Skip to main content

vortex_array/arrays/slice/
take.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::ops::Range;
5
6use num_traits::AsPrimitive;
7use vortex_buffer::Buffer;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10
11use crate::ArrayRef;
12use crate::ArrayVTable;
13use crate::IntoArray;
14use crate::array::ArrayView;
15use crate::arrays::Chunked;
16use crate::arrays::Dict;
17use crate::arrays::PiecewiseSequence;
18use crate::arrays::PrimitiveArray;
19use crate::arrays::Slice;
20use crate::arrays::chunked::ChunkedArrayExt;
21use crate::arrays::dict::TakeExecute;
22use crate::arrays::primitive::PrimitiveArrayExt;
23use crate::arrays::slice::SliceArraySlotsExt;
24use crate::canonical::AnyCanonical;
25use crate::executor::ExecutionCtx;
26use crate::match_each_integer_ptype;
27use crate::optimizer::kernels::ArrayKernelsExt;
28use crate::validity::Validity;
29
30/// A take of at most `1 / SPARSE_TAKE_RATIO` of the rows of a slice reads the child directly.
31///
32/// A take of more rows keeps the slice. Then a kernel that decodes all of its input decodes only
33/// the rows of the slice, not all rows of the child.
34const SPARSE_TAKE_RATIO: usize = 8;
35
36impl TakeExecute for Slice {
37    /// Take rows of the child at the indices moved by the start of the slice.
38    ///
39    /// The slice of an encoded child, such as an array with patches, can cost more than a take of
40    /// a few rows. A file scan gives slices of larger arrays, so a sparse take, such as a random
41    /// batch of rows, does not slice the child.
42    fn take(
43        array: ArrayView<'_, Slice>,
44        indices: &ArrayRef,
45        ctx: &mut ExecutionCtx,
46    ) -> VortexResult<Option<ArrayRef>> {
47        if indices.len().saturating_mul(SPARSE_TAKE_RATIO) > array.as_ref().len() {
48            return Ok(None);
49        }
50
51        // Runs of indices keep their structure only through the slice.
52        if indices.is::<PiecewiseSequence>() {
53            return Ok(None);
54        }
55
56        // A child with no take kernel decodes in full for a take, so it keeps the slice, which
57        // decodes only the rows of the slice.
58        let child = array.child();
59
60        if !supports_take(child, array.slice_range().clone(), ctx)? {
61            return Ok(None);
62        }
63
64        let indices = indices.clone().execute::<PrimitiveArray>(ctx)?;
65        let validity = indices.validity()?;
66
67        // An index past the end of the slice can be in the child, so the indices are checked here.
68        // A null index can have any value, so indices with nulls keep the slice.
69        if !matches!(validity, Validity::NonNullable | Validity::AllValid) {
70            return Ok(None);
71        }
72
73        let len = array.as_ref().len() as u64;
74        let start = array.slice_range().start as u64;
75
76        let moved = match_each_integer_ptype!(indices.ptype(), |T| {
77            shift_indices(indices.as_slice::<T>(), start, len)
78        })?;
79
80        let moved = PrimitiveArray::new(moved, validity).into_array();
81
82        child.take(moved).map(Some)
83    }
84}
85
86fn supports_take(array: &ArrayRef, range: Range<usize>, ctx: &ExecutionCtx) -> VortexResult<bool> {
87    if let Some(chunked) = array.as_opt::<Chunked>() {
88        if chunked.is_empty() || range.is_empty() {
89            return Ok(true);
90        }
91
92        let (first_chunk, first_offset) = chunked.find_chunk_idx(range.start)?;
93        let (last_chunk, last_offset) = chunked.find_chunk_idx(range.end - 1)?;
94
95        for idx in first_chunk..=last_chunk {
96            let chunk = chunked.chunk(idx);
97            let start = if idx == first_chunk { first_offset } else { 0 };
98            let end = if idx == last_chunk {
99                last_offset + 1
100            } else {
101                chunk.len()
102            };
103            if !supports_take(chunk, start..end, ctx)? {
104                return Ok(false);
105            }
106        }
107
108        return Ok(true);
109    }
110
111    Ok(array.is::<AnyCanonical>()
112        || ctx
113            .session()
114            .kernels()
115            .has_execute_parent(Dict.id(), array.encoding_id()))
116}
117
118fn shift_indices<T: AsPrimitive<u64>>(
119    indices: &[T],
120    start: u64,
121    len: u64,
122) -> VortexResult<Buffer<u64>> {
123    indices
124        .iter()
125        .map(|&index| {
126            let index: u64 = index.as_();
127
128            if index >= len {
129                vortex_bail!("take index {index} out of bounds for length {len}");
130            }
131
132            Ok(index + start)
133        })
134        .collect()
135}
136
137#[cfg(test)]
138mod tests {
139    use std::sync::LazyLock;
140
141    use vortex_buffer::Buffer;
142    use vortex_buffer::buffer;
143    use vortex_error::VortexExpect;
144    use vortex_error::VortexResult;
145    use vortex_session::VortexSession;
146
147    use crate::ArrayRef;
148    use crate::Canonical;
149    use crate::IntoArray;
150    use crate::VortexSessionExecute;
151    use crate::arrays::ChunkedArray;
152    use crate::arrays::MaskedArray;
153    use crate::arrays::PrimitiveArray;
154    use crate::arrays::Slice;
155    use crate::arrays::SliceArray;
156    use crate::arrays::dict::TakeExecute;
157    use crate::assert_arrays_eq;
158    use crate::compute::conformance::take::test_take_conformance;
159    use crate::validity::Validity;
160
161    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
162
163    /// A chunked array of 64 rows. A slice of it stays a slice until execution, as the slice of
164    /// an encoded array of a file does.
165    fn child() -> ArrayRef {
166        let rows = |range: std::ops::Range<i32>| {
167            PrimitiveArray::new(
168                range.clone().collect::<Buffer<i32>>(),
169                Validity::from_iter(range.map(|row| row % 7 != 3)),
170            )
171            .into_array()
172        };
173
174        let chunks = vec![rows(0..24), rows(24..64)];
175        let dtype = chunks[0].dtype().clone();
176
177        ChunkedArray::try_new(chunks, dtype)
178            .vortex_expect("chunks have one dtype")
179            .into_array()
180    }
181
182    #[test]
183    fn test_take_slice_reads_child() -> VortexResult<()> {
184        let mut ctx = SESSION.create_execution_ctx();
185        let child = child();
186
187        for range in [0..64, 10..42, 50..64] {
188            let sliced = SliceArray::try_new(child.clone(), range.clone())?.into_array();
189            let flat = child
190                .slice(range)?
191                .execute::<PrimitiveArray>(&mut ctx)?
192                .into_array();
193
194            for indices in [
195                buffer![1u8].into_array(),
196                buffer![3u16, 0, 3].into_array(),
197                PrimitiveArray::from_option_iter([Some(2i64), None, Some(0)]).into_array(),
198            ] {
199                let result = sliced.take(indices.clone())?;
200                assert_arrays_eq!(result, flat.take(indices)?, &mut ctx);
201            }
202        }
203
204        Ok(())
205    }
206
207    /// An index past the end of the slice is an error, also when it is in the child.
208    #[test]
209    fn test_take_slice_out_of_bounds() -> VortexResult<()> {
210        let mut ctx = SESSION.create_execution_ctx();
211        let sliced = SliceArray::try_new(child(), 10..42)?.into_array();
212
213        let result = sliced.take(buffer![0u32, 32].into_array())?;
214        assert!(result.execute::<Canonical>(&mut ctx).is_err());
215
216        Ok(())
217    }
218
219    /// A slice over a chunked child pushes down a sparse take only when every overlapping chunk
220    /// supports take; chunks without a take kernel keep the slice to avoid decoding the whole chunk.
221    #[test]
222    fn test_take_slice_checks_chunk_take_support() -> VortexResult<()> {
223        let mut ctx = SESSION.create_execution_ctx();
224        let no_take_chunk = MaskedArray::try_new(
225            PrimitiveArray::from_iter(0i32..32).into_array(),
226            Validity::AllValid,
227            &mut ctx,
228        )?
229        .into_array();
230        let primitive_chunk =
231            PrimitiveArray::new(Buffer::from_iter(32i32..64), Validity::AllValid).into_array();
232        let dtype = no_take_chunk.dtype().clone();
233        let chunked =
234            ChunkedArray::try_new(vec![no_take_chunk, primitive_chunk], dtype)?.into_array();
235        let sparse_indices = buffer![1u32, 5].into_array();
236
237        let overlaps_no_take = SliceArray::try_new(chunked.clone(), 4..28)?;
238        assert!(
239            Slice::take(overlaps_no_take.as_view(), &sparse_indices, &mut ctx)?.is_none(),
240            "slice overlapping a chunk without a take kernel should keep the slice"
241        );
242
243        let spans_both = SliceArray::try_new(chunked.clone(), 20..52)?;
244        assert!(
245            Slice::take(spans_both.as_view(), &sparse_indices, &mut ctx)?.is_none(),
246            "slice spanning a chunk without a take kernel should keep the slice"
247        );
248
249        let only_primitive = SliceArray::try_new(chunked, 36..60)?;
250        let pushed = Slice::take(only_primitive.as_view(), &sparse_indices, &mut ctx)?;
251        assert!(
252            pushed.is_some(),
253            "slice whose overlapping chunks all support take should push down"
254        );
255        assert_arrays_eq!(
256            pushed.vortex_expect("pushed down take"),
257            PrimitiveArray::new(buffer![37i32, 41], Validity::AllValid).into_array(),
258            &mut ctx
259        );
260
261        Ok(())
262    }
263
264    #[test]
265    fn test_take_slice_conformance() -> VortexResult<()> {
266        let sliced = SliceArray::try_new(child(), 5..60)?.into_array();
267        test_take_conformance(&sliced, &mut SESSION.create_execution_ctx());
268        Ok(())
269    }
270}