Skip to main content

vortex_array/
normalize.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use smallvec::SmallVec;
5use vortex_error::VortexResult;
6use vortex_error::vortex_bail;
7use vortex_session::registry::Id;
8use vortex_utils::aliases::hash_set::HashSet;
9
10use crate::ArrayRef;
11use crate::ExecutionCtx;
12
13/// Options for normalizing an array.
14pub struct NormalizeOptions<'a> {
15    /// The set of allowed array encodings (in addition to the canonical ones) that are permitted
16    /// in the normalized array.
17    pub allowed: &'a HashSet<Id>,
18    /// The operation to perform when a non-allowed encoding is encountered.
19    pub operation: Operation<'a>,
20}
21
22/// The operation to perform when a non-allowed encoding is encountered.
23pub enum Operation<'a> {
24    Error,
25    Execute(&'a mut ExecutionCtx),
26}
27
28impl ArrayRef {
29    /// Normalize the array according to given options.
30    ///
31    /// This operation performs a recursive traversal of the array. Any non-allowed encoding is
32    /// normalized per the configured operation.
33    pub fn normalize(self, options: &mut NormalizeOptions) -> VortexResult<ArrayRef> {
34        match &mut options.operation {
35            Operation::Error => {
36                self.normalize_with_error(options.allowed)?;
37                // Note this takes ownership so we can at a later date remove non-allowed encodings.
38                Ok(self)
39            }
40            Operation::Execute(ctx) => self.normalize_with_execution(options.allowed, ctx),
41        }
42    }
43
44    fn normalize_with_error(&self, allowed: &HashSet<Id>) -> VortexResult<()> {
45        if !self.is_allowed_encoding(allowed) {
46            vortex_bail!(AssertionFailed: "normalize forbids encoding ({})", self.encoding_id())
47        }
48
49        for child in self.children() {
50            child.normalize_with_error(allowed)?
51        }
52        Ok(())
53    }
54
55    fn normalize_with_execution(
56        self,
57        allowed: &HashSet<Id>,
58        ctx: &mut ExecutionCtx,
59    ) -> VortexResult<ArrayRef> {
60        let mut normalized = self;
61
62        // Top-first execute the array tree while we hit non-allowed encodings.
63        while !normalized.is_allowed_encoding(allowed) {
64            normalized = normalized.execute(ctx)?;
65        }
66
67        // Now we've normalized the root, we need to ensure the children are normalized also.
68        let slots = normalized.slots();
69        let mut normalized_slots = SmallVec::with_capacity(slots.len());
70        let mut any_slot_changed = false;
71
72        for slot in slots {
73            match slot {
74                Some(child) => {
75                    let normalized_child = child.clone().normalize(&mut NormalizeOptions {
76                        allowed,
77                        operation: Operation::Execute(ctx),
78                    })?;
79                    any_slot_changed |= !ArrayRef::ptr_eq(child, &normalized_child);
80                    normalized_slots.push(Some(normalized_child));
81                }
82                None => normalized_slots.push(None),
83            }
84        }
85
86        if any_slot_changed {
87            normalized = normalized.with_slots(normalized_slots)?;
88        }
89
90        Ok(normalized)
91    }
92
93    fn is_allowed_encoding(&self, allowed: &HashSet<Id>) -> bool {
94        allowed.contains(&self.encoding_id()) || self.is_canonical()
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use vortex_error::VortexResult;
101    use vortex_session::VortexSession;
102    use vortex_utils::aliases::hash_set::HashSet;
103
104    use super::NormalizeOptions;
105    use super::Operation;
106    use crate::ArrayRef;
107    use crate::ExecutionCtx;
108    use crate::IntoArray;
109    use crate::array::VTable;
110    use crate::arrays::Dict;
111    use crate::arrays::DictArray;
112    use crate::arrays::Primitive;
113    use crate::arrays::PrimitiveArray;
114    use crate::arrays::Slice;
115    use crate::arrays::SliceArray;
116    use crate::arrays::StructArray;
117    use crate::assert_arrays_eq;
118    use crate::validity::Validity;
119
120    #[test]
121    fn normalize_with_execution_keeps_parent_when_children_are_unchanged() -> VortexResult<()> {
122        let field = PrimitiveArray::from_iter(0i32..4).into_array();
123        let array = StructArray::try_new(
124            ["field"].into(),
125            vec![field.clone()],
126            field.len(),
127            Validity::NonNullable,
128        )?
129        .into_array();
130        let allowed = HashSet::from_iter([array.encoding_id(), field.encoding_id()]);
131        let mut ctx = ExecutionCtx::new(VortexSession::empty());
132
133        let normalized = array.clone().normalize(&mut NormalizeOptions {
134            allowed: &allowed,
135            operation: Operation::Execute(&mut ctx),
136        })?;
137
138        assert!(ArrayRef::ptr_eq(&array, &normalized));
139        Ok(())
140    }
141
142    #[test]
143    fn normalize_with_error_allows_canonical_arrays() -> VortexResult<()> {
144        let field = PrimitiveArray::from_iter(0i32..4).into_array();
145        let array = StructArray::try_new(
146            ["field"].into(),
147            vec![field.clone()],
148            field.len(),
149            Validity::NonNullable,
150        )?
151        .into_array();
152        let allowed = HashSet::default();
153
154        let normalized = array.clone().normalize(&mut NormalizeOptions {
155            allowed: &allowed,
156            operation: Operation::Error,
157        })?;
158
159        assert!(ArrayRef::ptr_eq(&array, &normalized));
160        Ok(())
161    }
162
163    #[test]
164    fn normalize_with_execution_rebuilds_parent_when_a_child_changes() -> VortexResult<()> {
165        let unchanged = PrimitiveArray::from_iter(0i32..4).into_array();
166        let sliced =
167            SliceArray::new(PrimitiveArray::from_iter(10i32..20).into_array(), 2..6).into_array();
168        let array = StructArray::try_new(
169            ["lhs", "rhs"].into(),
170            vec![unchanged.clone(), sliced],
171            unchanged.len(),
172            Validity::NonNullable,
173        )?
174        .into_array();
175        let allowed = HashSet::from_iter([array.encoding_id(), unchanged.encoding_id()]);
176        let mut ctx = ExecutionCtx::new(VortexSession::empty());
177
178        let normalized = array.clone().normalize(&mut NormalizeOptions {
179            allowed: &allowed,
180            operation: Operation::Execute(&mut ctx),
181        })?;
182
183        assert!(!ArrayRef::ptr_eq(&array, &normalized));
184
185        let original_children = array.children();
186        let normalized_children = normalized.children();
187        assert!(ArrayRef::ptr_eq(
188            &original_children[0],
189            &normalized_children[0]
190        ));
191        assert!(!ArrayRef::ptr_eq(
192            &original_children[1],
193            &normalized_children[1]
194        ));
195        assert_arrays_eq!(normalized_children[1], PrimitiveArray::from_iter(12i32..16));
196
197        Ok(())
198    }
199
200    #[test]
201    fn normalize_slice_of_dict_returns_dict() -> VortexResult<()> {
202        let codes = PrimitiveArray::from_iter(vec![0u32, 1, 0, 1, 2]).into_array();
203        let values = PrimitiveArray::from_iter(vec![10i32, 20, 30]).into_array();
204        let dict = DictArray::try_new(codes, values)?.into_array();
205
206        // Slice the dict array to get a SliceArray wrapping a DictArray.
207        let sliced = SliceArray::new(dict, 1..4).into_array();
208        assert_eq!(sliced.encoding_id(), Slice.id());
209
210        let allowed = HashSet::from_iter([Dict.id(), Primitive.id()]);
211        let mut ctx = ExecutionCtx::new(VortexSession::empty());
212
213        let normalized = sliced.normalize(&mut NormalizeOptions {
214            allowed: &allowed,
215            operation: Operation::Execute(&mut ctx),
216        })?;
217
218        // The normalized result should be a DictArray, not a SliceArray.
219        assert_eq!(normalized.encoding_id(), Dict.id());
220        assert_eq!(normalized.len(), 3);
221
222        // Verify the data: codes [1,0,1] -> values [20, 10, 20]
223        #[expect(deprecated)]
224        let normalized_canonical = normalized.to_canonical()?;
225        assert_arrays_eq!(
226            normalized_canonical,
227            PrimitiveArray::from_iter(vec![20i32, 10, 20])
228        );
229
230        Ok(())
231    }
232}