Skip to main content

vortex_array/arrays/decimal/compute/
rules.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::ops::Range;
5
6use vortex_error::VortexResult;
7use vortex_session::VortexSession;
8
9use crate::ArrayRef;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::arrays::Decimal;
13use crate::arrays::DecimalArray;
14use crate::arrays::Masked;
15use crate::arrays::Slice;
16use crate::arrays::slice::SliceReduce;
17use crate::arrays::slice::SliceReduceAdaptor;
18use crate::match_each_decimal_value_type;
19use crate::optimizer::kernels::ArrayKernelsExt;
20use crate::optimizer::rules::ArrayParentReduceRule;
21use crate::scalar_fn::builtin::cast::Cast;
22use crate::scalar_fn::builtin::cast::CastReduceAdaptor;
23use crate::scalar_fn::builtin::mask::Mask as MaskFn;
24use crate::scalar_fn::builtin::mask::MaskReduceAdaptor;
25
26pub(crate) fn register_parent_rules(session: &VortexSession) {
27    let kernels = session.kernels();
28    kernels.register_reduce_parent_rule(Masked, Decimal, const { &DecimalMaskedValidityRule });
29    kernels.register_reduce_parent_rule(Cast, Decimal, const { &CastReduceAdaptor(Decimal) });
30    kernels.register_reduce_parent_rule(MaskFn, Decimal, const { &MaskReduceAdaptor(Decimal) });
31    kernels.register_reduce_parent_rule(Slice, Decimal, const { &SliceReduceAdaptor(Decimal) });
32}
33
34/// Rule to push down validity masking from MaskedArray parent into DecimalArray child.
35///
36/// When a DecimalArray is wrapped by a MaskedArray, this rule merges the mask's validity
37/// with the DecimalArray's existing validity, eliminating the need for the MaskedArray wrapper.
38#[derive(Default, Debug)]
39pub struct DecimalMaskedValidityRule;
40
41impl ArrayParentReduceRule<Decimal> for DecimalMaskedValidityRule {
42    type Parent = Masked;
43
44    fn reduce_parent(
45        &self,
46        array: ArrayView<'_, Decimal>,
47        parent: ArrayView<'_, Masked>,
48        _child_idx: usize,
49    ) -> VortexResult<Option<ArrayRef>> {
50        // Merge the parent's validity mask into the child's validity
51        // TODO(joe): make this lazy
52        let masked_array = match_each_decimal_value_type!(array.values_type(), |D| {
53            // SAFETY: Since we are only flipping some bits in the validity, all invariants that
54            // were upheld are still upheld.
55            unsafe {
56                DecimalArray::new_unchecked(
57                    array.buffer::<D>(),
58                    array.decimal_dtype(),
59                    array.validity()?.and(parent.validity()?)?,
60                )
61            }
62            .into_array()
63        });
64
65        Ok(Some(masked_array))
66    }
67}
68
69impl SliceReduce for Decimal {
70    fn slice(array: ArrayView<'_, Self>, range: Range<usize>) -> VortexResult<Option<ArrayRef>> {
71        let byte_width = array.values_type().byte_width();
72        let byte_range = range.start * byte_width..range.end * byte_width;
73        let values = array.buffer_handle().slice(byte_range);
74        let validity = array.validity()?.slice(range)?;
75
76        // SAFETY: Slicing on element boundaries preserves the buffer alignment, values type,
77        // decimal precision and scale, and validity length invariants.
78        let result = unsafe {
79            DecimalArray::new_unchecked_handle(
80                values,
81                array.values_type(),
82                array.decimal_dtype(),
83                validity,
84            )
85            .into_array()
86        };
87        Ok(Some(result))
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use std::any::Any;
94    use std::ops::Range;
95    use std::sync::Arc;
96    use std::sync::LazyLock;
97
98    use futures::future::BoxFuture;
99    use num_traits::AsPrimitive;
100    use rstest::rstest;
101    use vortex_buffer::Alignment;
102    use vortex_buffer::Buffer;
103    use vortex_buffer::ByteBuffer;
104    use vortex_error::VortexResult;
105    use vortex_error::vortex_bail;
106    use vortex_error::vortex_err;
107    use vortex_session::VortexSession;
108
109    use crate::IntoArray;
110    use crate::VortexSessionExecute;
111    use crate::arrays::Decimal;
112    use crate::arrays::DecimalArray;
113    use crate::assert_arrays_eq;
114    use crate::buffer::BufferHandle;
115    use crate::buffer::DeviceBuffer;
116    use crate::dtype::DecimalDType;
117    use crate::match_each_decimal_value_type;
118    use crate::optimizer::ArrayOptimizer;
119    use crate::validity::Validity;
120
121    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
122
123    // Host-backed storage exposes device slicing without allowing implicit host copies.
124    #[derive(Debug, PartialEq, Eq, Hash)]
125    struct TestDeviceBuffer(ByteBuffer);
126
127    impl DeviceBuffer for TestDeviceBuffer {
128        fn as_any(&self) -> &dyn Any {
129            self
130        }
131
132        fn len(&self) -> usize {
133            self.0.len()
134        }
135
136        fn alignment(&self) -> Alignment {
137            self.0.alignment()
138        }
139
140        fn copy_to_host_sync(&self, _alignment: Alignment) -> VortexResult<ByteBuffer> {
141            vortex_bail!("decimal slicing must not copy device values to the host")
142        }
143
144        fn copy_to_host(
145            &self,
146            _alignment: Alignment,
147        ) -> VortexResult<BoxFuture<'static, VortexResult<ByteBuffer>>> {
148            vortex_bail!("decimal slicing must not copy device values to the host")
149        }
150
151        fn slice(&self, range: Range<usize>) -> Arc<dyn DeviceBuffer> {
152            Arc::new(Self(self.0.slice(range)))
153        }
154
155        fn aligned(self: Arc<Self>, alignment: Alignment) -> VortexResult<Arc<dyn DeviceBuffer>> {
156            assert!(self.alignment().is_aligned_to(alignment));
157            Ok(self)
158        }
159    }
160
161    // Exercise composed byte offsets at every storage width without allowing a host copy.
162    #[rstest]
163    fn test_slice_buffer_handle(#[values(2, 4, 9, 18, 38, 76)] precision: u8) -> VortexResult<()> {
164        let mut ctx = SESSION.create_execution_ctx();
165        let dtype = DecimalDType::new(precision, 1);
166        let values_type = dtype.canonical_values_type();
167        let bytes = match_each_decimal_value_type!(values_type, |D| {
168            Buffer::<D>::from_iter([-12i8, 34, -56, 78, 90, 12].map(|value| value.as_()))
169                .into_byte_buffer()
170        });
171        let handle = BufferHandle::new_device(Arc::new(TestDeviceBuffer(bytes.clone())));
172        let validity = Validity::from_iter([true, false, true, false, true, true]);
173        let array =
174            DecimalArray::try_new_handle(handle, values_type, dtype, validity.clone(), &mut ctx)?
175                .into_array();
176        let sliced = array.slice(1..5)?;
177
178        let range = 1..3;
179        let nested = sliced.slice(range.clone())?.optimize_ctx(&SESSION)?;
180        let decimal = nested.as_::<Decimal>();
181        let byte_width = values_type.byte_width();
182        let original_range = range.start + 1..range.end + 1;
183        let expected_bytes =
184            bytes.slice(original_range.start * byte_width..original_range.end * byte_width);
185        let handle = decimal.buffer_handle();
186
187        assert_eq!(nested.len(), range.len());
188        assert_eq!(nested.dtype(), array.dtype());
189        assert_eq!(decimal.values_type(), values_type);
190        assert_eq!(handle.len(), range.len() * byte_width);
191        assert!(handle.is_on_device());
192        assert!(handle.is_aligned_to(bytes.alignment()));
193
194        let actual_bytes = &handle
195            .as_device()
196            .as_any()
197            .downcast_ref::<TestDeviceBuffer>()
198            .ok_or_else(|| vortex_err!("expected TestDeviceBuffer"))?
199            .0;
200        assert_eq!(actual_bytes, &expected_bytes);
201        assert_eq!(actual_bytes.as_ptr(), expected_bytes.as_ptr());
202        assert_arrays_eq!(
203            decimal.validity()?.to_array(nested.len()),
204            validity.to_array(array.len()).slice(original_range)?,
205            &mut ctx
206        );
207
208        Ok(())
209    }
210}