Skip to main content

vortex_array/optimizer/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The optimizer applies metadata-only rewrite rules (`reduce` and `reduce_parent`) in a
5//! fixpoint loop until no more rules apply.
6//!
7//! Optimization runs between execution steps. After a child is decoded, `reduce_parent` rules
8//! that did not match before can match.
9//!
10//! Parent-reduce rules come from the session's [`kernels::ArrayKernels`]. To optimize, use
11//! [`ArrayOptimizer::optimize_ctx`] with the session or with an [`ExecutionCtx`] created from it.
12//!
13//! Array constructors do not optimize. The optimizer works top down: it tries the rules of a node,
14//! then optimizes the children that were never optimized, and tries the rules of the node again if
15//! a child changed. Thus a rule for a child encoding sees that encoding, not a lazy wrapper around
16//! it. The nodes that a rule builds are optimized before the next pass, so two rules that are
17//! inverses of each other cannot rewrite a node back and forth.
18//!
19//! The optimizer marks the arrays that it returns. Optimizing a marked array again tries no rule.
20
21use std::hash::Hash;
22use std::hash::Hasher;
23use std::sync::LazyLock;
24use std::sync::atomic::AtomicBool;
25use std::sync::atomic::Ordering;
26
27use smallvec::SmallVec;
28use vortex_error::VortexExpect;
29use vortex_error::VortexResult;
30use vortex_error::vortex_bail;
31use vortex_error::vortex_ensure_eq;
32use vortex_session::VortexSession;
33use vortex_utils::aliases::hash_map::HashMap;
34
35use crate::ArrayRef;
36use crate::array::ArrayId;
37use crate::arrays::ScalarFn;
38use crate::arrays::scalar_fn::AnyScalarFn;
39use crate::executor::ExecutionCtx;
40use crate::optimizer::kernels::ArrayKernelsExt;
41use crate::optimizer::kernels::ParentReduceKernels;
42use crate::trace_op;
43
44pub mod kernels;
45pub mod rules;
46
47/// Last zero-based fixpoint pass attempted before treating continued rewrites as an infinite loop.
48/// Increasing this value permits longer rewrite chains but delays detection of cyclic rules.
49const MAX_OPTIMIZER_REWRITE_PASS: usize = 100;
50
51/// Records whether the optimizer has already taken an array node to its fixpoint.
52///
53/// A shared array never changes, so a node that reached the optimizer's fixpoint stays there.
54/// Every new array starts unoptimized, and changing a uniquely owned array in place clears the
55/// state.
56///
57/// # What the mark promises
58///
59/// The mark promises only that no reduce or parent-reduce rule applies to the node or its
60/// descendants, given their encodings, dtypes, slots and data. These do not change while the
61/// array is shared. A thread that sees the mark skips the optimizer for the whole subtree, so a
62/// rule that could apply later is never tried.
63///
64/// # When an array stays unoptimized
65///
66/// An array must stay unmarked, or clear its mark, when the decision of a rule depends on
67/// something that can change after the optimizer pass:
68///
69/// - The array changes in place. [`ArrayRef::inner_mut`] clears the mark, because the caller holds
70///   the only reference and can replace slots or data.
71/// - A rule reads state that can be set on a shared array after the pass, such as statistics.
72///   For example, a rule that reduces an array to a constant when [`Stat::IsConstant`] is known
73///   does not run if the statistic is computed after the array was marked. A shared array cannot
74///   clear its mark, because that needs the only reference. Thus such a rule must not depend on
75///   the mark, or the optimizer must not mark the arrays that it can apply to.
76/// - The session changes. The mark does not record the kernels it was optimized with, so an
77///   array optimized with one session is not optimized again with a session that registers more
78///   kernels.
79///
80/// # Memory ordering
81///
82/// The flag uses [`Ordering::Relaxed`]. This is correct because the mark only promises things that
83/// a thread can already see through its reference to the array. If the mark comes to promise
84/// state that another thread writes, such as statistics that a rule reads, store it with
85/// [`Ordering::Release`] and load it with [`Ordering::Acquire`]. Then a thread that sees the mark
86/// also sees that state.
87///
88/// [`ArrayRef::inner_mut`]: crate::ArrayRef::inner_mut
89/// [`Stat::IsConstant`]: crate::stats::Stat::IsConstant
90#[derive(Debug, Default)]
91pub(crate) struct OptimizedState(pub(crate) AtomicBool);
92
93impl OptimizedState {
94    fn is_optimized(&self) -> bool {
95        self.0.load(Ordering::Relaxed)
96    }
97
98    fn mark_optimized(&self) {
99        self.0.store(true, Ordering::Relaxed);
100    }
101}
102
103/// Marks an array decoded from its serialized form as optimized.
104///
105/// Decoding calls this for each node it decodes, and it decodes the children of a node before the
106/// node. Thus every decoded node is marked, and the optimizer does not try reduce or
107/// parent-reduce rules on any of them. Only the nodes that an encoding's deserializer builds itself
108/// around its decoded children stay unmarked. Arrays are usually written as the compressor built
109/// them, so this skips rules on decoded arrays without the guarantee that none applies. A rule
110/// that rewrites a parent of a decoded node, such as a slice pushed into a dictionary, optimizes
111/// the new nodes it builds, but not the decoded nodes that it keeps.
112pub(crate) fn mark_decoded_optimized(array: &ArrayRef) {
113    array.optimized_state().mark_optimized();
114}
115
116/// The parent-reduce kernels [`ArrayOptimizer`] optimizes with, from [`AsOptimizerKernels`].
117///
118/// A [`VortexSession`] snapshots its registered kernels for each call. An [`ExecutionCtx`] reuses
119/// the snapshot it took from its session when it was created, so a kernel that optimizes what it
120/// builds, possibly once per element, passes its context.
121#[derive(Clone, Copy)]
122pub struct OptimizerKernels<'a>(KernelSource<'a>);
123
124#[derive(Clone, Copy)]
125enum KernelSource<'a> {
126    Session(&'a VortexSession),
127    Snapshot(&'a ParentReduceKernels),
128}
129
130impl OptimizerKernels<'_> {
131    fn with_reduce_parent_kernels<R>(self, f: impl FnOnce(&ParentReduceKernels) -> R) -> R {
132        match self.0 {
133            KernelSource::Session(session) => session.kernels().with_reduce_parent_kernels(f),
134            KernelSource::Snapshot(kernels) => f(kernels),
135        }
136    }
137}
138
139/// A source of the parent-reduce kernels [`ArrayOptimizer`] optimizes with.
140pub trait AsOptimizerKernels {
141    /// The kernels to optimize with.
142    fn optimizer_kernels(&self) -> OptimizerKernels<'_>;
143}
144
145impl AsOptimizerKernels for VortexSession {
146    fn optimizer_kernels(&self) -> OptimizerKernels<'_> {
147        OptimizerKernels(KernelSource::Session(self))
148    }
149}
150
151impl AsOptimizerKernels for LazyLock<VortexSession> {
152    fn optimizer_kernels(&self) -> OptimizerKernels<'_> {
153        OptimizerKernels(KernelSource::Session(self))
154    }
155}
156
157impl AsOptimizerKernels for ExecutionCtx {
158    fn optimizer_kernels(&self) -> OptimizerKernels<'_> {
159        OptimizerKernels(KernelSource::Snapshot(self.reduce_parent_kernels()))
160    }
161}
162
163/// Extension trait for optimizing array trees using reduce/reduce_parent rules.
164pub trait ArrayOptimizer {
165    /// Optimize the array with only the parent-reduce rules that `vortex-array` registers by
166    /// default.
167    ///
168    /// Encodings outside `vortex-array` register their rules with a session, so this misses them.
169    /// The result is not marked as optimized, so optimizing it later with a session still tries
170    /// the session's rules.
171    #[deprecated(
172        note = "use `optimize_ctx` with the session, or an `ExecutionCtx` created from it, instead"
173    )]
174    fn optimize(&self) -> VortexResult<ArrayRef>;
175
176    /// Optimize the root array node by running reduce and reduce_parent rules to fixpoint.
177    ///
178    /// The root is optimized first, then the descendants that were never optimized, then the root
179    /// again if a child changed. Parent-reduce kernels are looked up for each
180    /// `(parent_encoding_id, child_encoding_id)` pair in the [`kernels::KernelSession`] of the
181    /// session, or of the session an execution context was created from.
182    fn optimize_ctx(&self, kernels: &(impl AsOptimizerKernels + ?Sized)) -> VortexResult<ArrayRef>;
183
184    /// Optimize the entire array tree recursively (root and all descendants).
185    ///
186    /// This is the same as [`Self::optimize_ctx`]: optimizing a node also optimizes every
187    /// descendant that was never optimized.
188    fn optimize_recursive(
189        &self,
190        kernels: &(impl AsOptimizerKernels + ?Sized),
191    ) -> VortexResult<ArrayRef>;
192}
193
194impl ArrayOptimizer for ArrayRef {
195    fn optimize(&self) -> VortexResult<ArrayRef> {
196        /// A session that holds only the parent-reduce rules `vortex-array` registers by default.
197        static BUILTIN_SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
198
199        if self.optimized_state().is_optimized() {
200            return Ok(self.clone());
201        }
202
203        BUILTIN_SESSION
204            .kernels()
205            .with_reduce_parent_kernels(|kernels| {
206                Optimizer {
207                    kernels,
208                    mark: false,
209                    rewritten_shared: HashMap::new(),
210                }
211                .optimize_array(self)
212            })
213    }
214
215    fn optimize_ctx(&self, kernels: &(impl AsOptimizerKernels + ?Sized)) -> VortexResult<ArrayRef> {
216        if self.optimized_state().is_optimized() {
217            return Ok(self.clone());
218        }
219
220        kernels
221            .optimizer_kernels()
222            .with_reduce_parent_kernels(|kernels| optimize_with_kernels(self, kernels))
223    }
224
225    fn optimize_recursive(
226        &self,
227        kernels: &(impl AsOptimizerKernels + ?Sized),
228    ) -> VortexResult<ArrayRef> {
229        self.optimize_ctx(kernels)
230    }
231}
232
233/// [`ArrayOptimizer::optimize_ctx`] against a snapshot of the session's parent-reduce kernels.
234pub(crate) fn optimize_with_kernels(
235    array: &ArrayRef,
236    kernels: &ParentReduceKernels,
237) -> VortexResult<ArrayRef> {
238    Optimizer::new(kernels).optimize_array(array)
239}
240
241/// An array keyed by identity: two keys are equal only when they hold the same array, as
242/// [`ArrayRef::ptr_eq`] decides.
243///
244/// The key holds the array, so its address cannot be freed and reused by another array while the
245/// key exists.
246struct ArrayByPtr(ArrayRef);
247
248impl PartialEq for ArrayByPtr {
249    fn eq(&self, other: &Self) -> bool {
250        ArrayRef::ptr_eq(&self.0, &other.0)
251    }
252}
253
254impl Eq for ArrayByPtr {}
255
256impl Hash for ArrayByPtr {
257    fn hash<H: Hasher>(&self, state: &mut H) {
258        self.0.addr().hash(state);
259    }
260}
261
262/// The optimizer state, which can be kept for many optimize calls.
263///
264/// Execution keeps one optimizer for all of [`ArrayRef::execute_until`], so a shared node that one
265/// step rewrote is not rewritten again when a later step reaches it through another parent.
266pub(crate) struct Optimizer<'a> {
267    kernels: &'a ParentReduceKernels,
268    /// Whether to mark the arrays this optimizer returns as optimized. Only the deprecated
269    /// [`ArrayOptimizer::optimize`] leaves them unmarked, since it misses the session's rules.
270    mark: bool,
271    /// The shared nodes this optimizer rewrote, each with the array it was rewritten into.
272    ///
273    /// Many parents can hold the same unoptimized node, such as the struct below every field of a
274    /// projection. A rewrite returns a new array and does not mark the node, so without this each
275    /// parent would rewrite the node and its whole subtree again. The key keeps the node alive
276    /// for the life of the optimizer.
277    rewritten_shared: HashMap<ArrayByPtr, ArrayRef>,
278}
279
280impl<'a> Optimizer<'a> {
281    /// Creates an optimizer that tries `kernels` and marks the arrays it returns.
282    pub(crate) fn new(kernels: &'a ParentReduceKernels) -> Self {
283        Self {
284            kernels,
285            mark: true,
286            rewritten_shared: HashMap::new(),
287        }
288    }
289
290    /// Optimizes `array` and the descendants below it that were never optimized, and marks the
291    /// result.
292    ///
293    /// If another owner holds `array` too, the rewrite is remembered, and a later call with the
294    /// same array returns it.
295    pub(crate) fn optimize_array(&mut self, array: &ArrayRef) -> VortexResult<ArrayRef> {
296        if !array.is_shared() {
297            return self.optimize(array.clone());
298        }
299
300        let key = ArrayByPtr(array.clone());
301        if let Some(rewritten) = self.rewritten_shared.get(&key) {
302            return Ok(rewritten.clone());
303        }
304
305        let optimized = self.optimize(array.clone())?;
306        if !ArrayRef::ptr_eq(&optimized, array) {
307            self.rewritten_shared.insert(key, optimized.clone());
308        }
309
310        Ok(optimized)
311    }
312
313    /// Tries the parent-reduce kernels of the child in `slot_idx` against `parent`, without trying
314    /// those of `parent`'s other children.
315    pub(crate) fn reduce_parent_of_slot(
316        &self,
317        parent: &ArrayRef,
318        slot_idx: usize,
319    ) -> VortexResult<Option<ArrayRef>> {
320        let child = parent.slots()[slot_idx]
321            .as_ref()
322            .vortex_expect("parent-reduce needs a present slot");
323        reduce_parent_with_kernels(self.kernels, parent, child, slot_idx)
324    }
325
326    /// Optimizes `array` top down: first the root, then the descendants below it that were never
327    /// optimized, then the root again while its children change. Marks the result.
328    fn optimize(&mut self, array: ArrayRef) -> VortexResult<ArrayRef> {
329        if array.optimized_state().is_optimized() {
330            return Ok(array);
331        }
332
333        // The rules of the root get the first try, on children that can still be lazy, so a rule
334        // that drops or replaces a child does not pay to optimize that child's subtree first.
335        let mut optimized = self.optimize_root(array.clone())?;
336
337        for _ in 0..=MAX_OPTIMIZER_REWRITE_PASS {
338            let with_children = self.optimize_new_nodes(optimized.clone())?;
339            if ArrayRef::ptr_eq(&with_children, &optimized) {
340                break;
341            }
342
343            // A child changed its encoding, so a parent rule keyed on that encoding can apply now.
344            optimized = self.optimize_root(with_children)?;
345        }
346
347        // A rewrite keeps the logical values, so every statistic of the input stays valid. Lazy
348        // constructors such as `slice` put the statistics they carry over on the lazy node.
349        if !ArrayRef::ptr_eq(&optimized, &array) {
350            optimized.statistics().inherit_from(array.statistics());
351        }
352
353        if self.mark {
354            optimized.optimized_state().mark_optimized();
355        }
356
357        Ok(optimized)
358    }
359
360    /// Runs the reduce and parent-reduce rules on the root of `current_array` to fixpoint.
361    ///
362    /// The nodes each rewrite built are optimized before the next pass.
363    fn optimize_root(&mut self, mut current_array: ArrayRef) -> VortexResult<ArrayRef> {
364        let mut any_optimizations = false;
365
366        trace_op!(record_optimize_start(&current_array));
367
368        for _ in 0..=MAX_OPTIMIZER_REWRITE_PASS {
369            trace_op!(record_optimize_loop_start(&current_array));
370
371            if let Some(new_array) = current_array.reduce()? {
372                current_array = self.optimize_new_nodes(new_array)?;
373                any_optimizations = true;
374                trace_op!(record_optimize_loop_end());
375                continue;
376            }
377
378            trace_op!(record_optimize_reduce_none(&current_array));
379
380            // Try children in order; the first parent rewrite restarts the fixpoint loop. A parent
381            // that no kernel is registered for skips its children without probing each pair.
382            let mut reduced_parent = None;
383            let candidates = ReduceParentCandidates::new(self.kernels, &current_array);
384            if !candidates.is_empty() {
385                for (slot_idx, slot) in current_array.slots().iter().enumerate() {
386                    let Some(child) = slot else {
387                        continue;
388                    };
389                    if candidates.contains(child)
390                        && let Some(new_array) = reduce_parent_with_kernels(
391                            self.kernels,
392                            &current_array,
393                            child,
394                            slot_idx,
395                        )?
396                    {
397                        reduced_parent = Some(new_array);
398                        break;
399                    }
400                }
401            }
402
403            if let Some(new_array) = reduced_parent {
404                current_array = self.optimize_new_nodes(new_array)?;
405                any_optimizations = true;
406                trace_op!(record_optimize_loop_end());
407                continue;
408            }
409
410            trace_op!(record_optimize_parent_reduce_none(&current_array));
411            trace_op!(record_optimize_loop_end());
412
413            trace_op!(record_optimize_done(&current_array, any_optimizations));
414
415            return Ok(current_array);
416        }
417
418        vortex_bail!("Exceeded maximum optimization iterations (possible infinite loop)");
419    }
420
421    /// Optimizes the nodes below `array` that were never optimized, such as those a rule built
422    /// below its result.
423    ///
424    /// Rules and constructors build lazy arrays, so these nodes are not yet optimized, at any
425    /// depth. Optimizing them as each rewrite happens keeps the optimizer from undoing one rule
426    /// with its inverse: `slice(get_item(s))` and `get_item(slice(s))` rewrite into each other
427    /// until the inner `slice(s)` collapses into `s`'s own encoding.
428    ///
429    /// A child that is already optimized is left as it is without visiting its subtree, which
430    /// skips the subtrees a rule carries over from the array it rewrote.
431    fn optimize_new_nodes(&mut self, array: ArrayRef) -> VortexResult<ArrayRef> {
432        let mut new_slots: Option<SmallVec<_>> = None;
433        for (slot_idx, slot) in array.slots().iter().enumerate() {
434            let optimized = match slot {
435                Some(child) if !child.optimized_state().is_optimized() => {
436                    let optimized = self.optimize_array(child)?;
437                    (!ArrayRef::ptr_eq(&optimized, child)).then_some(optimized)
438                }
439                _ => None,
440            };
441            match optimized {
442                Some(optimized) => new_slots
443                    .get_or_insert_with(|| {
444                        let mut slots = SmallVec::with_capacity(array.slots().len());
445                        slots.extend(array.slots()[..slot_idx].iter().cloned());
446                        slots
447                    })
448                    .push(Some(optimized)),
449                None => {
450                    if let Some(new_slots) = &mut new_slots {
451                        new_slots.push(slot.clone());
452                    }
453                }
454            }
455        }
456        let Some(new_slots) = new_slots else {
457            return Ok(array);
458        };
459        // SAFETY: optimizer rules only replace child slots with logically equivalent arrays, so
460        // the parent's logical values and statistics remain valid.
461        unsafe { array.with_slots(new_slots) }
462    }
463}
464
465/// The child ids that parent-reduce kernels are registered for under one parent: those for the
466/// parent's encoding id and, for a scalar function array, those for [`AnyScalarFn::id`].
467struct ReduceParentCandidates<'a> {
468    exact: &'a [ArrayId],
469    any_scalar_fn: &'a [ArrayId],
470    /// Whether either list holds [`AnyScalarFn::id`], so any scalar function child is a candidate.
471    any_scalar_fn_child: bool,
472}
473
474impl<'a> ReduceParentCandidates<'a> {
475    fn new(kernels: &'a ParentReduceKernels, parent: &ArrayRef) -> Self {
476        let exact = kernels.children(parent.encoding_id()).unwrap_or_default();
477        let any_scalar_fn = if parent.is::<ScalarFn>() {
478            kernels.children(AnyScalarFn.id()).unwrap_or_default()
479        } else {
480            &[]
481        };
482        let any_scalar_fn_child = (!exact.is_empty() || !any_scalar_fn.is_empty()) && {
483            let any_id = AnyScalarFn.id();
484            exact.contains(&any_id) || any_scalar_fn.contains(&any_id)
485        };
486        Self {
487            exact,
488            any_scalar_fn,
489            any_scalar_fn_child,
490        }
491    }
492
493    fn is_empty(&self) -> bool {
494        self.exact.is_empty() && self.any_scalar_fn.is_empty()
495    }
496
497    /// Returns whether any kernel may apply to `child` under this parent.
498    fn contains(&self, child: &ArrayRef) -> bool {
499        let id = child.encoding_id();
500        self.exact.contains(&id)
501            || self.any_scalar_fn.contains(&id)
502            || (self.any_scalar_fn_child && child.is::<ScalarFn>())
503    }
504}
505
506/// Tries the parent-reduce kernels registered for `child` under `parent`.
507///
508/// Kernels registered for the exact encoding ids come first. A scalar function array also matches
509/// kernels registered under [`AnyScalarFn::id`], on either side, which are tried after them.
510pub(crate) fn reduce_parent_with_kernels(
511    kernels: &ParentReduceKernels,
512    parent: &ArrayRef,
513    child: &ArrayRef,
514    slot_idx: usize,
515) -> VortexResult<Option<ArrayRef>> {
516    let any_scalar_fn = AnyScalarFn.id();
517    let parent_ids = [
518        Some(parent.encoding_id()),
519        parent.is::<ScalarFn>().then_some(any_scalar_fn),
520    ];
521    let child_ids = [
522        Some(child.encoding_id()),
523        child.is::<ScalarFn>().then_some(any_scalar_fn),
524    ];
525    for parent_id in parent_ids.into_iter().flatten() {
526        for child_id in child_ids.into_iter().flatten() {
527            if let Some(reduced) =
528                try_parent_reduce_kernels(kernels, parent_id, child_id, parent, child, slot_idx)?
529            {
530                return Ok(Some(reduced));
531            }
532        }
533    }
534    Ok(None)
535}
536
537fn try_parent_reduce_kernels(
538    kernels: &ParentReduceKernels,
539    parent_id: ArrayId,
540    child_id: ArrayId,
541    parent: &ArrayRef,
542    child: &ArrayRef,
543    slot_idx: usize,
544) -> VortexResult<Option<ArrayRef>> {
545    let Some(reduce_parent_kernels) = kernels.get(parent_id, child_id) else {
546        return Ok(None);
547    };
548
549    #[allow(clippy::unused_enumerate_index)]
550    for (_kernel_idx, kernel) in reduce_parent_kernels.iter().enumerate() {
551        if let Some(new_array) = kernel.reduce_parent(child, parent, slot_idx)? {
552            vortex_ensure_eq!(
553                new_array.len(),
554                parent.len(),
555                "parent-reduce kernel for {} under {} changed the length",
556                child.encoding_id(),
557                parent.encoding_id(),
558            );
559            vortex_ensure_eq!(
560                new_array.dtype(),
561                parent.dtype(),
562                "parent-reduce kernel for {} under {} changed the dtype",
563                child.encoding_id(),
564                parent.encoding_id(),
565            );
566            trace_op!(record_session_parent_reduce_applied(
567                parent,
568                child,
569                slot_idx,
570                _kernel_idx,
571                kernel,
572                &new_array,
573            ));
574
575            return Ok(Some(new_array));
576        }
577
578        trace_op!(record_session_parent_reduce_declined(
579            parent,
580            child,
581            slot_idx,
582            _kernel_idx,
583            kernel,
584        ));
585    }
586
587    Ok(None)
588}
589
590#[cfg(test)]
591mod tests {
592    use std::sync::LazyLock;
593
594    use vortex_buffer::buffer;
595    use vortex_error::VortexResult;
596    use vortex_mask::Mask;
597    use vortex_session::VortexSession;
598
599    use crate::ArrayRef;
600    use crate::IntoArray;
601    use crate::arrays::Primitive;
602    use crate::arrays::StructArray;
603    use crate::optimizer::ArrayOptimizer;
604    use crate::scalar::ScalarValue;
605    use crate::stats::Precision;
606    use crate::stats::Stat;
607    use crate::stats::StatsProviderExt;
608
609    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
610
611    #[test]
612    fn optimize_marks_result_and_skips_it_after() -> VortexResult<()> {
613        let sliced = buffer![1i32, 2, 3, 4].into_array().slice(1..3)?;
614        assert!(!sliced.optimized_state().is_optimized());
615
616        let optimized = sliced.optimize_ctx(&SESSION)?;
617        assert!(optimized.is::<Primitive>());
618        assert!(optimized.optimized_state().is_optimized());
619        assert!(ArrayRef::ptr_eq(
620            &optimized.optimize_ctx(&SESSION)?,
621            &optimized
622        ));
623
624        // A new array built over an optimized one starts unoptimized.
625        assert!(!optimized.slice(0..1)?.optimized_state().is_optimized());
626        Ok(())
627    }
628
629    #[test]
630    fn optimize_rewrites_a_shared_node_once() -> VortexResult<()> {
631        // Both fields hold the same unoptimized slice. The second field reuses the rewrite of the
632        // first, so the optimizer does not rewrite the slice and its subtree again.
633        let shared = buffer![1i32, 2, 3, 4].into_array().slice(1..3)?;
634        let parent =
635            StructArray::from_fields(&[("a", shared.clone()), ("b", shared)])?.into_array();
636
637        let optimized = parent.optimize_ctx(&SESSION)?;
638        let fields = optimized.slots().iter().flatten().collect::<Vec<_>>();
639        assert_eq!(fields.len(), 2);
640        assert!(fields[0].is::<Primitive>());
641        assert!(ArrayRef::ptr_eq(fields[0], fields[1]));
642        Ok(())
643    }
644
645    #[test]
646    fn optimize_marks_every_descendant() -> VortexResult<()> {
647        let array = buffer![1i32, 2, 3, 4].into_array();
648        let filtered = array
649            .slice(1..4)?
650            .filter(Mask::from_iter([true, false, true]))?;
651
652        let optimized = filtered.optimize_ctx(&SESSION)?;
653        assert!(
654            optimized
655                .depth_first_traversal()
656                .all(|node| node.optimized_state().is_optimized())
657        );
658        assert!(ArrayRef::ptr_eq(
659            &optimized.optimize_recursive(&SESSION)?,
660            &optimized
661        ));
662        Ok(())
663    }
664
665    #[test]
666    fn optimize_keeps_stats_of_rewritten_array() -> VortexResult<()> {
667        let array = buffer![1i32, 2, 3, 4].into_array();
668        array
669            .statistics()
670            .set(Stat::IsSorted, Precision::exact(ScalarValue::Bool(true)));
671
672        let optimized = array.slice(1..3)?.optimize_ctx(&SESSION)?;
673        assert!(optimized.is::<Primitive>());
674        assert_eq!(
675            optimized.statistics().get_as::<bool>(Stat::IsSorted),
676            Precision::exact(true)
677        );
678        Ok(())
679    }
680}