Skip to main content

vortex_scan/plan/
partition.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! We have Plans which tell us how data is stored and how to read it. An
5//! Expression is a subset of a Plan which tells us how to read the data but
6//! doesn't know how the data is stored.
7//!
8//! Given a plan graph and an expression graph, we want to know which
9//! expressions can be pushed down to plan's children. For this we need to know
10//! which expressions operate on plan's disjoint slots (children).
11//!
12//! So, for an expression the rule (property) is "Given a plan and an
13//! expression graph, if you see this expression, it needs the following slots
14//! from a plan". Let's look at an example.
15//!
16//! If we have a non-nullable PackPlan(a: .., b: .., c: ..) and an Expression
17//! $.a > 5 && $.b < 1, we know that $.a > 5 and $.b < 1 are disjoint over the
18//! plan, and we never read "c". We know this because $.a and $.b (get_item)
19//! have a rule for a PackPlan which returns us one field.
20//!
21//! Thus we partition the expression into two parts: $.a > 5 references child
22//! plan for "a" of PackPlan, and we rewrite the expression over this plan to $
23//! > 5, same for $.b < 1.
24//!
25//! $.a > 5 over pack(a: child_plan) => $ > 5 over child_plan
26//!
27//! We also need a way to combine these parts back into an Expression. If we
28//! call these partitions 0 and 1, the combiner Expression is $.0 && $.1.
29//!
30//! $.a > 5 && $.b < 1 over pack(a: ..., b: ..., c: ...) =>
31//! {0: $ > 5, 1: $ < 1} and a combiner $.0 && $.1
32//!
33//! An invariant that must hold in rules is "combiner expression references
34//! exactly the slots it has requested to read from the plan".
35//!
36//! See register_pack_partition_rules and register_row_idx_partition_rules for
37//! examples.
38
39use std::any::Any;
40use std::array;
41use std::cell::RefCell;
42use std::fmt;
43use std::hash::Hash;
44use std::sync::LazyLock;
45
46use vortex_array::dtype::DType;
47use vortex_array::dtype::FieldName;
48use vortex_array::dtype::Nullability;
49use vortex_array::dtype::StructFields;
50use vortex_array::expr::BoundExpression;
51use vortex_array::scalar_fn::ScalarFnId;
52use vortex_array::scalar_fn::ScalarFnRef;
53use vortex_array::scalar_fn::ScalarFnVTable;
54use vortex_array::scalar_fn::builtin::get_item::GetItem;
55use vortex_error::VortexExpect;
56use vortex_error::VortexResult;
57use vortex_error::vortex_ensure;
58use vortex_error::vortex_err;
59use vortex_expr as unbound;
60use vortex_expr::Expression;
61use vortex_expr::bound::pack;
62use vortex_expr::traversal::NodeExt;
63use vortex_expr::traversal::Transformed;
64use vortex_expr::traversal::TraversalOrder;
65use vortex_session::ArcSwapMap;
66use vortex_session::SessionExt;
67use vortex_session::SessionVar;
68use vortex_session::VortexSession;
69use vortex_utils::aliases::hash_map::HashMap;
70use vortex_utils::aliases::hash_set::HashSet;
71
72use crate::plan::PlanId;
73use crate::plan::PlanVTable;
74use crate::plan::register_pack_partition_rules;
75use crate::plan::register_row_idx_partition_rules;
76
77/// A PartitionedPlan is a plan which has some logical meaning for its slots
78/// and allows partitioning an Expression over itself.
79pub trait PartitionedPlan: PlanVTable {
80    /// Each plan has slots which are numbers. This is the logical type for
81    /// these numbers.
82    /// For example, Pack has slots 0...n, first one is a validity.
83    /// This type for Pack is therefore Slot { Validity, Field(usize) }.
84    type Slot: Copy + Into<PlanSlot>;
85
86    /// Returns the logical dtype of a slot within `scope`.
87    fn slot_dtype(scope: &DType, slot: Self::Slot) -> VortexResult<DType>;
88
89    // You likely want to write a PartitionRule instead of overriding this
90    // method
91    /// Partitions an expression over this plan's independent child slots.
92    fn partition(
93        &self,
94        scope: &DType,
95        expr: &BoundExpression,
96        session: &VortexSession,
97    ) -> VortexResult<PartitionedExpression> {
98        partition_impl(scope, expr, self.id(), session)
99    }
100}
101
102/// A rule describing which plan slots an expression reads.
103pub trait PartitionRule: Send + Sync + 'static {
104    /// The plan whose slots this rule describes.
105    type Plan: PartitionedPlan;
106    /// For a plan and an expression, answer which plan's slots does this
107    /// expression use.
108    fn apply(
109        &self,
110        slots: &Slots<'_, Self::Plan>,
111        node: &BoundExpression,
112        // Return type is unbound because its type is only known after traversing
113        // the whole tree
114    ) -> VortexResult<Option<Expression>>;
115}
116
117/// Session state for partitioning expression over plans
118#[derive(Clone)]
119pub struct PartitionSession {
120    /// Rules for expression partitioning. $ stores None.
121    rules: ArcSwapMap<(PlanId, Option<ScalarFnId>), &'static dyn DynPartitionRule>,
122}
123
124impl PartitionSession {
125    /// Register a rule which allows to partition $ over a plan.
126    /// For example, if you have an expression $ < 5 && $ > 1, this rule will
127    /// run on each of $.
128    pub fn register_root_rule<Rule: PartitionRule>(&self, plan: Rule::Plan, rule: &'static Rule) {
129        self.rules.insert((plan.id(), None), rule);
130    }
131
132    /// Register a rule which allows to partition a scalar function over a plan
133    pub fn register_rule<Rule: PartitionRule>(
134        &self,
135        plan: Rule::Plan,
136        scalar_fn: impl ScalarFnVTable,
137        rule: &'static Rule,
138    ) {
139        self.rules.insert((plan.id(), Some(scalar_fn.id())), rule);
140    }
141
142    fn rule(
143        &self,
144        plan: PlanId,
145        scalar_fn: Option<ScalarFnId>,
146    ) -> Option<&'static dyn DynPartitionRule> {
147        self.rules.get(&(plan, scalar_fn))
148    }
149}
150
151/// Struct { i: dtype } for i in dtypes
152fn positional_scope(dtypes: Vec<DType>) -> DType {
153    DType::Struct(
154        StructFields::new((0..dtypes.len()).map(positional_name).collect(), dtypes),
155        Nullability::NonNullable,
156    )
157}
158
159/// Plan's child slot index
160pub type PlanSlot = usize;
161
162/// Slot references recorded while a partition rule builds its expression.
163pub struct Slots<'a, Plan: PartitionedPlan> {
164    scope: &'a DType,
165    reads: RefCell<HashMap<PlanSlot, Plan::Slot>>,
166}
167
168impl<'a, Plan: PartitionedPlan> Slots<'a, Plan> {
169    fn new(scope: &'a DType) -> Self {
170        Self {
171            scope,
172            reads: RefCell::new(HashMap::default()),
173        }
174    }
175
176    /// Plan's type
177    pub fn scope(&self) -> &DType {
178        self.scope
179    }
180
181    /// References a slot and records it as required by the expression.
182    pub fn read(&self, slot: Plan::Slot) -> Expression {
183        let position = slot.into();
184        self.reads.borrow_mut().entry(position).or_insert(slot);
185        unbound::get_item(positional_name(position), unbound::root())
186    }
187
188    fn into_reads(self) -> VortexResult<HashMap<PlanSlot, DType>> {
189        self.reads
190            .into_inner()
191            .into_iter()
192            .map(|(position, slot)| Ok((position, Plan::slot_dtype(self.scope, slot)?)))
193            .collect()
194    }
195}
196
197/// The expression partitions and their recombination, or an unpartitioned expression.
198pub enum PartitionedExpression {
199    /// Expression doesn't reference plan's children
200    Any(BoundExpression),
201    /// Expression references one of plan's children
202    One(PlanSlot, BoundExpression),
203    /// Expression references many plan's children
204    Many(Partitions),
205}
206
207/// Independent expressions and the expression combining their results.
208pub struct Partitions {
209    /// Combine "partitions" back into an Expression
210    pub combiner: BoundExpression,
211    /// The independent slot expressions, in combiner field order.
212    pub partitions: Vec<Partition>,
213}
214
215/// An expression over one plan slot.
216pub struct Partition {
217    /// The child slot evaluated by this expression.
218    pub slot: PlanSlot,
219    /// The expression bound against the slot dtype.
220    pub expr: BoundExpression,
221}
222
223struct RuleOutput {
224    expr: Expression,
225    reads: HashMap<PlanSlot, DType>,
226}
227
228trait DynPartitionRule: Send + Sync {
229    fn run(&self, scope: &DType, node: &BoundExpression) -> VortexResult<Option<RuleOutput>>;
230}
231
232impl<Rule: PartitionRule> DynPartitionRule for Rule {
233    fn run(&self, scope: &DType, node: &BoundExpression) -> VortexResult<Option<RuleOutput>> {
234        let slots = Slots::<Rule::Plan>::new(scope);
235        let Some(expr) = self.apply(&slots, node)? else {
236            return Ok(None);
237        };
238        Ok(Some(RuleOutput {
239            expr,
240            reads: slots.into_reads()?,
241        }))
242    }
243}
244
245fn partition_impl(
246    scope: &DType,
247    expr: &BoundExpression,
248    source: PlanId,
249    session: &VortexSession,
250) -> VortexResult<PartitionedExpression> {
251    let rules = session.get::<PartitionSession>();
252    let mut partitioner = Partitioner {
253        scope,
254        source,
255        rules: &rules,
256        parts: Ordered::default(),
257        substituted: false,
258    };
259    let root = match partitioner.visit(expr)? {
260        Analyzed::None(expr) => return Ok(PartitionedExpression::Any(expr)),
261        Analyzed::One(slot, expr) => return Ok(PartitionedExpression::One(slot, expr)),
262        Analyzed::Many(root) => root,
263    };
264
265    let mut partitions = Vec::with_capacity(partitioner.parts.items.len());
266    let mut dtypes = Vec::with_capacity(partitions.capacity());
267    let mut flattened = HashSet::default();
268    for (i, part) in partitioner.parts.items.into_iter().enumerate() {
269        if part.exprs.items.len() == 1 {
270            flattened.insert(positional_name(i));
271        }
272        let expr = pack_by_position(part.exprs.items);
273        dtypes.push(expr.dtype().clone());
274        partitions.push(Partition {
275            slot: part.slot,
276            expr,
277        });
278    }
279
280    let root = if flattened.is_empty() {
281        root
282    } else {
283        flatten_refs(root, &flattened)?
284    };
285    let mut combiner = root.bind(&positional_scope(dtypes))?;
286    if partitioner.substituted {
287        combiner = combiner.optimize_recursive()?;
288    }
289    Ok(PartitionedExpression::Many(Partitions {
290        combiner,
291        partitions,
292    }))
293}
294
295fn pack_by_position(mut exprs: Vec<BoundExpression>) -> BoundExpression {
296    if exprs.len() == 1 {
297        return exprs.pop().vortex_expect("a single child");
298    }
299    let names = exprs
300        .into_iter()
301        .enumerate()
302        .map(|(sub, expr)| (positional_name(sub), expr));
303    pack(names, Nullability::NonNullable)
304}
305
306enum Analyzed {
307    /// References no children
308    None(BoundExpression),
309    /// References one child
310    One(PlanSlot, BoundExpression),
311    /// References many children and is therefore replaced with a new $
312    Many(Expression),
313}
314
315#[derive(Clone, Copy)]
316enum Refs {
317    None,
318    One(PlanSlot),
319    Many,
320}
321
322impl Refs {
323    fn with(self, child: &Analyzed) -> Self {
324        match (self, child) {
325            (Refs::Many, _) | (_, Analyzed::Many(_)) => Refs::Many,
326            (refs, Analyzed::None(_)) => refs,
327            (Refs::None, Analyzed::One(slot, _)) => Refs::One(*slot),
328            (Refs::One(current), Analyzed::One(slot, _)) if current == *slot => self,
329            (Refs::One(_), Analyzed::One(..)) => Refs::Many,
330        }
331    }
332}
333
334struct Partitioner<'r> {
335    scope: &'r DType,
336    source: PlanId,
337    rules: &'r PartitionSession,
338    parts: Ordered<PlanSlot, Part>,
339    substituted: bool,
340}
341
342struct Part {
343    slot: PlanSlot,
344    exprs: Ordered<BoundExpression, BoundExpression>,
345}
346
347impl Partitioner<'_> {
348    fn visit(&mut self, node: &BoundExpression) -> VortexResult<Analyzed> {
349        if let Some(output) = self.apply_rule(node)? {
350            return self.replaced(output);
351        }
352        let scalar_fn = node
353            .as_scalar()
354            .ok_or_else(|| vortex_err!("$ has no partition rule"))?;
355
356        let mut refs = Refs::None;
357        let mut children = Vec::with_capacity(node.children().len());
358        for child in node.children() {
359            let analyzed = self.visit(child)?;
360            refs = refs.with(&analyzed);
361            children.push(analyzed);
362        }
363        match refs {
364            Refs::None => Ok(Analyzed::None(bound(scalar_fn, children)?)),
365            Refs::One(slot) => Ok(Analyzed::One(slot, bound(scalar_fn, children)?)),
366            Refs::Many => Ok(Analyzed::Many(self.unbound(scalar_fn, children)?)),
367        }
368    }
369
370    fn unbound(
371        &mut self,
372        scalar_fn: &ScalarFnRef,
373        children: Vec<Analyzed>,
374    ) -> VortexResult<Expression> {
375        let children = children
376            .into_iter()
377            .map(|child| match child {
378                Analyzed::None(expr) => to_unbound(&expr),
379                Analyzed::One(slot, expr) => Ok(self.cut(slot, expr)),
380                Analyzed::Many(expr) => Ok(expr),
381            })
382            .collect::<VortexResult<Vec<_>>>()?;
383        Expression::try_new(scalar_fn.clone(), children)
384    }
385
386    fn apply_rule(&self, node: &BoundExpression) -> VortexResult<Option<RuleOutput>> {
387        if !node.children().iter().all(BoundExpression::is_root) {
388            return Ok(None);
389        }
390        let scalar_fn = node.as_scalar().map(|scalar_fn| scalar_fn.id());
391        let rule = self.rules.rule(self.source, scalar_fn);
392        rule.map_or(Ok(None), |rule| rule.run(self.scope, node))
393    }
394
395    fn replaced(&mut self, output: RuleOutput) -> VortexResult<Analyzed> {
396        let RuleOutput { expr, reads } = output;
397        if reads.len() > 1 {
398            self.substituted = true;
399            return Ok(Analyzed::Many(self.cut_slots(expr, &reads)?));
400        }
401        match reads.into_iter().next() {
402            None => Ok(Analyzed::None(bind_part(&expr, None)?)),
403            Some((slot, dtype)) => Ok(Analyzed::One(slot, bind_part(&expr, Some(&dtype))?)),
404        }
405    }
406
407    fn cut_slots(
408        &mut self,
409        expr: Expression,
410        reads: &HashMap<PlanSlot, DType>,
411    ) -> VortexResult<Expression> {
412        let cut = expr.transform_down(|node| {
413            let Some(slot) = slot_of_read(&node)? else {
414                vortex_ensure!(!node.is_root(), "Slots must be read");
415                return Ok(Transformed::no(node));
416            };
417            let dtype = reads
418                .get(&slot)
419                .ok_or_else(|| vortex_err!("Slot {slot} was not read"))?;
420            Ok(replace(
421                self.cut(slot, BoundExpression::new_root(dtype.clone())),
422            ))
423        })?;
424        Ok(cut.into_inner())
425    }
426
427    fn cut(&mut self, slot: PlanSlot, expr: BoundExpression) -> Expression {
428        let part = self.parts.position(slot, || Part {
429            slot,
430            exprs: Ordered::default(),
431        });
432        let sub = self.parts.items[part]
433            .exprs
434            .position(expr.clone(), move || expr);
435        unbound::get_item(
436            positional_name(sub),
437            unbound::get_item(positional_name(part), unbound::root()),
438        )
439    }
440}
441
442fn slot_of_read(expr: &Expression) -> VortexResult<Option<PlanSlot>> {
443    let Some(name) = expr.as_opt::<GetItem>() else {
444        return Ok(None);
445    };
446    if !expr.child(0).is_root() {
447        return Ok(None);
448    }
449    name.as_ref()
450        .parse()
451        .map(Some)
452        .map_err(|_| vortex_err!("{name} is not a slot read"))
453}
454
455fn bound(scalar_fn: &ScalarFnRef, children: Vec<Analyzed>) -> VortexResult<BoundExpression> {
456    let exprs = children
457        .into_iter()
458        .map(|child| match child {
459            Analyzed::None(expr) | Analyzed::One(_, expr) => Ok(expr),
460            Analyzed::Many(_) => Err(vortex_err!("multiple slot referencing child")),
461        })
462        .collect::<VortexResult<Vec<_>>>()?;
463    BoundExpression::try_new(scalar_fn.clone(), exprs)
464}
465
466fn replace(value: Expression) -> Transformed<Expression> {
467    Transformed {
468        value,
469        order: TraversalOrder::Skip,
470        changed: true,
471    }
472}
473
474fn bind_part(expr: &Expression, root: Option<&DType>) -> VortexResult<BoundExpression> {
475    if slot_of_read(expr)?.is_some() {
476        let dtype = root.ok_or_else(|| vortex_err!("Part reads a slot it does not have"))?;
477        return Ok(BoundExpression::new_root(dtype.clone()));
478    }
479    let scalar_fn = expr
480        .as_scalar()
481        .ok_or_else(|| vortex_err!("Slots must be read"))?;
482    let children = expr
483        .children()
484        .iter()
485        .map(|child| bind_part(child, root))
486        .collect::<VortexResult<Vec<_>>>()?;
487    BoundExpression::try_new(scalar_fn.clone(), children)
488}
489
490const NAMES_LEN: usize = 100;
491static NAMES: LazyLock<[FieldName; NAMES_LEN]> =
492    LazyLock::new(|| array::from_fn(|position| FieldName::from(format!("{position}"))));
493pub(crate) fn positional_name(slot: PlanSlot) -> FieldName {
494    let name = NAMES.get(slot);
495    name.cloned().unwrap_or_else(|| format!("{slot}").into())
496}
497
498struct Ordered<K, V> {
499    index: HashMap<K, usize>,
500    items: Vec<V>,
501}
502
503impl<K, V> Default for Ordered<K, V> {
504    fn default() -> Self {
505        Self {
506            index: HashMap::default(),
507            items: Vec::new(),
508        }
509    }
510}
511
512impl<K: Hash + Eq, V> Ordered<K, V> {
513    fn position(&mut self, key: K, value: impl FnOnce() -> V) -> usize {
514        let items = &mut self.items;
515        *self.index.entry(key).or_insert_with(|| {
516            items.push(value());
517            items.len() - 1
518        })
519    }
520}
521
522fn to_unbound(expr: &BoundExpression) -> VortexResult<Expression> {
523    let scalar_fn = expr
524        .as_scalar()
525        .ok_or_else(|| vortex_err!("Expression without slots references $"))?;
526    let children = expr
527        .children()
528        .iter()
529        .map(to_unbound)
530        .collect::<VortexResult<Vec<_>>>()?;
531    Expression::try_new(scalar_fn.clone(), children)
532}
533
534/// References produced in cut() have two levels. If reference is used only
535/// once, we can remove one level of indirection here. $.0.x -> $.x
536fn flatten_refs(root: Expression, flattened: &HashSet<FieldName>) -> VortexResult<Expression> {
537    let flat = root.transform_down(|node| match flat_ref(&node, flattened) {
538        Some(inner) => Ok(replace(inner.clone())),
539        None => Ok(Transformed::no(node)),
540    })?;
541    Ok(flat.into_inner())
542}
543
544fn flat_ref<'a>(node: &'a Expression, flattened: &HashSet<FieldName>) -> Option<&'a Expression> {
545    let name = node.as_opt::<GetItem>()?;
546    if *name != positional_name(0) {
547        return None;
548    }
549    let inner = node.child(0);
550    let part = inner.as_opt::<GetItem>()?;
551    (inner.child(0).is_root() && flattened.contains(part)).then_some(inner)
552}
553
554impl Default for PartitionSession {
555    fn default() -> Self {
556        let this = Self {
557            rules: ArcSwapMap::default(),
558        };
559        register_pack_partition_rules(&this);
560        register_row_idx_partition_rules(&this);
561        this
562    }
563}
564
565impl fmt::Debug for PartitionSession {
566    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567        f.debug_struct("PartitionSession").finish_non_exhaustive()
568    }
569}
570
571impl SessionVar for PartitionSession {
572    fn as_any(&self) -> &dyn Any {
573        self
574    }
575
576    fn as_any_mut(&mut self) -> &mut dyn Any {
577        self
578    }
579}