Skip to main content

vortex_scan/plan/optimize/
rules.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Typed and type-erased interfaces for plan rewrites.
5
6use std::any::type_name;
7use std::fmt::Debug;
8use std::marker::PhantomData;
9
10use vortex_error::VortexResult;
11#[cfg(debug_assertions)]
12use vortex_error::vortex_ensure_eq;
13use vortex_session::VortexSession;
14
15use crate::plan::Plan;
16use crate::plan::PlanRef;
17use crate::plan::PlanVTable;
18
19/// A rewrite over one concrete plan operator.
20///
21/// Rules return one rewrite without recursively optimizing the replacement. The plan optimizer
22/// owns traversal and drives further rewrites.
23pub trait PlanReduceRule<P: PlanVTable>: Debug + Send + Sync + 'static {
24    /// Attempts to replace `plan`.
25    fn reduce(&self, plan: &Plan<P>, session: &VortexSession) -> VortexResult<Option<PlanRef>>;
26}
27
28/// Type-erased interface used by [`PlanRuleSet`].
29pub trait DynPlanReduceRule: Debug + Send + Sync + 'static {
30    /// Returns whether this rule supports the concrete plan operator.
31    fn matches(&self, plan: &PlanRef) -> bool;
32
33    /// Attempts to replace `plan`.
34    fn reduce(&self, plan: &PlanRef, session: &VortexSession) -> VortexResult<Option<PlanRef>>;
35}
36
37/// Bridges a typed [`PlanReduceRule`] to a type-erased static registry.
38pub struct PlanReduceRuleAdapter<P, R> {
39    rule: R,
40    _plan: PhantomData<fn() -> P>,
41}
42
43impl<P, R> PlanReduceRuleAdapter<P, R> {
44    /// Creates an adapter for a typed plan rule.
45    pub const fn new(rule: R) -> Self {
46        Self {
47            rule,
48            _plan: PhantomData,
49        }
50    }
51}
52
53impl<P, R> Debug for PlanReduceRuleAdapter<P, R>
54where
55    P: PlanVTable,
56    R: PlanReduceRule<P>,
57{
58    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        formatter
60            .debug_struct("PlanReduceRuleAdapter")
61            .field("plan", &type_name::<P>())
62            .field("rule", &self.rule)
63            .finish()
64    }
65}
66
67impl<P, R> DynPlanReduceRule for PlanReduceRuleAdapter<P, R>
68where
69    P: PlanVTable,
70    R: PlanReduceRule<P>,
71{
72    fn matches(&self, plan: &PlanRef) -> bool {
73        plan.is::<P>()
74    }
75
76    fn reduce(&self, plan: &PlanRef, session: &VortexSession) -> VortexResult<Option<PlanRef>> {
77        let Some(plan) = plan.as_opt::<P>() else {
78            return Ok(None);
79        };
80        self.rule.reduce(plan, session)
81    }
82}
83
84/// An ordered static collection of single-plan rewrite rules.
85pub struct PlanRuleSet {
86    rules: &'static [&'static dyn DynPlanReduceRule],
87}
88
89impl PlanRuleSet {
90    /// Creates a rule set whose first successful rewrite wins.
91    pub const fn new(rules: &'static [&'static dyn DynPlanReduceRule]) -> Self {
92        Self { rules }
93    }
94
95    /// Evaluates rules registered for the concrete plan operator.
96    pub fn evaluate(
97        &self,
98        plan: &PlanRef,
99        session: &VortexSession,
100    ) -> VortexResult<Option<PlanRef>> {
101        for rule in self.rules {
102            if !rule.matches(plan) {
103                continue;
104            }
105            let Some(reduced) = rule.reduce(plan, session)? else {
106                continue;
107            };
108
109            #[cfg(debug_assertions)]
110            {
111                vortex_ensure_eq!(
112                    reduced.row_count(),
113                    plan.row_count(),
114                    "Plan rewrite from {rule:?} changed row count"
115                );
116                vortex_ensure_eq!(
117                    reduced.dtype(),
118                    plan.dtype(),
119                    "Plan rewrite from {rule:?} changed dtype"
120                );
121            }
122
123            return Ok(Some(reduced));
124        }
125        Ok(None)
126    }
127}
128
129/// A metadata-only rewrite where a child plan rewrites its parent plan.
130///
131/// Rules return one rewrite without recursively optimizing the replacement. The plan optimizer
132/// owns traversal and drives further rewrites.
133pub trait PlanParentReduceRule<C: PlanVTable>: Debug + Send + Sync + 'static {
134    /// The concrete parent operator matched by this rule.
135    type Parent: PlanVTable;
136
137    /// Attempts to replace `parent` based on its child in slot `child_idx`.
138    fn reduce_parent(
139        &self,
140        child: &Plan<C>,
141        parent: &Plan<Self::Parent>,
142        child_idx: usize,
143        session: &VortexSession,
144    ) -> VortexResult<Option<PlanRef>>;
145}
146
147/// Type-erased interface used by [`PlanParentRuleSet`].
148pub trait DynPlanParentReduceRule: Debug + Send + Sync + 'static {
149    /// Returns whether this rule supports the concrete child and parent operators.
150    fn matches(&self, child: &PlanRef, parent: &PlanRef) -> bool;
151
152    /// Attempts to replace `parent` based on `child` in slot `child_idx`.
153    fn reduce_parent(
154        &self,
155        child: &PlanRef,
156        parent: &PlanRef,
157        child_idx: usize,
158        session: &VortexSession,
159    ) -> VortexResult<Option<PlanRef>>;
160}
161
162/// Bridges a typed [`PlanParentReduceRule`] to a type-erased static registry.
163pub struct PlanParentReduceRuleAdapter<C, R> {
164    rule: R,
165    _child: PhantomData<fn() -> C>,
166}
167
168impl<C, R> PlanParentReduceRuleAdapter<C, R> {
169    /// Creates an adapter for a typed parent-child rule.
170    pub const fn new(rule: R) -> Self {
171        Self {
172            rule,
173            _child: PhantomData,
174        }
175    }
176}
177
178impl<C, R> Debug for PlanParentReduceRuleAdapter<C, R>
179where
180    C: PlanVTable,
181    R: PlanParentReduceRule<C>,
182{
183    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        formatter
185            .debug_struct("PlanParentReduceRuleAdapter")
186            .field("parent", &type_name::<R::Parent>())
187            .field("child", &type_name::<C>())
188            .field("rule", &self.rule)
189            .finish()
190    }
191}
192
193impl<C, R> DynPlanParentReduceRule for PlanParentReduceRuleAdapter<C, R>
194where
195    C: PlanVTable,
196    R: PlanParentReduceRule<C>,
197{
198    fn matches(&self, child: &PlanRef, parent: &PlanRef) -> bool {
199        child.is::<C>() && parent.is::<R::Parent>()
200    }
201
202    fn reduce_parent(
203        &self,
204        child: &PlanRef,
205        parent: &PlanRef,
206        child_idx: usize,
207        session: &VortexSession,
208    ) -> VortexResult<Option<PlanRef>> {
209        let Some(child) = child.as_opt::<C>() else {
210            return Ok(None);
211        };
212        let Some(parent) = parent.as_opt::<R::Parent>() else {
213            return Ok(None);
214        };
215        self.rule.reduce_parent(child, parent, child_idx, session)
216    }
217}
218
219/// An ordered static collection of parent-child plan rewrite rules.
220pub struct PlanParentRuleSet {
221    rules: &'static [&'static dyn DynPlanParentReduceRule],
222}
223
224impl PlanParentRuleSet {
225    /// Creates a rule set whose first successful rewrite wins.
226    pub const fn new(rules: &'static [&'static dyn DynPlanParentReduceRule]) -> Self {
227        Self { rules }
228    }
229
230    /// Evaluates rules registered for the concrete `(parent, child)` pair.
231    pub fn evaluate(
232        &self,
233        child: &PlanRef,
234        parent: &PlanRef,
235        child_idx: usize,
236        session: &VortexSession,
237    ) -> VortexResult<Option<PlanRef>> {
238        for rule in self.rules {
239            if !rule.matches(child, parent) {
240                continue;
241            }
242            let Some(reduced) = rule.reduce_parent(child, parent, child_idx, session)? else {
243                continue;
244            };
245
246            #[cfg(debug_assertions)]
247            {
248                vortex_ensure_eq!(
249                    reduced.row_count(),
250                    parent.row_count(),
251                    "Plan rewrite from {rule:?} changed row count"
252                );
253                vortex_ensure_eq!(
254                    reduced.dtype(),
255                    parent.dtype(),
256                    "Plan rewrite from {rule:?} changed dtype"
257                );
258            }
259
260            return Ok(Some(reduced));
261        }
262        Ok(None)
263    }
264}