Skip to main content

vortex_scan/plan/builtins/zoned/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::borrow::Cow;
5use std::fmt;
6use std::ops::Range;
7use std::sync::Arc;
8
9use parking_lot::RwLock;
10use vortex_array::ArrayRef;
11use vortex_array::EmptyMetadata;
12use vortex_array::IntoArray;
13use vortex_array::VortexSessionExecute;
14use vortex_array::aggregate_fn::AggregateFnRef;
15use vortex_array::arrays::BoolArray;
16use vortex_array::arrays::ConstantArray;
17use vortex_array::arrays::StructArray;
18use vortex_array::dtype::DType;
19use vortex_array::scalar::Scalar;
20use vortex_array::validity::Validity;
21use vortex_buffer::BitBufferMut;
22use vortex_error::VortexExpect;
23use vortex_error::VortexResult;
24use vortex_error::vortex_bail;
25use vortex_error::vortex_err;
26use vortex_expr::BoundExpression;
27use vortex_expr::stats::stat_fn::StatFn;
28use vortex_expr::traversal::NodeExt;
29use vortex_expr::traversal::Transformed;
30use vortex_expr::traversal::TraversalOrder;
31use vortex_functions::dynamic::DynamicExprUpdates;
32use vortex_mask::Mask;
33use vortex_session::VortexSession;
34use vortex_session::registry::CachedId;
35
36use crate::execution::operators::OnceSource;
37use crate::execution::operators::UNBOUNDED;
38use crate::execution::operators::WholeSource;
39use crate::execution::pipeline::Chain;
40use crate::execution::pipeline::Compiler;
41use crate::execution::zone_map::ZoneMap;
42use crate::plan::Eval;
43use crate::plan::Plan;
44use crate::plan::PlanId;
45use crate::plan::PlanParts;
46use crate::plan::PlanRef;
47use crate::plan::PlanSlots;
48use crate::plan::PlanVTable;
49use crate::plan::optimizer::PlanParentReduceRule;
50use crate::plan::optimizer::PlanReduceRule;
51
52const DATA: usize = 0;
53const ZONES: usize = 1;
54
55#[derive(Clone, Debug)]
56struct ZonedPruningState {
57    expression: BoundExpression,
58    /// The dtype of the column the zones summarise, which the expression is bound to.
59    column_dtype: DType,
60    /// Which zones the expression proves can be pruned, shared by every execution of this plan.
61    pruned_zones: Arc<PrunedZones>,
62}
63
64/// Which zones a pruning expression proves can be pruned, shared by every execution of a plan.
65///
66/// The zone table is read once and kept. An expression with dynamic comparisons, such as a top-N
67/// bound an engine tightens during the scan, is proven again over the kept zones whenever one of
68/// them changes, as the default scan's zoned reader does.
69pub(crate) struct PrunedZones {
70    updates: Option<DynamicExprUpdates>,
71    /// The zones, and the pruned zones as of an update version.
72    state: RwLock<Option<(ZoneMap, u64, Mask)>>,
73}
74
75impl PrunedZones {
76    fn new(expression: &BoundExpression) -> Self {
77        Self {
78            updates: DynamicExprUpdates::new(expression),
79            state: RwLock::new(None),
80        }
81    }
82
83    fn version(&self) -> u64 {
84        self.updates.as_ref().map_or(0, DynamicExprUpdates::version)
85    }
86
87    /// The pruned zones, proven again if a dynamic comparison changed, or `None` before any
88    /// execution read the zones.
89    pub(crate) fn get(
90        &self,
91        expression: &BoundExpression,
92        session: &VortexSession,
93    ) -> VortexResult<Option<Mask>> {
94        let version = self.version();
95        {
96            let state = self.state.read();
97            match &*state {
98                None => return Ok(None),
99                Some((_, proven, pruned)) if *proven >= version => return Ok(Some(pruned.clone())),
100                Some(_) => {}
101            }
102        }
103        let mut state = self.state.write();
104        let Some((zones, proven, pruned)) = state.as_mut() else {
105            return Ok(None);
106        };
107        if *proven < version {
108            *pruned = zones.prune(expression, session)?;
109            *proven = version;
110        }
111        Ok(Some(pruned.clone()))
112    }
113
114    /// Proves `expression` over `zones` and keeps both, unless another execution did first.
115    pub(crate) fn init(
116        &self,
117        zones: ZoneMap,
118        expression: &BoundExpression,
119        session: &VortexSession,
120    ) -> VortexResult<Mask> {
121        let version = self.version();
122        let pruned = zones.prune(expression, session)?;
123        let mut state = self.state.write();
124        if state.is_none() {
125            *state = Some((zones, version, pruned.clone()));
126        }
127        Ok(pruned)
128    }
129}
130
131impl fmt::Debug for PrunedZones {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.debug_struct("PrunedZones")
134            .field("dynamic", &self.updates.is_some())
135            .field("read", &self.state.read().is_some())
136            .finish()
137    }
138}
139
140/// Zoned-plan-specific data.
141#[derive(Clone, Debug)]
142pub struct ZonedData {
143    zone_len: u64,
144    /// The aggregate functions whose results the zone table stores, in field order.
145    aggregate_fns: Arc<[AggregateFnRef]>,
146    pruning: Option<ZonedPruningState>,
147}
148
149/// Reads data alongside the zone statistics summarising it.
150///
151/// Its zone table stores aggregate states supplied by the source adapter. An expression containing abstract statistic functions can rewrite it into a
152/// pruning plan whose data slot is absent, retaining only the zone-statistics child; a plan that
153/// reads the data is optimized to its data child alone. Its slots are always `[data, zones]`.
154#[derive(Clone, Debug)]
155pub struct Zoned;
156
157/// A plan that pairs data with its zone statistics or represents a zone-backed pruning proof.
158pub type ZonedPlan = Plan<Zoned>;
159
160impl ZonedPlan {
161    /// Pairs data and statistics slots with their zone length and aggregate functions.
162    pub fn from_slots(
163        dtype: DType,
164        row_count: u64,
165        slots: PlanSlots,
166        zone_len: u64,
167        aggregate_fns: Arc<[AggregateFnRef]>,
168    ) -> Self {
169        PlanParts {
170            vtable: Zoned,
171            dtype,
172            row_count,
173            slots,
174            data: ZonedData {
175                zone_len,
176                aggregate_fns,
177                pruning: None,
178            },
179        }
180        .into_typed()
181    }
182
183    /// Creates a zoned plan over `data` summarised by `zones` of `zone_len` rows each, whose
184    /// fields hold the results of `aggregate_fns`.
185    pub fn new(
186        data: PlanRef,
187        zones: PlanRef,
188        zone_len: u64,
189        aggregate_fns: Arc<[AggregateFnRef]>,
190    ) -> Self {
191        let dtype = data.dtype().clone();
192        let row_count = data.row_count();
193        Self::from_slots(
194            dtype,
195            row_count,
196            [data, zones].into(),
197            zone_len,
198            aggregate_fns,
199        )
200    }
201
202    /// Returns the number of rows each zone summarises.
203    pub fn zone_len(&self) -> u64 {
204        self.data().zone_len
205    }
206
207    /// Returns the aggregate functions whose results the zone table stores.
208    pub fn aggregate_fns(&self) -> &Arc<[AggregateFnRef]> {
209        &self.data().aggregate_fns
210    }
211
212    /// Returns the dtype of the column the zones summarise, when this is a pruning plan.
213    pub fn pruning_column_dtype(&self) -> Option<&DType> {
214        self.data()
215            .pruning
216            .as_ref()
217            .map(|state| &state.column_dtype)
218    }
219
220    /// Returns the cache of pruned zones shared by every execution of this pruning plan.
221    pub(crate) fn pruned_zones(&self) -> Option<&Arc<PrunedZones>> {
222        self.data()
223            .pruning
224            .as_ref()
225            .map(|state| &state.pruned_zones)
226    }
227
228    /// Returns the plan producing the summarised data, unless this is a pruning plan.
229    pub fn data_plan(&self) -> VortexResult<Option<PlanRef>> {
230        self.slot(DATA)
231    }
232
233    /// Returns the plan producing the zone statistics.
234    pub fn zones_plan(&self) -> VortexResult<PlanRef> {
235        self.slot_required(ZONES)
236    }
237
238    /// Returns whether this plan represents a zone-backed pruning proof.
239    pub fn is_pruning(&self) -> bool {
240        self.data().pruning.is_some()
241    }
242
243    /// Returns the abstract pruning proof carried by this plan, when present.
244    pub fn pruning_expression(&self) -> Option<&BoundExpression> {
245        self.data().pruning.as_ref().map(|state| &state.expression)
246    }
247
248    fn with_pruning(&self, expression: BoundExpression) -> VortexResult<Option<Self>> {
249        if self.data().zone_len == 0 || self.is_pruning() {
250            return Ok(None);
251        }
252        let mut data = self.data().clone();
253        data.pruning = Some(ZonedPruningState {
254            expression: expression.clone(),
255            column_dtype: self.dtype().clone(),
256            pruned_zones: Arc::new(PrunedZones::new(&expression)),
257        });
258        Ok(Some(
259            PlanParts {
260                vtable: Zoned,
261                dtype: expression.dtype().clone(),
262                row_count: self.row_count(),
263                slots: [None, self.slots()[ZONES].clone()].into_iter().collect(),
264                data,
265            }
266            .into_typed(),
267        ))
268    }
269}
270
271impl PlanVTable for Zoned {
272    type PlanData = ZonedData;
273    type Metadata = EmptyMetadata;
274
275    fn id(&self) -> PlanId {
276        static ID: CachedId = CachedId::new("vortex.plan.zoned");
277        *ID
278    }
279
280    fn fmt(plan: &Plan<Self>, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
281        if let Some(expression) = plan.pruning_expression() {
282            write!(formatter, " prune={expression}")?;
283        }
284        Ok(())
285    }
286
287    fn metadata(_plan: &Plan<Self>) -> Option<Self::Metadata> {
288        None
289    }
290
291    fn with_slots(
292        plan: &Plan<Self>,
293        slots: &PlanSlots,
294        data: &mut Self::PlanData,
295    ) -> VortexResult<()> {
296        slots.check_len("Zoned", ZONES + 1)?;
297        if slots[ZONES].is_none() {
298            vortex_bail!("Zoned plan has no zones child");
299        }
300        if plan.is_pruning() {
301            if slots[DATA].is_some() {
302                vortex_bail!("Zoned pruning plan has a data child");
303            }
304            // New zones may prove different zones, so the proof of the old ones is not kept.
305            if let Some(state) = &mut data.pruning {
306                state.pruned_zones = Arc::new(PrunedZones::new(&state.expression));
307            }
308            return Ok(());
309        }
310
311        let data = slots.required(DATA)?;
312        if data.dtype() != plan.dtype() || data.row_count() != plan.row_count() {
313            vortex_bail!("Zoned data child shape does not match the plan output");
314        }
315        Ok(())
316    }
317
318    fn slot_name(_plan: &Plan<Self>, slot: usize) -> Cow<'_, str> {
319        match slot {
320            DATA => Cow::Borrowed("data"),
321            ZONES => Cow::Borrowed("zones"),
322            _ => Cow::Owned(format!("slot[{slot}]")),
323        }
324    }
325
326    /// A data plan compiles as its data child. A pruning plan whose zones an earlier execution
327    /// proved emits the expanded result; otherwise it collects the whole zone table, proves the
328    /// expression over it, keeps the result, and emits it expanded to the selected rows.
329    fn compile(
330        plan: &Plan<Self>,
331        rows: Range<u64>,
332        mask: &Mask,
333        compiler: &mut Compiler<'_>,
334    ) -> VortexResult<Option<Chain>> {
335        if !plan.is_pruning() {
336            let Some(data) = plan.data_plan()? else {
337                vortex_bail!("Zoned plan has no data child");
338            };
339            return compiler.compile(&data, rows, mask);
340        }
341        if mask.all_false() {
342            return Ok(None);
343        }
344        let expression = plan
345            .pruning_expression()
346            .ok_or_else(|| vortex_err!("Zoned pruning plan has no expression"))?;
347        if let Some(pruned) = pruned_zones(plan)?.get(expression, compiler.session())? {
348            return Ok(Some(Chain::new(OnceSource::new(expand_zones(
349                plan, &rows, mask, &pruned,
350            )?))));
351        }
352        let zones = plan.zones_plan()?;
353        let count = usize::try_from(zones.row_count())?;
354        let Some(chain) = compiler.compile(&zones, 0..zones.row_count(), &Mask::new_true(count))?
355        else {
356            vortex_bail!("Zoned pruning plan has an empty zone table");
357        };
358        let zoned = plan.clone();
359        let mask = mask.clone();
360        let source = WholeSource::new(zones.dtype().clone(), move |table, cx| {
361            let pruned = prune_zones(&zoned, cx.session(), table)?;
362            expand_zones(&zoned, &rows, &mask, &pruned)
363        });
364        Ok(Some(compiler.join_with(vec![chain], |_| UNBOUNDED, source)))
365    }
366}
367
368/// The per-zone results kept on a pruning `plan`.
369fn pruned_zones(plan: &ZonedPlan) -> VortexResult<&Arc<PrunedZones>> {
370    plan.pruned_zones()
371        .ok_or_else(|| vortex_err!("Zone pruning needs a pruning plan"))
372}
373
374/// Builds the zone map from the zone table and proves the expression over it, one value per
375/// zone, keeping both on the plan.
376fn prune_zones(plan: &ZonedPlan, session: &VortexSession, table: ArrayRef) -> VortexResult<Mask> {
377    let table = table.execute::<StructArray>(&mut session.create_execution_ctx())?;
378    let (Some(expression), Some(column_dtype)) =
379        (plan.pruning_expression(), plan.pruning_column_dtype())
380    else {
381        vortex_bail!("Zone pruning needs a pruning plan");
382    };
383    let zone_map = ZoneMap::try_new(
384        column_dtype.clone(),
385        table,
386        Arc::clone(plan.aggregate_fns()),
387        plan.zone_len(),
388        plan.row_count(),
389    )?;
390    pruned_zones(plan)?.init(zone_map, expression, session)
391}
392
393/// Expands the per-zone result to one value per row of `rows` that `mask` selects.
394///
395/// Every row of a zone shares the zone's value, so the rows are filled a zone at a time and the
396/// selection is applied once at the end.
397fn expand_zones(
398    plan: &ZonedPlan,
399    rows: &Range<u64>,
400    mask: &Mask,
401    pruned: &Mask,
402) -> VortexResult<ArrayRef> {
403    let zone_len = plan.zone_len();
404    let start_zone = usize::try_from(rows.start / zone_len)?;
405    let end_zone = usize::try_from(rows.end.div_ceil(zone_len))?;
406    let selected_zones = pruned.slice(start_zone..end_zone);
407    if selected_zones.all_true() || selected_zones.all_false() {
408        let scalar = Scalar::from(selected_zones.all_true()).cast(plan.dtype())?;
409        return Ok(ConstantArray::new(scalar, mask.true_count()).into_array());
410    }
411    let mut bits = BitBufferMut::with_capacity(mask.len());
412    let mut row = rows.start;
413    while row < rows.end {
414        let zone = usize::try_from(row / zone_len).vortex_expect("zone index must fit in usize");
415        let zone_end = ((row / zone_len) + 1) * zone_len;
416        let end = zone_end.min(rows.end);
417        bits.append_n(
418            pruned.value(zone),
419            usize::try_from(end - row).vortex_expect("zone rows must fit in usize"),
420        );
421        row = end;
422    }
423    let validity = if plan.dtype().is_nullable() {
424        Validity::AllValid
425    } else {
426        Validity::NonNullable
427    };
428    let array = BoolArray::try_new(bits.freeze(), validity)?.into_array();
429    if mask.all_true() {
430        return Ok(array);
431    }
432    array.filter(mask.clone())
433}
434
435/// Rewrites an abstract statistic expression over a zoned plan into its pruning state.
436#[derive(Debug)]
437pub(crate) struct ExpressionZonedRule;
438
439impl PlanParentReduceRule<Zoned> for ExpressionZonedRule {
440    type Parent = Eval;
441
442    fn reduce_parent(
443        &self,
444        child: &ZonedPlan,
445        parent: &Plan<Eval>,
446        _child_idx: usize,
447        _session: &VortexSession,
448    ) -> VortexResult<Option<PlanRef>> {
449        if !is_zone_pruning(parent)? {
450            return Ok(None);
451        }
452        Ok(child
453            .with_pruning(parent.expression().clone())?
454            .map(Plan::into_plan))
455    }
456}
457
458/// Whether `eval` is a boolean expression over abstract statistics alone, which a zone table can
459/// prune without reading the data it summarises.
460pub fn is_zone_pruning(eval: &Plan<Eval>) -> VortexResult<bool> {
461    let mut contains_stat = false;
462    let mut contains_root = false;
463    eval.expression().clone().transform_down(|expression| {
464        if expression
465            .as_scalar()
466            .is_some_and(|scalar_fn| scalar_fn.is::<StatFn>())
467        {
468            contains_stat = true;
469            return Ok(Transformed {
470                value: expression,
471                order: TraversalOrder::Skip,
472                changed: false,
473            });
474        }
475        contains_root |= expression.is_root();
476        Ok(Transformed::no(expression))
477    })?;
478    Ok(eval.dtype().is_boolean() && contains_stat && !contains_root)
479}
480
481/// Replaces a zoned data plan by its data: a scan reads the data through it and never its zone
482/// table. Pruning plans are derived from the filter over the lowered plan before this runs, so
483/// an optimized plan carries a zone table only where a pruning plan reads it.
484#[derive(Debug)]
485pub(crate) struct ZonedDataRule;
486
487impl PlanReduceRule<Zoned> for ZonedDataRule {
488    fn reduce(
489        &self,
490        plan: &Plan<Zoned>,
491        _session: &VortexSession,
492    ) -> VortexResult<Option<PlanRef>> {
493        plan.data_plan()
494    }
495}
496
497#[cfg(test)]
498mod tests;