Skip to main content

vortex_array/arrays/varbin/compute/
cast.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5use vortex_error::vortex_ensure;
6
7use crate::ArrayRef;
8use crate::ExecutionCtx;
9use crate::IntoArray;
10use crate::array::ArrayView;
11use crate::arrays::VarBin;
12use crate::arrays::VarBinArray;
13use crate::arrays::varbin::VarBinArraySlotsExt;
14use crate::dtype::DType;
15use crate::dtype::Nullability;
16use crate::scalar_fn::builtin::cast::CastKernel;
17use crate::scalar_fn::builtin::cast::CastReduce;
18use crate::validity::Validity;
19
20fn build_with_validity(
21    array: ArrayView<'_, VarBin>,
22    new_dtype: DType,
23    new_validity: Validity,
24) -> VortexResult<ArrayRef> {
25    // SAFETY: the offsets and bytes are unchanged from a valid array, and the validity was cast
26    // from the array's own validity, so it has the same length.
27    Ok(unsafe {
28        VarBinArray::new_unchecked_from_handle(
29            array.offsets().clone(),
30            array.bytes_handle().clone(),
31            new_dtype,
32            new_validity,
33        )
34    }
35    .into_array())
36}
37
38impl CastReduce for VarBin {
39    fn cast(array: ArrayView<'_, VarBin>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
40        if !array.dtype().eq_ignore_nullability(dtype) {
41            return Ok(None);
42        }
43
44        let new_nullability = dtype.nullability();
45        let Some(new_validity) = array
46            .validity()?
47            .trivially_cast_nullability(new_nullability, array.len())?
48        else {
49            return Ok(None);
50        };
51        let new_dtype = array.dtype().with_nullability(new_nullability);
52        Ok(Some(build_with_validity(array, new_dtype, new_validity)?))
53    }
54}
55
56impl CastKernel for VarBin {
57    fn cast(
58        array: ArrayView<'_, VarBin>,
59        dtype: &DType,
60        ctx: &mut ExecutionCtx,
61    ) -> VortexResult<Option<ArrayRef>> {
62        if !array.dtype().eq_ignore_nullability(dtype) {
63            return Ok(None);
64        }
65
66        let new_nullability = dtype.nullability();
67        let validity = array.validity()?;
68
69        let new_validity = match new_nullability {
70            Nullability::Nullable => validity.into_nullable(),
71            Nullability::NonNullable => {
72                // `VarBin` does not validate the bytes at null rows, so those bytes can be
73                // invalid UTF-8. `Validity::cast_nullability` uses the statistics of the validity
74                // array, which can come from untrusted input. A forged statistic would then show
75                // unchecked bytes as `Utf8` values. Read the validity values instead.
76                let mask = validity.execute_mask(array.len(), ctx)?;
77
78                vortex_ensure!(
79                    mask.all_true(),
80                    "Cannot cast array with invalid values to non-nullable type."
81                );
82
83                Validity::NonNullable
84            }
85        };
86
87        let new_dtype = array.dtype().with_nullability(new_nullability);
88        Ok(Some(build_with_validity(array, new_dtype, new_validity)?))
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use std::sync::LazyLock;
95
96    use rstest::rstest;
97    use vortex_buffer::Buffer;
98    use vortex_buffer::buffer;
99    use vortex_error::VortexResult;
100    use vortex_session::VortexSession;
101
102    use crate::Canonical;
103    use crate::IntoArray;
104    use crate::VortexSessionExecute;
105    use crate::arrays::BoolArray;
106    use crate::arrays::VarBinArray;
107    use crate::arrays::VarBinViewArray;
108    use crate::assert_arrays_eq;
109    use crate::builtins::ArrayBuiltins;
110    use crate::compute::conformance::cast::test_cast_conformance;
111    use crate::dtype::DType;
112    use crate::dtype::Nullability;
113    use crate::stats::Precision;
114    use crate::stats::Stat;
115    use crate::validity::Validity;
116
117    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
118
119    #[rstest]
120    #[case(
121        DType::Utf8(Nullability::Nullable),
122        DType::Utf8(Nullability::NonNullable)
123    )]
124    #[case(
125        DType::Binary(Nullability::Nullable),
126        DType::Binary(Nullability::NonNullable)
127    )]
128    #[case(
129        DType::Utf8(Nullability::NonNullable),
130        DType::Utf8(Nullability::Nullable)
131    )]
132    #[case(
133        DType::Binary(Nullability::NonNullable),
134        DType::Binary(Nullability::Nullable)
135    )]
136    fn try_cast_varbin_nullable(#[case] source: DType, #[case] target: DType) {
137        let varbin = VarBinArray::from_iter(vec![Some("a"), Some("b"), Some("c")], source);
138
139        let res = varbin.into_array().cast(target.clone());
140        assert_arrays_eq!(
141            res.unwrap(),
142            VarBinViewArray::from_iter([Some("a"), Some("b"), Some("c")], target),
143            &mut SESSION.create_execution_ctx()
144        );
145    }
146
147    #[rstest]
148    #[case(DType::Utf8(Nullability::Nullable))]
149    #[case(DType::Binary(Nullability::Nullable))]
150    fn try_cast_varbin_fail(#[case] source: DType) {
151        // Failure surfaces during execution via the kernel.
152        let non_nullable_source = source.as_nonnullable();
153        let varbin = VarBinArray::from_iter(vec![Some("a"), Some("b"), None], source);
154        let mut ctx = SESSION.create_execution_ctx();
155        let result = varbin
156            .into_array()
157            .cast(non_nullable_source)
158            .and_then(|a| a.execute::<Canonical>(&mut ctx).map(|c| c.into_array()));
159        assert!(result.is_err(), "Expected error, got: {result:?}");
160    }
161
162    #[test]
163    fn cast_to_non_nullable_ignores_forged_min_statistic() -> VortexResult<()> {
164        let mut ctx = SESSION.create_execution_ctx();
165
166        // Only the null row holds bytes that are not valid UTF-8.
167        let values = Buffer::copy_from([b'a', 0xFF, b'b']);
168        let offsets = buffer![0i32, 1, 2, 3].into_array();
169
170        let is_valid = BoolArray::from_iter([true, false, true]).into_array();
171        is_valid.statistics().set(Stat::Min, Precision::exact(true));
172
173        let varbin = VarBinArray::try_new(
174            offsets,
175            values,
176            DType::Utf8(Nullability::Nullable),
177            Validity::Array(is_valid),
178            &mut ctx,
179        )?;
180
181        let result = varbin
182            .into_array()
183            .cast(DType::Utf8(Nullability::NonNullable))
184            .and_then(|a| a.execute::<Canonical>(&mut ctx));
185
186        assert!(result.is_err(), "Expected error, got: {result:?}");
187        Ok(())
188    }
189
190    #[rstest]
191    #[case(VarBinArray::from_iter(vec![Some("hello"), Some("world"), Some("test")], DType::Utf8(Nullability::NonNullable)))]
192    #[case(VarBinArray::from_iter(vec![Some("hello"), None, Some("world")], DType::Utf8(Nullability::Nullable)))]
193    #[case(VarBinArray::from_iter(vec![Some(b"binary".as_slice()), Some(b"data".as_slice())], DType::Binary(Nullability::NonNullable)))]
194    #[case(VarBinArray::from_iter(vec![Some(b"test".as_slice()), None], DType::Binary(Nullability::Nullable)))]
195    #[case(VarBinArray::from_iter(vec![Some("single")], DType::Utf8(Nullability::NonNullable)))]
196    fn test_cast_varbin_conformance(#[case] array: VarBinArray) {
197        test_cast_conformance(&array.into_array(), &mut SESSION.create_execution_ctx());
198    }
199}