Skip to main content

vortex_scan/plan/builtins/
share.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::borrow::Cow;
5use std::ops::Range;
6
7use vortex_array::ArrayRef;
8use vortex_array::EmptyMetadata;
9use vortex_array::IntoArray;
10use vortex_array::optimizer::ArrayOptimizer;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_mask::Mask;
14use vortex_session::registry::CachedId;
15
16use crate::arrays::shared::Shared;
17use crate::execution::operators::OnceSource;
18use crate::execution::operators::UNBOUNDED;
19use crate::execution::operators::WholeSource;
20use crate::execution::pipeline::Chain;
21use crate::execution::pipeline::Compiler;
22use crate::plan::Plan;
23use crate::plan::PlanId;
24use crate::plan::PlanParts;
25use crate::plan::PlanRef;
26use crate::plan::PlanSlots;
27use crate::plan::PlanVTable;
28
29/// Produces its child's whole value once per split, as a
30/// [`SharedArray`](crate::arrays::shared::SharedArray) that the split's later scans reuse.
31///
32/// Dictionary values sit under a share. An expression the optimizer pushes onto the values stays
33/// above it, so the expression runs over values canonicalized once, and the projection reading the
34/// same dictionary finds them already canonical, rather than each evaluating over the encoded
35/// values.
36#[derive(Clone, Debug)]
37pub struct Share;
38
39/// Operator-specific data for a [`Share`] plan.
40#[derive(Clone, Debug, Default)]
41pub struct ShareData;
42
43/// A plan that shares its child's value between executions.
44pub type SharePlan = Plan<Share>;
45
46impl SharePlan {
47    /// Creates a share of `child`.
48    pub fn new(child: PlanRef) -> Self {
49        PlanParts {
50            vtable: Share,
51            dtype: child.dtype().clone(),
52            row_count: child.row_count(),
53            slots: [child].into(),
54            data: ShareData,
55        }
56        .into_typed()
57    }
58
59    /// Returns the shared plan.
60    pub fn child_plan(&self) -> VortexResult<PlanRef> {
61        self.slot_required(0)
62    }
63}
64
65impl PlanVTable for Share {
66    type PlanData = ShareData;
67    type Metadata = EmptyMetadata;
68
69    fn id(&self) -> PlanId {
70        static ID: CachedId = CachedId::new("vortex.plan.share");
71        *ID
72    }
73
74    fn metadata(_plan: &Plan<Self>) -> Option<Self::Metadata> {
75        Some(EmptyMetadata)
76    }
77
78    fn with_slots(
79        plan: &Plan<Self>,
80        slots: &PlanSlots,
81        _data: &mut Self::PlanData,
82    ) -> VortexResult<()> {
83        slots.check_len("Share", 1)?;
84        let child = slots.required(0)?;
85        if child.dtype() != plan.dtype() || child.row_count() != plan.row_count() {
86            vortex_bail!("Share child does not match the share's dtype and row count");
87        }
88        Ok(())
89    }
90
91    fn slot_name(_plan: &Plan<Self>, index: usize) -> Cow<'_, str> {
92        if index == 0 {
93            Cow::Borrowed("child")
94        } else {
95            Cow::Owned(format!("slot[{index}]"))
96        }
97    }
98
99    /// A share whose value an earlier scan of the split produced emits the selected rows of it;
100    /// otherwise it collects its child whole, keeps it for the split, and emits the selected
101    /// rows.
102    fn compile(
103        plan: &Plan<Self>,
104        rows: Range<u64>,
105        mask: &Mask,
106        compiler: &mut Compiler<'_>,
107    ) -> VortexResult<Option<Chain>> {
108        if mask.all_false() {
109            return Ok(None);
110        }
111        let cache = compiler.values().clone();
112        let shared = plan.clone().into_plan();
113        if let Some(value) = cache.get(&shared) {
114            return Ok(Some(Chain::new(OnceSource::new(selected_rows(
115                &value, &rows, mask,
116            )?))));
117        }
118        let child = plan.child_plan()?;
119        let len = usize::try_from(plan.row_count())?;
120        let Some(chain) = compiler.compile(&child, 0..plan.row_count(), &Mask::new_true(len))?
121        else {
122            return Ok(None);
123        };
124        let mask = mask.clone();
125        let source = WholeSource::new(plan.dtype().clone(), move |whole, cx| {
126            let whole = whole.optimize_ctx(cx.session())?;
127            let value = cache.insert(&shared, Shared::new(whole).into_array());
128            selected_rows(&value, &rows, &mask)
129        });
130        Ok(Some(compiler.join_with(vec![chain], |_| UNBOUNDED, source)))
131    }
132}
133
134/// The rows of `rows` that `mask` selects, from a whole shared value.
135fn selected_rows(value: &ArrayRef, rows: &Range<u64>, mask: &Mask) -> VortexResult<ArrayRef> {
136    let array = value.slice(usize::try_from(rows.start)?..usize::try_from(rows.end)?)?;
137    if mask.all_true() {
138        return Ok(array);
139    }
140    array.filter(mask.clone())
141}