Skip to main content

vortex_array/optimizer/
rules.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Metadata-only rewrite rules for the optimizer (Layers 1 and 2 of the execution model).
5//!
6//! Reduce rules are the cheapest transformations in the execution pipeline: they operate
7//! purely on array structure and metadata without reading any data buffers.
8//!
9//! There are two kinds of reduce rules:
10//!
11//! - [`ArrayReduceRule`] (Layer 1) -- a self-rewrite where an array simplifies itself.
12//!   Example: a `FilterArray` with an all-true mask removes the filter wrapper.
13//!
14//! - [`ArrayParentReduceRule`] (Layer 2) -- a child-driven rewrite where a child rewrites
15//!   its parent. Example: a `DictArray` child of a `ScalarFnArray` pushes the scalar function
16//!   into the dictionary values.
17//!
18//! Reduce rules are collected into a [`ReduceRuleSet`] per encoding. Parent-reduce rules are
19//! registered with the session's [`ArrayKernels`](crate::optimizer::kernels::ArrayKernels) for
20//! each `(parent, child)` pair they apply to. The optimizer evaluates both in a fixpoint loop until
21//! no more rules apply.
22
23use std::fmt::Debug;
24
25use vortex_error::VortexResult;
26
27use crate::ArrayRef;
28use crate::array::ArrayView;
29use crate::array::VTable;
30use crate::matcher::Matcher;
31use crate::trace_op;
32
33/// A metadata-only rewrite rule that transforms an array based on its own structure (Layer 1).
34///
35/// These rules look only at the array's metadata and children types (not buffer contents)
36/// and return a structurally simpler replacement, or `None` if the rule doesn't apply.
37pub trait ArrayReduceRule<V: VTable>: Debug + Send + Sync + 'static {
38    /// Attempt to rewrite this array.
39    ///
40    /// Returns:
41    /// - `Ok(Some(new_array))` if the rule applied successfully
42    /// - `Ok(None)` if the rule doesn't apply
43    /// - `Err(e)` if an error occurred
44    fn reduce(&self, array: ArrayView<'_, V>) -> VortexResult<Option<ArrayRef>>;
45}
46
47/// A metadata-only rewrite rule where a child encoding rewrites its parent (Layer 2).
48///
49/// The child sees the parent's type via the associated `Parent` [`Matcher`] and can return
50/// a replacement for the parent. This enables optimizations like pushing operations through
51/// compression layers (e.g., pushing a scalar function into dictionary values).
52pub trait ArrayParentReduceRule<V: VTable>: Debug + Send + Sync + 'static {
53    /// The parent array type this rule matches against.
54    type Parent: Matcher;
55
56    /// Attempt to rewrite this child array given information about its parent.
57    ///
58    /// Returns:
59    /// - `Ok(Some(new_array))` if the rule applied successfully
60    /// - `Ok(None)` if the rule doesn't apply
61    /// - `Err(e)` if an error occurred
62    fn reduce_parent(
63        &self,
64        array: ArrayView<'_, V>,
65        parent: <Self::Parent as Matcher>::Match<'_>,
66        child_idx: usize,
67    ) -> VortexResult<Option<ArrayRef>>;
68}
69
70/// A collection of [`ArrayReduceRule`]s registered for a specific encoding.
71///
72/// During optimization, the optimizer calls [`evaluate`](Self::evaluate) which tries each rule
73/// in order. The first rule that returns `Some` wins.
74pub struct ReduceRuleSet<V: VTable> {
75    rules: &'static [&'static dyn ArrayReduceRule<V>],
76}
77
78impl<V: VTable> ReduceRuleSet<V> {
79    /// Create a new reduction rule set with the given rules.
80    pub const fn new(rules: &'static [&'static dyn ArrayReduceRule<V>]) -> Self {
81        Self { rules }
82    }
83
84    /// Evaluate the reduction rules on the given array.
85    pub fn evaluate(&self, array: ArrayView<'_, V>) -> VortexResult<Option<ArrayRef>> {
86        for rule in self.rules.iter() {
87            if let Some(reduced) = rule.reduce(array)? {
88                trace_op!(record_reduce_applied(array.array(), *rule, &reduced));
89                return Ok(Some(reduced));
90            }
91            trace_op!(record_reduce_declined(array.array(), *rule));
92        }
93        Ok(None)
94    }
95}