Skip to main content

vortex_scan/plan/builtins/eval/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4pub(crate) mod execute;
5
6use std::borrow::Cow;
7use std::fmt;
8use std::ops::Range;
9
10use vortex_array::EmptyMetadata;
11use vortex_array::dtype::Nullability;
12use vortex_array::dtype::StructFields;
13use vortex_array::scalar_fn::builtin::pack::Pack;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_bail;
17use vortex_expr::BoundExpression;
18use vortex_expr::traversal::NodeExt;
19use vortex_expr::traversal::Transformed;
20use vortex_expr::traversal::TraversalOrder;
21use vortex_mask::Mask;
22use vortex_session::VortexSession;
23use vortex_session::registry::CachedId;
24
25use crate::execution::operators::EvalStage;
26use crate::execution::pipeline::Chain;
27use crate::execution::pipeline::Compiler;
28use crate::plan::PackPlan;
29use crate::plan::Plan;
30use crate::plan::PlanId;
31use crate::plan::PlanParts;
32use crate::plan::PlanRef;
33use crate::plan::PlanSlots;
34use crate::plan::PlanVTable;
35use crate::plan::optimizer::PlanParentReduceRule;
36use crate::plan::optimizer::PlanReduceRule;
37
38/// Applies an expression to the output of its child.
39#[derive(Clone, Debug)]
40pub struct Eval;
41
42/// The expression evaluated by an [`Eval`].
43#[derive(Clone, Debug)]
44pub struct EvalData {
45    expression: BoundExpression,
46}
47
48/// A plan that applies an expression to its child.
49pub type EvalPlan = Plan<Eval>;
50
51impl EvalPlan {
52    /// Creates an evaluation of `expression`, which must be bound to the child's dtype.
53    pub fn try_new(expression: BoundExpression, child: PlanRef) -> VortexResult<Self> {
54        validate_expression_child(&expression, &child)?;
55
56        // SAFETY: The expression root dtype was validated against the child dtype above.
57        Ok(unsafe { Self::new_unchecked(expression, child) })
58    }
59
60    /// Creates an evaluation without validating the expression's root dtype.
61    ///
62    /// # Safety
63    ///
64    /// Every scope root in `expression` must have the same dtype as `child`.
65    pub unsafe fn new_unchecked(expression: BoundExpression, child: PlanRef) -> Self {
66        PlanParts {
67            vtable: Eval,
68            dtype: expression.dtype().clone(),
69            row_count: child.row_count(),
70            slots: [child].into(),
71            data: EvalData { expression },
72        }
73        .into_typed()
74    }
75
76    /// Returns the expression evaluated by this plan.
77    pub fn expression(&self) -> &BoundExpression {
78        &self.data().expression
79    }
80
81    /// Returns the child plan supplying the expression root.
82    pub fn child_plan(&self) -> VortexResult<PlanRef> {
83        self.slot_required(0)
84    }
85}
86
87impl PlanVTable for Eval {
88    type PlanData = EvalData;
89    type Metadata = EmptyMetadata;
90
91    fn id(&self) -> PlanId {
92        static ID: CachedId = CachedId::new("vortex.plan.eval");
93        *ID
94    }
95
96    fn fmt(plan: &Plan<Self>, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(formatter, " expr={}", plan.expression())
98    }
99
100    fn metadata(_plan: &Plan<Self>) -> Option<Self::Metadata> {
101        // Expressions serialize through `vortex.expr` protobuf, which is not wired up here yet.
102        None
103    }
104
105    fn with_slots(
106        plan: &Plan<Self>,
107        slots: &PlanSlots,
108        _data: &mut Self::PlanData,
109    ) -> VortexResult<()> {
110        slots.check_len("Eval", 1)?;
111        let child = slots.required(0)?;
112        validate_expression_child(plan.expression(), child)?;
113        if child.row_count() != plan.row_count() {
114            vortex_error::vortex_bail!(
115                "Eval child has {} rows but the plan has {}",
116                child.row_count(),
117                plan.row_count()
118            );
119        }
120        Ok(())
121    }
122
123    fn slot_name(_plan: &Plan<Self>, index: usize) -> Cow<'_, str> {
124        if index == 0 {
125            Cow::Borrowed("child")
126        } else {
127            Cow::Owned(format!("slot[{index}]"))
128        }
129    }
130
131    fn compile(
132        plan: &Plan<Self>,
133        rows: Range<u64>,
134        mask: &Mask,
135        compiler: &mut Compiler<'_>,
136    ) -> VortexResult<Option<Chain>> {
137        let chain = compiler.compile(&plan.child_plan()?, rows, mask)?;
138        Ok(chain.map(|chain| chain.with(EvalStage::new(plan.expression().clone()))))
139    }
140}
141
142fn validate_expression_child(expression: &BoundExpression, child: &PlanRef) -> VortexResult<()> {
143    if !expression.is_root_bound_to(child.dtype()) {
144        vortex_bail!(
145            "Eval expression is not bound to child dtype {}",
146            child.dtype()
147        );
148    }
149    Ok(())
150}
151
152/// Removes an [`Eval`] whose expression is the identity expression.
153#[derive(Debug)]
154pub(crate) struct EvalIdentityRule;
155
156impl PlanReduceRule<Eval> for EvalIdentityRule {
157    fn reduce(&self, plan: &Plan<Eval>, _session: &VortexSession) -> VortexResult<Option<PlanRef>> {
158        if plan.expression().is_root() {
159            Ok(Some(plan.child_plan()?))
160        } else {
161            Ok(None)
162        }
163    }
164}
165
166/// Eval(expr1, Eval(expr2)) -> Eval(expr1 . expr2)
167#[derive(Debug)]
168pub(crate) struct EvalEvalRule;
169impl PlanParentReduceRule<Eval> for EvalEvalRule {
170    type Parent = Eval;
171    fn reduce_parent(
172        &self,
173        child: &Plan<Eval>,
174        parent: &Plan<Eval>,
175        _: usize,
176        _session: &VortexSession,
177    ) -> VortexResult<Option<PlanRef>> {
178        let child_expr = child.expression();
179        let expr = parent.expression().clone().transform_down(|expr| {
180            if !expr.is_root() {
181                return Ok(Transformed::no(expr));
182            }
183            Ok(Transformed {
184                value: child_expr.clone(),
185                order: TraversalOrder::Skip,
186                changed: true,
187            })
188        })?;
189        // We want to fold repeated expressions like ($.a).b -> $.a.b.
190        let expr = expr.into_inner().optimize()?;
191        let plan = EvalPlan::try_new(expr, child.child_plan()?)?;
192        Ok(Some(plan.into_plan()))
193    }
194}
195
196/// Eval(pack({0: expr})) -> PackPlan(expr) for a non-nullable pack
197#[derive(Debug)]
198pub(crate) struct EvalPackRule;
199impl PlanReduceRule<Eval> for EvalPackRule {
200    fn reduce(&self, plan: &Plan<Eval>, _session: &VortexSession) -> VortexResult<Option<PlanRef>> {
201        let Some(expr) = plan.expression.as_opt::<Pack>() else {
202            return Ok(None);
203        };
204        if expr.nullability != Nullability::NonNullable {
205            return Ok(None);
206        }
207        let [child_expr] = plan.expression.children() else {
208            return Ok(None);
209        };
210        let fields = StructFields::new(expr.names.clone(), vec![child_expr.dtype().clone()]);
211
212        let child_plan = plan.slot(0)?.vortex_expect("no child plan");
213        let child_plan = EvalPlan::try_new(child_expr.clone(), child_plan)?.into_plan();
214
215        let plan = PackPlan::try_new(
216            fields,
217            Nullability::NonNullable,
218            plan.row_count(),
219            vec![child_plan],
220            None,
221        )?;
222        Ok(Some(plan.into_plan()))
223    }
224}