Skip to main content

vortex_array/
normalize.rs

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