Skip to main content

vortex_array/arrays/dict/compute/
cast.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5
6use super::Dict;
7use super::DictArray;
8use crate::ArrayRef;
9use crate::IntoArray;
10use crate::array::ArrayView;
11use crate::arrays::dict::DictArrayExt;
12use crate::arrays::dict::DictArraySlotsExt;
13use crate::builtins::ArrayBuiltins;
14use crate::dtype::DType;
15use crate::scalar_fn::builtin::cast::CastReduce;
16
17impl CastReduce for Dict {
18    fn cast(array: ArrayView<'_, Dict>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
19        // Casting unused entries must not introduce errors that a cast over the rows would skip.
20        if !array.has_all_values_referenced() {
21            let safe_for_unused_values = match (array.dtype(), dtype) {
22                (DType::Primitive(from, _), DType::Primitive(to, _)) => {
23                    from.casts_losslessly_to(*to)
24                }
25                (from, to) => from.as_nullable() == to.as_nullable(),
26            };
27            if !safe_for_unused_values {
28                return Ok(None);
29            }
30        }
31
32        // An unused null entry must not make a cast to a non-nullable dtype fail.
33        if !dtype.is_nullable() && !array.values().validity()?.definitely_no_nulls() {
34            return Ok(None);
35        }
36        // Cast the dictionary values to the target type
37        let casted_values = array.values().cast(dtype.clone())?;
38
39        // If the codes are nullable but we are casting to non nullable dtype we have to remove nullability from codes as well
40        let casted_codes = if array.codes().dtype().is_nullable() && !dtype.is_nullable() {
41            array
42                .codes()
43                .cast(array.codes().dtype().with_nullability(dtype.nullability()))?
44        } else {
45            array.codes().clone()
46        };
47
48        // SAFETY: casting does not alter invariants of the codes
49        Ok(Some(
50            unsafe {
51                DictArray::new_unchecked(casted_codes, casted_values)
52                    .set_all_values_referenced(array.has_all_values_referenced())
53            }
54            .into_array(),
55        ))
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use std::sync::LazyLock;
62
63    use rstest::rstest;
64    use vortex_buffer::BitBuffer;
65    use vortex_buffer::buffer;
66    use vortex_error::VortexResult;
67    use vortex_session::VortexSession;
68
69    use crate::ArrayRef;
70    use crate::Canonical;
71    use crate::IntoArray;
72    use crate::VortexSessionExecute;
73    use crate::arrays::Dict;
74    use crate::arrays::DictArray;
75    use crate::arrays::PrimitiveArray;
76    use crate::arrays::dict::DictArraySlotsExt;
77    use crate::assert_arrays_eq;
78    use crate::builders::dict::dict_encode;
79    use crate::builtins::ArrayBuiltins;
80    use crate::compute::conformance::cast::test_cast_conformance;
81    use crate::dtype::DType;
82    use crate::dtype::Nullability;
83    use crate::dtype::PType;
84    use crate::optimizer::ArrayOptimizer;
85    use crate::validity::Validity;
86
87    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
88
89    #[test]
90    fn test_cast_dict_to_wider_type() {
91        let ctx = &mut SESSION.create_execution_ctx();
92        let values = buffer![1i32, 2, 3, 2, 1].into_array();
93        let dict = dict_encode(&values, ctx).unwrap();
94
95        let casted = dict
96            .into_array()
97            .cast(DType::Primitive(PType::I64, Nullability::NonNullable))
98            .unwrap();
99        assert_eq!(
100            casted.dtype(),
101            &DType::Primitive(PType::I64, Nullability::NonNullable)
102        );
103
104        assert_arrays_eq!(casted, PrimitiveArray::from_iter([1i64, 2, 3, 2, 1]), ctx);
105    }
106
107    #[test]
108    fn test_cast_dict_nullable() {
109        let values =
110            PrimitiveArray::from_option_iter([Some(10i32), None, Some(20), Some(10), None]);
111        let dict = dict_encode(&values.into_array(), &mut SESSION.create_execution_ctx()).unwrap();
112
113        let casted = dict
114            .into_array()
115            .cast(DType::Primitive(PType::I64, Nullability::Nullable))
116            .unwrap();
117        assert_eq!(
118            casted.dtype(),
119            &DType::Primitive(PType::I64, Nullability::Nullable)
120        );
121        assert_arrays_eq!(
122            casted,
123            PrimitiveArray::from_option_iter([Some(10i64), None, Some(20), Some(10), None]),
124            &mut SESSION.create_execution_ctx()
125        );
126    }
127
128    #[test]
129    fn test_cast_dict_allvalid_to_nonnullable_and_back() {
130        let ctx = &mut SESSION.create_execution_ctx();
131        // Create an AllValid dict array (no nulls)
132        let values = buffer![10i32, 20, 30, 40].into_array();
133        let dict = dict_encode(&values, ctx).unwrap();
134
135        // Verify initial state - codes should be NonNullable, values should be NonNullable
136        assert_eq!(dict.codes().dtype().nullability(), Nullability::NonNullable);
137        assert_eq!(
138            dict.values().dtype().nullability(),
139            Nullability::NonNullable
140        );
141
142        // Cast to NonNullable (should be identity since already NonNullable)
143        let non_nullable = dict
144            .into_array()
145            .cast(DType::Primitive(PType::I32, Nullability::NonNullable))
146            .unwrap()
147            .optimize_ctx(&SESSION)
148            .unwrap();
149        assert_eq!(
150            non_nullable.dtype(),
151            &DType::Primitive(PType::I32, Nullability::NonNullable)
152        );
153
154        // Check that codes and values are still NonNullable
155        let non_nullable_dict = non_nullable.as_::<Dict>();
156        assert_eq!(
157            non_nullable_dict.codes().dtype().nullability(),
158            Nullability::NonNullable
159        );
160        assert_eq!(
161            non_nullable_dict.values().dtype().nullability(),
162            Nullability::NonNullable
163        );
164
165        // Cast to Nullable
166        let nullable = non_nullable
167            .cast(DType::Primitive(PType::I32, Nullability::Nullable))
168            .unwrap()
169            .optimize_ctx(&SESSION)
170            .unwrap();
171        assert_eq!(
172            nullable.dtype(),
173            &DType::Primitive(PType::I32, Nullability::Nullable)
174        );
175
176        // Check that both codes and values are now Nullable
177        let nullable_dict = nullable.as_::<Dict>();
178        assert_eq!(
179            nullable_dict.codes().dtype().nullability(),
180            Nullability::NonNullable
181        );
182        assert_eq!(
183            nullable_dict.values().dtype().nullability(),
184            Nullability::Nullable
185        );
186
187        // Cast back to NonNullable
188        let back_to_non_nullable = nullable
189            .cast(DType::Primitive(PType::I32, Nullability::NonNullable))
190            .unwrap()
191            .optimize_ctx(&SESSION)
192            .unwrap();
193        assert_eq!(
194            back_to_non_nullable.dtype(),
195            &DType::Primitive(PType::I32, Nullability::NonNullable)
196        );
197
198        let expected = PrimitiveArray::from_iter([10i32, 20, 30, 40]);
199        assert_arrays_eq!(back_to_non_nullable, expected, ctx);
200    }
201
202    #[rstest]
203    #[case(dict_encode(&buffer![1i32, 2, 3, 2, 1, 3].into_array(), &mut SESSION.create_execution_ctx()).unwrap().into_array())]
204    #[case(dict_encode(&buffer![100u32, 200, 100, 300, 200].into_array(), &mut SESSION.create_execution_ctx()).unwrap().into_array())]
205    #[case(dict_encode(&PrimitiveArray::from_option_iter([Some(1i32), None, Some(2), Some(1), None]).into_array(), &mut SESSION.create_execution_ctx()).unwrap().into_array())]
206    #[case(dict_encode(&buffer![1.5f32, 2.5, 1.5, 3.5].into_array(), &mut SESSION.create_execution_ctx()).unwrap().into_array())]
207    fn test_cast_dict_conformance(#[case] array: ArrayRef) {
208        test_cast_conformance(&array, &mut SESSION.create_execution_ctx());
209    }
210
211    #[test]
212    fn test_cast_dict_with_unreferenced_null_values_to_nonnullable() {
213        let ctx = &mut SESSION.create_execution_ctx();
214        // Create a dict with nullable values that have unreferenced null entries.
215        // Values: [1.0, null, 3.0] (index 1 is null but no code points to it)
216        // Codes: [0, 2, 0] (only reference indices 0 and 2, never 1)
217        let values = PrimitiveArray::new(
218            buffer![1.0f64, 0.0f64, 3.0f64],
219            Validity::from(BitBuffer::from(vec![true, false, true])),
220        )
221        .into_array();
222        let codes = buffer![0u32, 2, 0].into_array();
223        let dict = DictArray::try_new(codes, values).unwrap();
224
225        // The dict is Nullable (because values are nullable), but all codes point to valid values.
226        assert_eq!(
227            dict.dtype(),
228            &DType::Primitive(PType::F64, Nullability::Nullable)
229        );
230
231        // Casting to NonNullable should succeed since all logical values are non-null.
232        let result = dict
233            .into_array()
234            .cast(DType::Primitive(PType::F64, Nullability::NonNullable));
235        assert!(
236            result.is_ok(),
237            "cast to NonNullable should succeed for dict with only unreferenced null values"
238        );
239        let casted = result.unwrap();
240        assert_eq!(
241            casted.dtype(),
242            &DType::Primitive(PType::F64, Nullability::NonNullable)
243        );
244        assert_arrays_eq!(casted, PrimitiveArray::from_iter([1.0f64, 3.0, 1.0]), ctx);
245    }
246
247    /// Slicing keeps the whole dictionary, so the value `1000` stays in `values` although no
248    /// remaining row references it. The cast must only consider the rows: `[1, 1, 1]` fits in i8.
249    #[test]
250    fn test_cast_dict_after_slice_ignores_unreferenced_values() -> VortexResult<()> {
251        let ctx = &mut SESSION.create_execution_ctx();
252        let dict = dict_encode(&buffer![1000i64, 1, 1, 1].into_array(), ctx)?;
253        let rows = dict.into_array().slice(1..4)?.optimize_ctx(&SESSION)?;
254
255        let casted = rows
256            .cast(DType::Primitive(PType::I8, Nullability::NonNullable))?
257            .optimize_ctx(&SESSION)?
258            .execute::<Canonical>(ctx)?;
259
260        assert_arrays_eq!(casted, PrimitiveArray::from_iter([1i8, 1, 1]), ctx);
261        Ok(())
262    }
263
264    #[test]
265    fn test_cast_dict_with_unreferenced_values_preserves_nullability_rewrite() -> VortexResult<()> {
266        let ctx = &mut SESSION.create_execution_ctx();
267        let dict = DictArray::try_new(
268            buffer![1u8, 1, 1].into_array(),
269            buffer![1000i64, 1].into_array(),
270        )?
271        .into_array();
272
273        let nullable = dict
274            .cast(DType::Primitive(PType::I64, Nullability::Nullable))?
275            .optimize_ctx(&SESSION)?;
276        assert!(nullable.is::<Dict>());
277        let non_nullable = nullable
278            .cast(DType::Primitive(PType::I64, Nullability::NonNullable))?
279            .optimize_ctx(&SESSION)?;
280        assert!(non_nullable.is::<Dict>());
281
282        assert_arrays_eq!(non_nullable, PrimitiveArray::from_iter([1i64, 1, 1]), ctx);
283        Ok(())
284    }
285
286    #[test]
287    fn test_cast_dict_rejects_referenced_out_of_range_value() -> VortexResult<()> {
288        let ctx = &mut SESSION.create_execution_ctx();
289        let dict = dict_encode(&buffer![1000i64, 1, 1, 1].into_array(), ctx)?;
290        let casted = dict
291            .into_array()
292            .cast(DType::Primitive(PType::I8, Nullability::NonNullable))?
293            .optimize_ctx(&SESSION)?;
294
295        assert!(casted.is::<Dict>());
296        let error = casted.execute::<Canonical>(ctx).unwrap_err();
297        assert!(error.to_string().contains("values exceed target range"));
298        Ok(())
299    }
300}