Skip to main content

vortex_scan/plan/builtins/take/
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::ops::Range;
8
9use vortex_array::Canonical;
10use vortex_array::EmptyMetadata;
11use vortex_array::IntoArray;
12use vortex_array::dtype::DType;
13use vortex_error::VortexResult;
14use vortex_expr::BoundExpression;
15use vortex_expr::BoundLabels;
16use vortex_expr::ExactBoundExpr;
17use vortex_expr::label_bound_tree;
18use vortex_functions::dynamic::DynamicComparison;
19use vortex_functions::is_negative_cost;
20use vortex_mask::Mask;
21use vortex_session::VortexSession;
22use vortex_session::registry::CachedId;
23
24use crate::execution::operators::OnceSource;
25use crate::execution::operators::TakeSource;
26use crate::execution::pipeline::Chain;
27use crate::execution::pipeline::Compiler;
28use crate::plan::Eval;
29use crate::plan::EvalPlan;
30use crate::plan::Plan;
31use crate::plan::PlanId;
32use crate::plan::PlanParts;
33use crate::plan::PlanRef;
34use crate::plan::PlanSlots;
35use crate::plan::PlanVTable;
36use crate::plan::Share;
37use crate::plan::optimizer::PlanParentReduceRule;
38
39const CODES: usize = 0;
40const VALUES: usize = 1;
41
42/// Indexes `values` by `codes`, with slots `[codes, values]`.
43#[derive(Clone, Debug)]
44pub struct Take;
45
46/// A plan that indexes one child by another.
47pub type TakePlan = Plan<Take>;
48
49impl TakePlan {
50    /// Creates a take from potentially unbuilt slots without validation.
51    ///
52    /// # Safety
53    ///
54    /// `slots` must be `[codes, values]`, both present; `codes` must have `row_count` rows; and
55    /// `dtype` must be the values dtype unioned with the codes nullability.
56    pub unsafe fn from_slots_unchecked(dtype: DType, row_count: u64, slots: PlanSlots) -> Self {
57        PlanParts {
58            vtable: Take,
59            dtype,
60            row_count,
61            slots,
62            data: (),
63        }
64        .into_typed()
65    }
66
67    /// Creates a take of `values` at `codes`.
68    ///
69    /// The row domain is that of `codes`, and the output dtype is that of `values`.
70    pub fn new(codes: PlanRef, values: PlanRef) -> Self {
71        let dtype = values
72            .dtype()
73            .union_nullability(codes.dtype().nullability());
74        let row_count = codes.row_count();
75        PlanParts {
76            vtable: Take,
77            dtype,
78            row_count,
79            slots: [codes, values].into(),
80            data: (),
81        }
82        .into_typed()
83    }
84
85    /// Returns the plan producing indices.
86    pub fn codes(&self) -> VortexResult<PlanRef> {
87        self.slot_required(CODES)
88    }
89
90    /// Returns the plan producing the values being indexed.
91    pub fn values(&self) -> VortexResult<PlanRef> {
92        self.slot_required(VALUES)
93    }
94}
95
96impl PlanVTable for Take {
97    type PlanData = ();
98    type Metadata = EmptyMetadata;
99
100    fn id(&self) -> PlanId {
101        static ID: CachedId = CachedId::new("vortex.plan.take");
102        *ID
103    }
104
105    fn metadata(_plan: &Plan<Self>) -> Option<Self::Metadata> {
106        Some(EmptyMetadata)
107    }
108
109    fn with_slots(
110        plan: &Plan<Self>,
111        slots: &PlanSlots,
112        _data: &mut Self::PlanData,
113    ) -> VortexResult<()> {
114        slots.check_len("Take", 2)?;
115        let codes = slots.required(CODES)?;
116        let values = slots.required(VALUES)?;
117        let dtype = values
118            .dtype()
119            .union_nullability(codes.dtype().nullability());
120        if codes.row_count() != plan.row_count() || &dtype != plan.dtype() {
121            vortex_error::vortex_bail!("Take child shape does not match the plan output");
122        }
123        Ok(())
124    }
125
126    fn slot_name(_plan: &Plan<Self>, index: usize) -> Cow<'_, str> {
127        match index {
128            CODES => Cow::Borrowed("codes"),
129            VALUES => Cow::Borrowed("values"),
130            _ => Cow::Owned(format!("slot[{index}]")),
131        }
132    }
133
134    /// A take whose values an earlier scan of the split produced looks its codes up in them;
135    /// otherwise it joins its codes with the whole of its values.
136    fn compile(
137        plan: &Plan<Self>,
138        rows: Range<u64>,
139        mask: &Mask,
140        compiler: &mut Compiler<'_>,
141    ) -> VortexResult<Option<Chain>> {
142        let Some(codes) = compiler.compile(&plan.codes()?, rows, mask)? else {
143            return Ok(None);
144        };
145        let cache = compiler.values().clone();
146        let values_plan = plan.values()?;
147        if let Some(values) = cache.get(&values_plan) {
148            let source = TakeSource::new(plan.clone(), Some(values), None);
149            return Ok(Some(compiler.join(vec![codes], source)));
150        }
151        let values = values_plan;
152        let values_rows = 0..values.row_count();
153        let len = usize::try_from(values_rows.end)?;
154        let values = match compiler.compile(&values, values_rows, &Mask::new_true(len))? {
155            Some(values) => values,
156            None => Chain::new(OnceSource::new(
157                Canonical::empty(values.dtype()).into_array(),
158            )),
159        };
160        let source = TakeSource::new(plan.clone(), None, Some(cache));
161        Ok(Some(compiler.join_with(
162            vec![codes, values],
163            TakeSource::capacity,
164            source,
165        )))
166    }
167}
168
169/// Pushes an expression, or the part of it that reads the values, onto the dictionary values of
170/// a [`Take`].
171///
172/// Evaluating over values rather than codes is only sound for infallible expressions, since values
173/// no selected row references are evaluated too, and, when codes may be null, strict ones:
174/// otherwise per-row behaviour is not preserved.
175///
176/// A boolean expression is pushed whole onto the values as they are, so it stays above any
177/// [`Share`] of them. Otherwise the largest part holding every read of the values and built only
178/// from negative-cost functions, such as the byte length in `cast(byte_length($))`, is pushed
179/// beneath the share, since it is cheaper over the encoded values than canonicalizing them; the
180/// rest stays above the take.
181#[derive(Debug)]
182pub(crate) struct ExpressionTakeRule;
183
184/// Per expression node: whether it reads the root, and whether it is strict, infallible, and built
185/// only from negative-cost functions.
186type Labels = BoundLabels<(bool, bool, bool, bool)>;
187
188impl PlanParentReduceRule<Take> for ExpressionTakeRule {
189    type Parent = Eval;
190
191    fn reduce_parent(
192        &self,
193        child: &Plan<Take>,
194        parent: &Plan<Eval>,
195        _child_idx: usize,
196        _session: &VortexSession,
197    ) -> VortexResult<Option<PlanRef>> {
198        let expression = parent.expression();
199        // A dynamic comparison stays above the take: evaluated per batch it reads the latest
200        // bound, and the dictionary batches the take emits evaluate it over their values anyway.
201        // Values it never reaches can always be kept between scans.
202        if expression.contains::<DynamicComparison>()? {
203            return Ok(None);
204        }
205        // Strictness keeps a null code null. Without null codes every row takes its value's result.
206        let codes_nullable = child.codes()?.dtype().is_nullable();
207        let labels = label_bound_tree(
208            expression,
209            |node| match node.as_scalar() {
210                Some(scalar_fn) => (
211                    false,
212                    scalar_fn.signature().is_strict() || !codes_nullable,
213                    scalar_fn.signature().is_infallible(),
214                    is_negative_cost(scalar_fn.id()),
215                ),
216                None => (true, true, true, true),
217            },
218            |acc, &child| {
219                (
220                    acc.0 | child.0,
221                    acc.1 & child.1,
222                    acc.2 & child.2,
223                    acc.3 & child.3,
224                )
225            },
226        );
227        let label = |node: &BoundExpression| {
228            labels
229                .get(&ExactBoundExpr(node.clone()))
230                .copied()
231                .unwrap_or((false, false, false, false))
232        };
233
234        let (references_root, is_strict, is_infallible, is_negative_cost) = label(expression);
235        if references_root && is_strict && is_infallible && !is_negative_cost {
236            if !expression.dtype().is_boolean() {
237                return Ok(None);
238            }
239            let values = child.values()?;
240            let Some(expression) = rebind_root(expression, child.dtype(), values.dtype()) else {
241                return Ok(None);
242            };
243            let values = EvalPlan::try_new(expression, values)?.into_plan();
244            let take = TakePlan::new(child.codes()?, values).into_plan();
245            if take.dtype() != parent.dtype() {
246                return Ok(None);
247            }
248            return Ok(Some(take));
249        }
250
251        let Some(inner) = negative_cost_part(expression, &labels) else {
252            return Ok(None);
253        };
254        let values = child.values()?;
255        let values = match values.as_opt::<Share>() {
256            Some(share) => share.child_plan()?,
257            None => values,
258        };
259        let Some(pushed) = rebind_root(&inner, child.dtype(), values.dtype()) else {
260            return Ok(None);
261        };
262        let values = EvalPlan::try_new(pushed, values)?.into_plan();
263        let take = TakePlan::new(child.codes()?, values).into_plan();
264        let outer = replace(
265            expression,
266            &inner,
267            &BoundExpression::new_root(take.dtype().clone()),
268        )?;
269        if outer.dtype() != expression.dtype() {
270            return Ok(None);
271        }
272        if outer.is_root() {
273            return Ok(Some(take));
274        }
275        Ok(Some(EvalPlan::try_new(outer, take)?.into_plan()))
276    }
277}
278
279/// The largest strict, infallible, negative-cost part of `expression` holding every read of the
280/// root, unless that is the bare root.
281fn negative_cost_part(expression: &BoundExpression, labels: &Labels) -> Option<BoundExpression> {
282    let (references_root, is_strict, is_infallible, is_negative_cost) =
283        labels.get(&ExactBoundExpr(expression.clone())).copied()?;
284    if !references_root {
285        return None;
286    }
287    if is_strict && is_infallible && is_negative_cost {
288        return (!expression.is_root()).then(|| expression.clone());
289    }
290    let mut reading = expression.children().iter().filter(|child| {
291        labels
292            .get(&ExactBoundExpr((*child).clone()))
293            .is_some_and(|label| label.0)
294    });
295    let child = reading.next()?;
296    if reading.next().is_some() {
297        return None;
298    }
299    negative_cost_part(child, labels)
300}
301
302/// `expression`, bound to the take's dtype `from`, bound instead to its values' dtype `to`, or
303/// `None` when it does not apply there.
304///
305/// Values are less nullable than the take when its codes may be null: the take's nulls come from
306/// its codes, which a strict expression keeps null.
307fn rebind_root(expression: &BoundExpression, from: &DType, to: &DType) -> Option<BoundExpression> {
308    if from == to {
309        return Some(expression.clone());
310    }
311    replace(
312        expression,
313        &BoundExpression::new_root(from.clone()),
314        &BoundExpression::new_root(to.clone()),
315    )
316    .ok()
317}
318
319/// `expression` with each occurrence of `needle` replaced by `replacement`.
320fn replace(
321    expression: &BoundExpression,
322    needle: &BoundExpression,
323    replacement: &BoundExpression,
324) -> VortexResult<BoundExpression> {
325    if ExactBoundExpr(expression.clone()) == ExactBoundExpr(needle.clone()) {
326        return Ok(replacement.clone());
327    }
328    if expression.children().is_empty() {
329        return Ok(expression.clone());
330    }
331    let children = expression
332        .children()
333        .iter()
334        .map(|child| replace(child, needle, replacement))
335        .collect::<VortexResult<Vec<_>>>()?;
336    expression.clone().with_children(children)
337}